From 27059e21500fe46203a678f56f77763f1ab97c9b Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:52:08 +0000 Subject: [PATCH 1/8] Match TypeScript 4.1.1 ProtoWallet HMAC keys, linkage proofs and counterparties createHMAC keys HMAC-SHA256 with the minimal-length X coordinate, as @bsv/sdk 4.1.1 and earlier TypeScript SDKs do. verifyHMAC also accepts tags made with the 32-byte padded key, so earlier Swift and Go tags stay valid. AES-GCM keeps the 32-byte key (COMP-064). The counterparty linkage proof writes z as 32 bytes, and revealSpecificKeyLinkage accepts self and anyone and returns the resolved key. --- .../Rulings/COMP-064-Wallet-HMAC-Key.md | 41 ++++++++++ .../BSVWallet/ABI/WalletCertificateABI.swift | 6 +- Sources/BSVWallet/Crypto/ProtoWallet.swift | 38 ++++++--- .../BSVWallet/Crypto/WalletKeyDeriver.swift | 10 +++ Tests/BSVWalletTests/ProtoWalletTests.swift | 81 ++++++++++++++++++- 5 files changed, 157 insertions(+), 19 deletions(-) create mode 100644 Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md diff --git a/Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md b/Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md new file mode 100644 index 0000000..db130c7 --- /dev/null +++ b/Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md @@ -0,0 +1,41 @@ +# COMP-064: Wallet HMAC key length + +Status: Accepted. Replaces the HMAC part of COMP-002. + +## Context + +BRC-2 and BRC-56 key wallet HMACs with the X coordinate of the shared +type-42 point. COMP-002 keyed both AES-GCM and HMAC with the 32-byte +zero-padded X coordinate, following Go v1.3.3. + +`@bsv/sdk` 4.1.1 keys HMAC-SHA256 with the minimal-length big-endian X +coordinate (`SymmetricKey.toArray()` with no length). TypeScript SDK 2 and 3 +did the same, so every TypeScript wallet and app issues tags this way. Its +test `packages/sdk/src/wallet/__tests/ProtoWallet.brc56-hmac-key.test.ts` +pins six vectors and rejects tags made with the padded key. The two keys +differ only when the X coordinate starts with a zero byte, about one key in +256. For those keys a Swift tag failed TypeScript verification, and a +TypeScript tag failed Swift verification. + +## Ruling + +- `ProtoWallet.createHMAC` keys HMAC-SHA256 with the minimal-length X + coordinate. +- `ProtoWallet.verifyHMAC` accepts a tag made with the minimal key or with the + 32-byte padded key. The padded check runs only when the two keys differ. +- AES-256-GCM encryption and decryption keep the 32-byte key. TypeScript + 4.1.1 also uses the 32-byte key there. + +## Reason + +TypeScript wallets and apps are the 1Sat wallet's peers, so their HMAC tags +must verify in Swift and Swift tags must verify in TypeScript. Accepting the +padded tag keeps tags that earlier Swift releases and Go v1.3.3 peers created +valid. This is a deliberate leniency: TypeScript 4.1.1 rejects the padded tag. + +## Tests + +`ProtoWalletTests.testBRC56HMACKeyVectorsMatchTypeScript` checks all six +TypeScript vectors: the derived key, the created tag, verification of the tag, +and acceptance of each padded-key tag. The published BRC-2 HMAC vector is +unchanged because its X coordinate has no leading zero byte. diff --git a/Sources/BSVWallet/ABI/WalletCertificateABI.swift b/Sources/BSVWallet/ABI/WalletCertificateABI.swift index 1354251..c660385 100644 --- a/Sources/BSVWallet/ABI/WalletCertificateABI.swift +++ b/Sources/BSVWallet/ABI/WalletCertificateABI.swift @@ -74,11 +74,7 @@ public struct WalletRevealSpecificKeyLinkageRequest: Equatable, Sendable { keyID: WalletKeyID, privilege: WalletPrivilege = .standard ) throws { - guard case .publicKey = counterparty else { - throw WalletABIError.invalidFieldRelation( - "specific key linkage requires a concrete counterparty public key" - ) - } + // `self` and `anyone` resolve to concrete keys, as @bsv/sdk 4.1.1 does (W6). self.counterparty = counterparty self.verifier = verifier self.protocolID = protocolID diff --git a/Sources/BSVWallet/Crypto/ProtoWallet.swift b/Sources/BSVWallet/Crypto/ProtoWallet.swift index 5a21f91..5163988 100644 --- a/Sources/BSVWallet/Crypto/ProtoWallet.swift +++ b/Sources/BSVWallet/Crypto/ProtoWallet.swift @@ -97,13 +97,12 @@ public struct ProtoWallet: for: request.counterparty, nonce: proofNonce ) - // BRC-97 defines z as a variable-width big-endian integer. The live - // TypeScript SDK emits its minimal representation; Go's fixed 32-byte - // padding differs only when z has leading zero bytes. - let encodedResponse = Array(proof.response.drop(while: { $0 == 0 })) + // R(33) || S'(33) || z(32): TypeScript 4.x (`ProtoWallet.ts` + // `z.toArray('be', 32)`) and Go both pad z to 32 bytes, so the proof + // is always 98 bytes and verifiers may slice fixed offsets. let proofBytes = proof.noncePublicKey.compressedBytes + proof.nonceSharedSecret.compressedBytes - + encodedResponse + + proof.response let protocolID = try WalletProtocolID( securityLevel: .everyAppAndCounterparty, name: "counterparty linkage revelation" @@ -135,9 +134,9 @@ public struct ProtoWallet: _ request: WalletRevealSpecificKeyLinkageRequest ) async throws -> WalletRevealSpecificKeyLinkageResult { try requireStandardPrivilege(request.privilege) - guard case .publicKey(let counterparty) = request.counterparty else { - throw WalletCryptoError.keyDerivationFailed - } + // TypeScript 4.x resolves `self` to the identity key and `anyone` to the + // public key of private key 1, and its clients reject any other answer. + let counterparty = try keyDeriver.resolvedCounterparty(request.counterparty) let linkage = try keyDeriver.revealSpecificSecret( counterparty: request.counterparty, protocolID: request.protocolID, @@ -219,7 +218,7 @@ public struct ProtoWallet: keyID: request.keyID, counterparty: request.counterparty ) - let code = BSVHashing.hmacSHA256(request.data, key: key.bytes) + let code = BSVHashing.hmacSHA256(request.data, key: walletHMACKey(key.bytes)) do { return WalletCreateHMACResult(hmac: try WalletHMAC(bytes: code.bytes)) } catch { @@ -235,11 +234,21 @@ public struct ProtoWallet: keyID: request.keyID, counterparty: request.counterparty ) - return WalletVerifyHMACResult(valid: BSVHashing.isValidHMACSHA256( + // Tags from TypeScript wallets and from current Swift use the minimal + // key; tags Swift created before the switch used the padded 32-byte + // key. Both stay valid. The two keys differ only when the shared X + // coordinate has a leading zero byte. + let minimalKey = walletHMACKey(key.bytes) + let valid = BSVHashing.isValidHMACSHA256( + request.hmac.bytes, + authenticating: request.data, + key: minimalKey + ) || (minimalKey.count != key.bytes.count && BSVHashing.isValidHMACSHA256( request.hmac.bytes, authenticating: request.data, key: key.bytes )) + return WalletVerifyHMACResult(valid: valid) } public func createSignature( @@ -300,6 +309,15 @@ public struct ProtoWallet: public var customMirror: Mirror { walletEmptyMirror(self) } } +/// The BRC-56 HMAC key: the shared X coordinate as its minimal big-endian +/// integer (leading zero bytes removed; zero is one `00` byte). This matches +/// TypeScript `@bsv/sdk` 4.1.1 `ProtoWallet.createHmac`, which keys HMAC-SHA256 +/// with `SymmetricKey.toArray()`. BRC-2 encryption keeps the 32-byte key. +func walletHMACKey(_ paddedKey: [UInt8]) -> [UInt8] { + let minimal = Array(paddedKey.drop(while: { $0 == 0 })) + return minimal.isEmpty ? [0] : minimal +} + private func walletCurrentISO8601Timestamp() -> String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] diff --git a/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift b/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift index 0677dae..feb3e92 100644 --- a/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift +++ b/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift @@ -152,6 +152,16 @@ public struct WalletKeyDeriver: "\(protocolID.securityLevel.rawValue)-\(protocolID.name)-\(keyID.value)" } + /// The public key a counterparty stands for: the identity key for `self` + /// and the public key of private key 1 for `anyone`. + public func resolvedCounterparty(_ counterparty: WalletCounterparty) throws -> PublicKey { + do { + return try normalizedCounterparty(counterparty) + } catch { + throw WalletCryptoError.keyDerivationFailed + } + } + private func normalizedCounterparty(_ counterparty: WalletCounterparty) throws -> PublicKey { switch counterparty { case .self: diff --git a/Tests/BSVWalletTests/ProtoWalletTests.swift b/Tests/BSVWalletTests/ProtoWalletTests.swift index fcbd0c9..763b35d 100644 --- a/Tests/BSVWalletTests/ProtoWalletTests.swift +++ b/Tests/BSVWalletTests/ProtoWalletTests.swift @@ -214,7 +214,10 @@ final class ProtoWalletTests: XCTestCase { )) } - func testCounterpartyProofSerializesResponseAsBRC97MinimalInteger() async throws { + /// `@bsv/sdk` 4.1.1 writes z as `linkageProof.z.toArray('be', 32)` + /// (packages/sdk/src/wallet/ProtoWallet.ts:196), so a response with a + /// leading zero byte keeps it and the proof is always 98 bytes (W7). + func testCounterpartyProofSerializesResponseAsFixed32ByteInteger() async throws { let proverKey = try PrivateKey(scalar(7)) let counterpartyKey = try PrivateKey(scalar(13)) let verifierKey = try PrivateKey(scalar(17)) @@ -263,9 +266,9 @@ final class ProtoWalletTests: XCTestCase { counterparty: .publicKey(proverKey.publicKey), ciphertext: result.encryptedLinkageProof.bytes )).plaintext - let expectedResponse = Array(selectedResponse.drop(while: { $0 == 0 })) - XCTAssertEqual(Array(proofBytes.dropFirst(66)), expectedResponse) - XCTAssertLessThan(proofBytes.count, 98) + XCTAssertEqual(selectedResponse.first, 0) + XCTAssertEqual(Array(proofBytes.dropFirst(66)), selectedResponse) + XCTAssertEqual(proofBytes.count, 98) } func testSpecificKeyLinkageMatchesBRC69BRC72AndProofTypeZero() async throws { @@ -444,6 +447,76 @@ final class ProtoWalletTests: XCTestCase { } } + /// BRC-56 HMAC key vectors from `@bsv/sdk` 4.1.1 + /// (packages/sdk/src/wallet/__tests/ProtoWallet.brc56-hmac-key.test.ts:9-70). + /// Tags use the minimal-length X coordinate as the HMAC key (W1, COMP-064). + /// TypeScript rejects `rejectedTag` (made with the zero-padded 32-byte key); + /// Swift still accepts it so tags Swift and Go peers made before the switch + /// keep verifying. + func testBRC56HMACKeyVectorsMatchTypeScript() async throws { + let rootKey = try PrivateKey(walletTestHex( + "f0efba88c117ca2614554bb676d743f413822a31e3c8d70cfcc5fff119d20a07" + )) + XCTAssertEqual( + Hex.encode(rootKey.publicKey.compressedBytes), + "035818cd7cc614fea816c8b39eebe6e43cafc635451ec5a873f8757b418aaae91a" + ) + let counterparty = try PublicKey(walletTestHex( + "03458d551018414b8fe1adbcef2d0afc17e1074bfab3fdde3e1b0750bdde58a9a7" + )) + let protocolID = try WalletProtocolID(securityLevel: .everyAppAndCounterparty, name: "hmac key vectors") + let data = try walletTestHex("4252432d353620484d41432074657374") + let vectors: [(WalletCounterparty, String, String, String, String?)] = [ + (.self, "k0", + "b1273850ff41cee365a4d590e3c323822129f66c5a9b2eacb8b9e790e000e396", + "99455edf49ea2156f6109466fb344c3027d4c14485581a50bf5ff0850328a269", nil), + (.self, "k95", + "0c82ac78dc853158f24883ccfda332be6ba34f821765357cc4ef2a190a28fd", + "3a968ebaa25eaa4b1cfad138f96105bb1eb738defc066d01e37b32595900d48b", + "054a0fc6a3b0e21b31dc627fb1d645f2eea4127dff71eac95b1f71b7cb13c787"), + (.self, "k91538", + "9dc11102cc72eca3c6e4e232460eac581e9b2cee1bb35c395b635d3f6393", + "5a8b84fb2a7d9ce7b12feb8319f14dc6169e0be005a1a8e58d9b9b2d1ac29d47", + "ff43127cb1ddfbd19776d01ce34b8c3e83916b51fa55ac045a355b731e6999f5"), + (.publicKey(counterparty), "k0", + "1896e0210afac8dbb4ca3bd4ea25c8377d0352ab83e62fe6ffabeca78c1a6113", + "986af579272261acf3e890bb1650124b0dfbc0b1edacda202f8ed0c3b876c072", nil), + (.publicKey(counterparty), "k497", + "1829e1dd58fc2c45b6edcbb277eecdecbab1c884b42fd779e131fea5881b45", + "3a5ea2bf5bcc9bc1461041737384bf258b0a3e5a475fb281a19c2972cdb1cff6", + "aa39467c48a116ffb00fd7b56ff158bd9af37d1298df2f031c0125458c30f574"), + (.publicKey(counterparty), "k29510", + "a52a35523175d6c181e90f463a27cdbf70f4ecf055e912d6fc24ac7d0e3c", + "ecca769bb17b1775ce8ae4326fe721ba0f7ba272300741bf4a5b068cf0cebd60", + "2677674035f1aaac3219b3405cf8569ec07922a3ceffbd4f7c8a7948b2d3c553"), + ] + let wallet = ProtoWallet(rootKey: rootKey) + let deriver = WalletKeyDeriver(rootKey: rootKey) + for (party, keyIDText, hmacKey, tag, paddedTag) in vectors { + let keyID = try WalletKeyID(keyIDText) + let symmetric = try deriver.deriveSymmetricKey( + protocolID: protocolID, keyID: keyID, counterparty: party + ) + XCTAssertEqual(Hex.encode(walletHMACKey(symmetric.bytes)), hmacKey, keyIDText) + let created = try await wallet.createHMAC(WalletCreateHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: party, data: data + )) + XCTAssertEqual(Hex.encode(created.hmac.bytes), tag, keyIDText) + let valid = try await wallet.verifyHMAC(WalletVerifyHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: party, data: data, + hmac: WalletHMAC(bytes: walletTestHex(tag)) + )).valid + XCTAssertTrue(valid, keyIDText) + if let paddedTag { + let paddedValid = try await wallet.verifyHMAC(WalletVerifyHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: party, data: data, + hmac: WalletHMAC(bytes: walletTestHex(paddedTag)) + )).valid + XCTAssertTrue(paddedValid, "padded-key tag \(keyIDText)") + } + } + } + func testHMACMutationsPermissionsAndPublicKeys() async throws { let wallet = ProtoWallet(rootKey: try walletTestPrivateKey(42)) let protocolID = try walletTestProtocol() From 6cb3761b527d145c0ba2cbc7796345c0389942b7 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:52:08 +0000 Subject: [PATCH 2/8] Speak the @bsv/sdk 4.1.1 wallet wire TypeScript wallets and apps are the 1Sat wallet's peers, so the binary wallet wire now follows @bsv/sdk 4.1.1 where pinned Go v1.3.3 differs: - createAction and signAction results use the TypeScript layout with display-order txids; the txid and signable transaction may be absent - list totals count every match and records run to the end of the frame - listOutputs totalOutputs is UInt64 for BRC-112 balance baskets - the optional spendable listOutputs extension - abortAction refusal is error code 8 - false verifications, unknown calls (including the call-29 probe) and malformed requests are answered in-band with the TypeScript messages - maps arrive in any order, omitted booleans and counterparties use the TypeScript sentinels, empty list entries have length 0 - discovery seekPermission defaults to true; JSON errors carry code 1 - JSON keyring {} reads as no keyring Go-oracle tests now record the Go differences instead of pinning them. --- Sources/BSVWallet/ABI/WalletActionABI.swift | 23 +- .../BSVWallet/ABI/WalletRequestHandling.swift | 4 +- .../JSON/WalletBRC100ActionJSON.swift | 6 +- .../JSON/WalletBRC100CertificateJSON.swift | 6 +- .../JSON/WalletBRC100JSONCodec.swift | 5 +- .../Substrates/WalletWireProcessor.swift | 127 ++++-- .../Substrates/WalletWireTransceiver.swift | 8 +- .../Substrates/WalletWireTransport.swift | 2 +- .../Wire/WalletWireActionCodec.swift | 158 ++++--- .../Wire/WalletWireActionPrimitives.swift | 43 +- .../Wire/WalletWireActionResultCodec.swift | 405 ++++++++++-------- .../Wire/WalletWireActionTypes.swift | 20 +- .../Wire/WalletWireCertificateCodec.swift | 9 +- .../WalletWireCertificatePrimitives.swift | 13 +- .../WalletWireCertificateResultCodec.swift | 113 +++-- Sources/BSVWallet/Wire/WalletWireCodec.swift | 27 +- .../BSVWallet/Wire/WalletWireFailures.swift | 115 +++++ .../BSVWallet/Wire/WalletWirePrimitives.swift | 19 +- Sources/BSVWallet/Wire/WalletWireTypes.swift | 4 +- .../WalletWireActionGoOracleTests.swift | 71 ++- .../WalletWireCertificateGoOracleTests.swift | 15 +- .../WalletWireGoOracleTests.swift | 18 +- .../Substrates/WalletWireSubstrateTests.swift | 26 +- .../WalletWireActionAdversarialTests.swift | 282 ++++++------ .../Wire/WalletWireAdversarialTests.swift | 36 +- ...alletWireCertificateAdversarialTests.swift | 30 +- .../Wire/WalletWireCertificateTests.swift | 5 +- .../Wire/WalletWireKeyQueryTests.swift | 14 +- .../WalletWireTypeScript41VectorTests.swift | 295 +++++++++++++ 29 files changed, 1351 insertions(+), 548 deletions(-) create mode 100644 Sources/BSVWallet/Wire/WalletWireFailures.swift create mode 100644 Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift diff --git a/Sources/BSVWallet/ABI/WalletActionABI.swift b/Sources/BSVWallet/ABI/WalletActionABI.swift index 0353601..df66bf9 100644 --- a/Sources/BSVWallet/ABI/WalletActionABI.swift +++ b/Sources/BSVWallet/ABI/WalletActionABI.swift @@ -290,9 +290,6 @@ public struct WalletCreateActionResult: sendWithResults.count, kind: "send-with results", maximum: limits.maximumCollectionCount ) } - guard transactionID != nil || transaction != nil || signableTransaction != nil else { - throw WalletABIError.invalidFieldRelation("createAction result has no transaction value") - } self.transactionID = transactionID self.transaction = transaction self.noSendChange = noSendChange @@ -381,9 +378,6 @@ public struct WalletSignActionResult: sendWithResults: [WalletSendWithResult]? = nil, limits: WalletABILimits = .standard ) throws { - guard transactionID != nil || transaction != nil else { - throw WalletABIError.invalidFieldRelation("signAction result has no transaction value") - } if let sendWithResults { try walletABIRequireCount( sendWithResults.count, kind: "send-with results", maximum: limits.maximumCollectionCount @@ -685,11 +679,14 @@ public struct WalletListOutputsRequest: Equatable, Sendable { public struct WalletListOutputsResult: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { - public let totalOutputs: UInt32 + /// The number of matching outputs, or for a BRC-112 balance basket + /// (`walletIsBalanceBasket`) the balance in satoshis. A balance may exceed + /// `UInt32.max`; an output count may not. + public let totalOutputs: UInt64 public let beef: BEEF? public let outputs: [WalletOutput] public init( - totalOutputs: UInt32, + totalOutputs: UInt64, beef: BEEF? = nil, outputs: [WalletOutput], limits: WalletABILimits = .standard @@ -860,3 +857,13 @@ public struct WalletInternalizeActionResult: Equatable, Sendable { public let accepted: Bool public init(accepted: Bool) { self.accepted = accepted } } + +/// 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. +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 ") +} diff --git a/Sources/BSVWallet/ABI/WalletRequestHandling.swift b/Sources/BSVWallet/ABI/WalletRequestHandling.swift index c27051e..f7a71d7 100644 --- a/Sources/BSVWallet/ABI/WalletRequestHandling.swift +++ b/Sources/BSVWallet/ABI/WalletRequestHandling.swift @@ -75,9 +75,9 @@ public enum WalletRequest: case .action(.listOutputs(let value)): return makeSeekPermissionMetadata(rawValue: value.seekPermission, defaultValue: true) case .certificate(.discoverByIdentityKey(let value)): - return makeSeekPermissionMetadata(rawValue: value.seekPermission, defaultValue: false) + return makeSeekPermissionMetadata(rawValue: value.seekPermission, defaultValue: true) case .certificate(.discoverByAttributes(let value)): - return makeSeekPermissionMetadata(rawValue: value.seekPermission, defaultValue: false) + return makeSeekPermissionMetadata(rawValue: value.seekPermission, defaultValue: true) case .keyQuery(.getPublicKey(let value)): return makeSeekPermissionMetadata(rawValue: value.access.seekPermission, defaultValue: true) case .keyQuery(.encrypt(let value)): diff --git a/Sources/BSVWallet/JSON/WalletBRC100ActionJSON.swift b/Sources/BSVWallet/JSON/WalletBRC100ActionJSON.swift index 37d5f4e..30d80f0 100644 --- a/Sources/BSVWallet/JSON/WalletBRC100ActionJSON.swift +++ b/Sources/BSVWallet/JSON/WalletBRC100ActionJSON.swift @@ -343,14 +343,14 @@ private struct ActionInputDTO: Codable { private struct ActionOutputDTO: Codable { let satoshis: UInt64; let lockingScript: String?; let spendable: Bool; let customInstructions: String? - let tags: [String]; let outputIndex: UInt32; let outputDescription: String; let basket: String + let tags: [String]?; let outputIndex: UInt32; let outputDescription: String; let basket: String init(_ value: WalletActionOutput) { satoshis = value.satoshis; lockingScript = value.lockingScript.map(Hex.encode); spendable = value.spendable customInstructions = value.customInstructions; tags = value.tags; outputIndex = value.outputIndex outputDescription = value.outputDescription; basket = value.basket } func model(_ codec: WalletBRC100JSONCodec) throws -> WalletActionOutput { - try .init(satoshis: satoshis, lockingScript: try lockingScript.map { try decodeCanonicalHex($0, maximum: codec.abiLimits.maximumBytePayloadCount) }, spendable: spendable, customInstructions: customInstructions, tags: tags, outputIndex: outputIndex, outputDescription: outputDescription, basket: basket, limits: codec.abiLimits) + try .init(satoshis: satoshis, lockingScript: try lockingScript.map { try decodeCanonicalHex($0, maximum: codec.abiLimits.maximumBytePayloadCount) }, spendable: spendable, customInstructions: customInstructions, tags: tags ?? [], outputIndex: outputIndex, outputDescription: outputDescription, basket: basket, limits: codec.abiLimits) } } @@ -419,7 +419,7 @@ private struct ListOutputsDTO: Codable { func model(_ codec: WalletBRC100JSONCodec) throws -> WalletListOutputsRequest { try .init(basket: basket, tags: tags ?? [], tagQueryMode: tagQueryMode, include: include, includeCustomInstructions: includeCustomInstructions, includeTags: includeTags, includeLabels: includeLabels, pagination: .init(limit: limit, offset: offset), seekPermission: seekPermission, limits: codec.abiLimits) } } private struct ListOutputsResultDTO: Codable { - let totalOutputs: UInt32; let BEEF: [UInt8]?; let outputs: [OutputDTO] + let totalOutputs: UInt64; let BEEF: [UInt8]?; let outputs: [OutputDTO] init(_ value: WalletListOutputsResult, codec: WalletBRC100JSONCodec) throws { totalOutputs = value.totalOutputs; BEEF = try value.beef?.serialized(limits: codec.beefLimits); outputs = value.outputs.map(OutputDTO.init) } func model(_ codec: WalletBRC100JSONCodec) throws -> WalletListOutputsResult { try .init(totalOutputs: totalOutputs, beef: try BEEF.map { try BSVTransaction.BEEF(bytes: $0, limits: codec.beefLimits, transactionOrder: .any) }, outputs: try outputs.map { try $0.model(codec) }, limits: codec.abiLimits) } } diff --git a/Sources/BSVWallet/JSON/WalletBRC100CertificateJSON.swift b/Sources/BSVWallet/JSON/WalletBRC100CertificateJSON.swift index f177d48..ade74ba 100644 --- a/Sources/BSVWallet/JSON/WalletBRC100CertificateJSON.swift +++ b/Sources/BSVWallet/JSON/WalletBRC100CertificateJSON.swift @@ -182,7 +182,11 @@ private struct CertificateResultDTO: Codable { let revocationOutpoint: String; let signature: String?; let fields: [String: String] let keyring: [String: CertificateCiphertext]?; let verifier: String? init(_ value: WalletCertificateResult) throws { let certificate = try CertificateDTO(value.certificate); type = certificate.type; subject = certificate.subject; serialNumber = certificate.serialNumber; certifier = certificate.certifier; revocationOutpoint = certificate.revocationOutpoint; signature = certificate.signature; fields = certificate.fields; keyring = value.keyring.map { Dictionary(uniqueKeysWithValues: $0.map { ($0.key.value, $0.value) }) }; if value.verifier.isEmpty { verifier = nil } else { guard let text = String(bytes: value.verifier, encoding: .utf8) else { throw WalletJSONCodecError.invalidJSON }; verifier = text } } - func model(_ codec: WalletBRC100JSONCodec) throws -> WalletCertificateResult { try .init(certificate: CertificateDTO(type: type, subject: subject, serialNumber: serialNumber, certifier: certifier, revocationOutpoint: revocationOutpoint, signature: signature, fields: fields).model(codec), keyring: try keyring.map { try dictionaryCiphertexts($0, limits: codec.certificateLimits) }, verifier: verifier.map { Array($0.utf8) } ?? [], limits: codec.abiLimits) } + // `@bsv/sdk` 4.1.1 treats an empty keyring as absent: its processor writes + // the no-keyring flag for `{}` and its transceiver returns `{}` for that flag + // (WalletWireProcessor.ts:2118, WalletWireTransceiver.ts:1622). JSON `{}` is + // therefore read as no keyring. + func model(_ codec: WalletBRC100JSONCodec) throws -> WalletCertificateResult { try .init(certificate: CertificateDTO(type: type, subject: subject, serialNumber: serialNumber, certifier: certifier, revocationOutpoint: revocationOutpoint, signature: signature, fields: fields).model(codec), keyring: try keyring.flatMap { $0.isEmpty ? nil : try dictionaryCiphertexts($0, limits: codec.certificateLimits) }, verifier: verifier.map { Array($0.utf8) } ?? [], limits: codec.abiLimits) } } private struct ListCertificatesResultDTO: Codable { let totalCertificates: UInt32; let certificates: [CertificateResultDTO] diff --git a/Sources/BSVWallet/JSON/WalletBRC100JSONCodec.swift b/Sources/BSVWallet/JSON/WalletBRC100JSONCodec.swift index cfe9f88..7409522 100644 --- a/Sources/BSVWallet/JSON/WalletBRC100JSONCodec.swift +++ b/Sources/BSVWallet/JSON/WalletBRC100JSONCodec.swift @@ -178,7 +178,7 @@ public protocol WalletJSONFailureMapping: Sendable { public struct WalletJSONRedactingFailureMapper: WalletJSONFailureMapping, Sendable { public init() {} public func payload(for error: any Error, call: WalletCall) -> WalletJSONErrorPayload { - WalletJSONErrorPayload(name: "WERR_UNKNOWN", message: "Wallet request failed") + WalletJSONErrorPayload(name: "WERR_UNKNOWN", message: "Wallet request failed", code: 1) } } @@ -215,7 +215,8 @@ public struct WalletBRC100JSONProcessor: Sendable { call: route.call, body: (try? codec.encodeError(.init( name: "WERR_UNKNOWN", - message: "Wallet returned a mismatched result" + message: "Wallet returned a mismatched result", + code: 1 ))) ?? [] ) } diff --git a/Sources/BSVWallet/Substrates/WalletWireProcessor.swift b/Sources/BSVWallet/Substrates/WalletWireProcessor.swift index b559c47..2131320 100644 --- a/Sources/BSVWallet/Substrates/WalletWireProcessor.swift +++ b/Sources/BSVWallet/Substrates/WalletWireProcessor.swift @@ -47,6 +47,12 @@ public struct WalletWireProcessor: self.wireLimits = wireLimits } + /// Answers one request frame. + /// + /// Every malformed or unsupported request gets an in-band error frame, as a + /// `@bsv/sdk` 4.1.1 processor sends: code 1 and a short message, with an + /// empty stack. Only a bad `maximumResponseByteCount`, cancellation, or a + /// response larger than the caller allows throw out of band. public func transmit( _ request: [UInt8], maximumResponseByteCount: Int @@ -59,31 +65,51 @@ public struct WalletWireProcessor: } let responseLimits = try limitedResponseLimits(maximumResponseByteCount) try Task.checkCancellation() - let frame = try WalletWireCodec.decodeRequestFrame(request, limits: wireLimits) - + let call = request.first.flatMap(WalletCall.init(rawValue:)) let response: [UInt8] + do { + response = try await process(request, responseLimits: responseLimits) + } catch is CancellationError { + throw CancellationError() + } catch { + response = try failureFrame( + code: WalletWireErrorCode.unknownError, + message: walletWireRequestFailureMessage(error, call: call), + limits: responseLimits + ) + } + guard response.count <= maximumResponseByteCount else { + throw WalletWireError.byteLimitExceeded( + kind: "transport response", + actual: response.count, + maximum: maximumResponseByteCount + ) + } + return response + } + + private func process( + _ request: [UInt8], + responseLimits: WalletWireLimits + ) async throws -> [UInt8] { + // Call 29 is the @bsv/sdk 4.1 certificate compatibility profile. This + // processor answers it as an older processor does, with exactly the + // error a TypeScript transceiver downgrades on (see COMP-050). + let frame = try WalletWireCodec.decodeRequestFrame(request, limits: wireLimits) switch frame.call { case .createAction, .signAction, .abortAction, .listActions, .internalizeAction, .listOutputs, .relinquishOutput: - response = try await processAction(request, responseLimits: responseLimits) + return try await processAction(request, responseLimits: responseLimits) case .revealCounterpartyKeyLinkage, .revealSpecificKeyLinkage, .acquireCertificate, .listCertificates, .proveCertificate, .relinquishCertificate, .discoverByIdentityKey, .discoverByAttributes: - response = try await processCertificate(request, responseLimits: responseLimits) + return try await processCertificate(request, responseLimits: responseLimits) case .getPublicKey, .encrypt, .decrypt, .createHMAC, .verifyHMAC, .createSignature, .verifySignature, .isAuthenticated, .waitForAuthentication, .getHeight, .getHeaderForHeight, .getNetwork, .getVersion: - response = try await processKeyQuery(request, responseLimits: responseLimits) - } - guard response.count <= maximumResponseByteCount else { - throw WalletWireError.byteLimitExceeded( - kind: "transport response", - actual: response.count, - maximum: maximumResponseByteCount - ) + return try await processKeyQuery(request, responseLimits: responseLimits) } - return response } private func processAction( @@ -123,11 +149,15 @@ public struct WalletWireProcessor: } try Task.checkCancellation() let responseBEEFLimits = try limitedBEEFLimits(responseLimits.maximumPayloadByteCount) - return try WalletWireCodec.encodeActionResult( - result, - beefLimits: responseBEEFLimits, - limits: responseLimits - ) + return try encodeResult(call: decoded.request.call, limits: responseLimits) { + try WalletWireCodec.encodeActionResult( + result, + request: decoded.request, + listOutputsEncoding: decoded.listOutputsEncoding, + beefLimits: responseBEEFLimits, + limits: responseLimits + ) + } } private func processCertificate( @@ -166,11 +196,13 @@ public struct WalletWireProcessor: return try encodeFailure(error, call: decoded.request.call, limits: responseLimits) } try Task.checkCancellation() - return try WalletWireCodec.encodeCertificateResult( - result, - certificateLimits: certificateLimits, - limits: responseLimits - ) + return try encodeResult(call: decoded.request.call, limits: responseLimits) { + try WalletWireCodec.encodeCertificateResult( + result, + certificateLimits: certificateLimits, + limits: responseLimits + ) + } } private func processKeyQuery( @@ -205,7 +237,32 @@ public struct WalletWireProcessor: return try encodeFailure(error, call: decoded.request.call, limits: responseLimits) } try Task.checkCancellation() - return try WalletWireCodec.encodeKeyQueryResult(result, limits: responseLimits) + return try encodeResult(call: decoded.request.call, limits: responseLimits) { + try WalletWireCodec.encodeKeyQueryResult(result, limits: responseLimits) + } + } + + /// Encodes a wallet result, answering in-band when it has no wire encoding. + private func encodeResult( + call: WalletCall, + limits: WalletWireLimits, + _ encode: () throws -> [UInt8] + ) throws -> [UInt8] { + do { + return try encode() + } catch let rejection as WalletWireResultRejection { + return try failureFrame( + code: WalletWireErrorCode.clamped(rejection.code), + message: rejection.message, + limits: limits + ) + } catch { + return try failureFrame( + code: WalletWireErrorCode.unknownError, + message: walletWireResultFailureMessage(error, call: call), + limits: limits + ) + } } private func encodeFailure( @@ -214,6 +271,28 @@ public struct WalletWireProcessor: limits: WalletWireLimits ) throws -> [UInt8] { let remote = failureMapper.remoteError(for: error, call: call) + return try failureFrame( + code: WalletWireErrorCode.clamped(remote.code), + message: remote.message, + limits: limits + ) + } + + /// An error frame with an empty stack: stacks disclose implementation details. + private func failureFrame( + code: UInt8, + message: String, + limits: WalletWireLimits + ) throws -> [UInt8] { + let remote = try WalletWireRemoteError( + code: code, + message: walletWireTruncatedMessage( + message, + maximum: limits.maximumRemoteMessageUTF8ByteCount + ), + stack: "", + limits: limits + ) return try WalletWireCodec.encodeResultFrame(.failure(remote), limits: limits) } diff --git a/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift b/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift index 9845875..32a064c 100644 --- a/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift +++ b/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift @@ -15,13 +15,15 @@ public struct WalletWireTransceiver: private let beefLimits: BEEFLimits private let certificateLimits: CertificateLimits private let wireLimits: WalletWireLimits + private let listOutputsEncoding: WalletWireListOutputsEncoding public init( transport: any WalletWireTransport, originator: String, beefLimits: BEEFLimits, certificateLimits: CertificateLimits, - wireLimits: WalletWireLimits + wireLimits: WalletWireLimits, + listOutputsEncoding: WalletWireListOutputsEncoding = .legacy ) throws { let count = originator.utf8.count let maximum = min( @@ -49,6 +51,7 @@ public struct WalletWireTransceiver: ) self.certificateLimits = certificateLimits self.wireLimits = wireLimits + self.listOutputsEncoding = listOutputsEncoding } public func createAction( @@ -303,6 +306,7 @@ public struct WalletWireTransceiver: let frame = try WalletWireCodec.encodeActionRequest( request, originator: originator, + listOutputsEncoding: listOutputsEncoding, beefLimits: beefLimits, limits: wireLimits ) @@ -310,6 +314,8 @@ public struct WalletWireTransceiver: return try WalletWireCodec.decodeActionResult( response, expectedCall: request.call, + request: request, + listOutputsEncoding: listOutputsEncoding, beefLimits: beefLimits, limits: wireLimits ) diff --git a/Sources/BSVWallet/Substrates/WalletWireTransport.swift b/Sources/BSVWallet/Substrates/WalletWireTransport.swift index 94c8f2e..439aab5 100644 --- a/Sources/BSVWallet/Substrates/WalletWireTransport.swift +++ b/Sources/BSVWallet/Substrates/WalletWireTransport.swift @@ -59,7 +59,7 @@ public struct WalletWireRedactingFailureMapper: public init( code: UInt8 = 1, - message: String = "wallet operation failed", + message: String = "Wallet operation failed", stack: String = "", limits: WalletWireLimits ) throws { diff --git a/Sources/BSVWallet/Wire/WalletWireActionCodec.swift b/Sources/BSVWallet/Wire/WalletWireActionCodec.swift index 18465d2..31162b2 100644 --- a/Sources/BSVWallet/Wire/WalletWireActionCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireActionCodec.swift @@ -3,15 +3,21 @@ import BSVKeys import BSVTransaction extension WalletWireCodec { + /// Encodes an action request frame. `listOutputsEncoding: .spendable` appends + /// the one-byte `01` extension to a `listOutputs` request. public static func encodeActionRequest( _ request: WalletWireActionRequest, originator: String, + listOutputsEncoding: WalletWireListOutputsEncoding = .legacy, beefLimits: BEEFLimits, limits: WalletWireLimits = .standard ) throws -> [UInt8] { - let parameters = try encodeActionParameters( + var parameters = try encodeActionParameters( request, beefLimits: beefLimits, limits: limits ) + if case .listOutputs = request, listOutputsEncoding == .spendable { + parameters.append(1) + } return try encodeRequestFrame( WalletWireRequestFrame(call: request.call, originator: originator, parameters: parameters), limits: limits @@ -25,11 +31,17 @@ extension WalletWireCodec { ) throws -> WalletWireDecodedActionRequest { let frame = try decodeRequestFrame(bytes, limits: limits) do { + var parameters = frame.parameters + var encoding = WalletWireListOutputsEncoding.legacy + if frame.call == .listOutputs { + encoding = try walletWireSplitListOutputsExtension(¶meters, limits: limits) + } return WalletWireDecodedActionRequest( originator: frame.originator, request: try decodeActionParameters( - frame.parameters, call: frame.call, beefLimits: beefLimits, limits: limits - ) + parameters, call: frame.call, beefLimits: beefLimits, limits: limits + ), + listOutputsEncoding: encoding ) } catch let error as WalletWireError { throw error @@ -38,29 +50,57 @@ extension WalletWireCodec { } } + /// Encodes an action result frame. + /// + /// `request` supplies what the layout depends on: a BRC-112 balance basket + /// and the `listOutputs` encoding. A refused abort is the error frame code 8 + /// that `@bsv/sdk` 4.1.1 sends. A result with no wire encoding throws + /// `WalletWireResultRejection`, which a processor sends in-band. public static func encodeActionResult( _ result: WalletWireActionResult, + request: WalletWireActionRequest? = nil, + listOutputsEncoding: WalletWireListOutputsEncoding = .legacy, beefLimits: BEEFLimits, limits: WalletWireLimits = .standard ) throws -> [UInt8] { + if case .abortAction(let value) = result, !value.aborted { + return try encodeResultFrame(.failure(WalletWireRemoteError( + code: WalletWireErrorCode.abortRefused, + message: WalletWireFailureText.abortRefused, + stack: "", + limits: limits + )), limits: limits) + } let payload = try encodeActionResultPayload( - result, beefLimits: beefLimits, limits: limits + result, request: request, listOutputsEncoding: listOutputsEncoding, + beefLimits: beefLimits, limits: limits ) return try encodeResultFrame(.success(payload), limits: limits) } + /// Decodes an action result frame. With `request`, list pages are checked + /// against the requested limit and a balance basket's total is read as a + /// 64-bit balance. Error code 8 on `abortAction` reads as `aborted: false`. public static func decodeActionResult( _ bytes: [UInt8], expectedCall: WalletCall, + request: WalletWireActionRequest? = nil, + listOutputsEncoding: WalletWireListOutputsEncoding = .legacy, beefLimits: BEEFLimits, limits: WalletWireLimits = .standard ) throws -> WalletWireActionResult { switch try decodeResultFrame(bytes, limits: limits) { - case .failure(let remote): throw remote + case .failure(let remote): + if expectedCall == .abortAction, remote.code == WalletWireErrorCode.abortRefused { + return .abortAction(WalletAbortActionResult(aborted: false)) + } + throw remote case .success(let payload): do { return try decodeActionResultPayload( - payload, call: expectedCall, beefLimits: beefLimits, limits: limits + payload, call: expectedCall, request: request, + listOutputsEncoding: listOutputsEncoding, + beefLimits: beefLimits, limits: limits ) } catch let error as WalletWireError { throw error @@ -174,8 +214,9 @@ extension WalletWireCodec { ) } } + // @bsv/sdk writes -1 for omitted labels; they default to none. try walletWireWriteStringSlice( - value.labels, kind: "labels", to: &writer, limits: limits + value.labels.isEmpty ? nil : value.labels, kind: "labels", to: &writer, limits: limits ) try walletWireWriteText( value.description, kind: "action description", to: &writer, limits: limits @@ -255,14 +296,12 @@ extension WalletWireCodec { ) var spends: [UInt32: WalletSignActionSpend] = [:] spends.reserveCapacity(min(count, reader.remainingCount)) - var priorIndex: UInt32? for _ in 0.. [WalletCreateActionInput]? { let count = try reader.readCompactSize() if count == UInt64.max { return nil } - guard count != 0 else { - throw WalletWireError.nonRoundTrippableValue(kind: "empty create-action inputs") - } guard count <= UInt64(limits.abiLimits.maximumCollectionCount), count <= UInt64(Int.max) else { throw WalletWireError.countLimitExceeded( kind: "inputs", actual: count, maximum: limits.abiLimits.maximumCollectionCount @@ -571,7 +604,10 @@ private extension WalletWireCodec { output.customInstructions, kind: "custom instructions", to: &writer, limits: limits ) - try walletWireWriteStringSlice(output.tags, kind: "tags", to: &writer, limits: limits) + // @bsv/sdk writes -1 for omitted tags; they default to none. + try walletWireWriteStringSlice( + output.tags.isEmpty ? nil : output.tags, kind: "tags", to: &writer, limits: limits + ) } } @@ -607,9 +643,9 @@ private extension WalletWireCodec { let custom = try reader.readOptionalString( maximum: walletWireMaximumText(limits), kind: "custom instructions" ) - guard let tags = try walletWireReadStringSlice( + let tags = try walletWireReadStringSlice( from: &reader, kind: "tags", optional: false, limits: limits - ) else { throw WalletWireError.nonRoundTrippableValue(kind: "absent tags") } + ) ?? [] result.append(try WalletCreateActionOutput( lockingScript: script, satoshis: satoshis, outputDescription: description, basket: basket, customInstructions: custom, tags: tags, limits: limits.abiLimits @@ -636,17 +672,10 @@ private extension WalletWireCodec { ) writer.writeOptionalBoolean(options.returnTransactionIDOnly) writer.writeOptionalBoolean(options.noSend) - if let noSendChange = options.noSendChange { - let nestedCount = try walletWireOutpointCollectionByteCount( - noSendChange, kind: "no-send change", limits: limits - ) - writer.writeCompactSize(UInt64(nestedCount)) - try walletWireWriteOutpointCollection( - noSendChange, kind: "no-send change", to: &writer, limits: limits - ) - } else { - try writer.writeOptionalVarBytes(nil) - } + // @bsv/sdk 4.1.1: an outpoint count (or -1) followed by the outpoints. + try walletWireWriteOutpointCollection( + options.noSendChange, kind: "no-send change", to: &writer, limits: limits + ) try walletWireWriteTransactionIDs( options.sendWith, kind: "send-with transaction IDs", to: &writer, limits: limits ) @@ -675,20 +704,9 @@ private extension WalletWireCodec { ) let txidOnly = try reader.readOptionalBoolean(kind: "return transaction ID only") let noSend = try reader.readOptionalBoolean(kind: "no send") - let noSendChangeBytes = try reader.readOptionalVarBytes( - maximum: limits.maximumPayloadByteCount, kind: "no-send change" + let noSendChange = try walletWireReadOutpointCollection( + from: &reader, kind: "no-send change", limits: limits ) - let noSendChange: [Outpoint]? - if let encoded = noSendChangeBytes { - var nested = WalletWireReader(encoded) - noSendChange = try walletWireReadOutpointCollection( - from: &nested, kind: "no-send change", limits: limits - ) - try nested.requireEnd() - if noSendChange == nil { - throw WalletWireError.nonRoundTrippableValue(kind: "nested absent no-send change") - } - } else { noSendChange = nil } let sendWith = try walletWireReadTransactionIDs( from: &reader, kind: "send-with transaction IDs", limits: limits ) @@ -745,3 +763,39 @@ private extension WalletWireCodec { ) } } + +/// Splits the optional `listOutputs` request extension. @bsv/sdk 4.1 appends one +/// `01` byte after `seekPermission` to ask for the spendable response layout. +func walletWireSplitListOutputsExtension( + _ parameters: inout [UInt8], + limits: WalletWireLimits +) throws -> WalletWireListOutputsEncoding { + var reader = WalletWireReader(parameters) + _ = try reader.readVarBytes(maximum: walletWireMaximumText(limits), kind: "basket") + let tagCount = try reader.readCompactSize() + if tagCount != UInt64.max, tagCount > 0 { + guard tagCount <= UInt64(limits.abiLimits.maximumTagCount) else { + throw WalletWireError.countLimitExceeded( + kind: "tags", actual: tagCount, maximum: limits.abiLimits.maximumTagCount + ) + } + for _ in 0.. TransactionID { - try TransactionID(wireBytes: readBytes(count: 32)) + /// Reads a transaction ID written in display byte order. + mutating func readWalletTransactionID() throws -> TransactionID { + try TransactionID(wireBytes: Array(readBytes(count: 32).reversed())) } mutating func readDisplayTransactionID() throws -> TransactionID { @@ -109,8 +112,7 @@ func walletWireWriteStringSlice( writer.writeCompactSize(UInt64(values.count)) for value in values { try walletWireRequireText(value, kind: kind, maximum: walletWireMaximumText(limits)) - if value.isEmpty { writer.writeCompactSize(UInt64.max) } - else { try writer.writeString(value) } + try writer.writeString(value) } } @@ -122,8 +124,8 @@ func walletWireReadStringSlice( ) throws -> [String]? { let encodedCount = try reader.readCompactSize() if encodedCount == UInt64.max { - if optional { return nil } - throw WalletWireError.nonRoundTrippableValue(kind: "absent \(kind)") + // `@bsv/sdk` writes -1 for an omitted array whose JSON default is empty. + return optional ? nil : [] } let maximum = kind == "labels" ? limits.abiLimits.maximumLabelCount : kind == "tags" ? limits.abiLimits.maximumTagCount @@ -135,15 +137,12 @@ func walletWireReadStringSlice( result.reserveCapacity(min(Int(encodedCount), reader.remainingCount)) for _ in 0.. [UInt8] { var writer = WalletWireWriter(maximumByteCount: limits.maximumPayloadByteCount) switch result { case .createAction(let value): - // The pinned serializer embeds a second success byte in this call's payload. - writer.writeByte(0) - guard let transactionID = value.transactionID else { - throw WalletWireError.nonRoundTrippableValue( - kind: "create-action result without transaction ID" - ) - } - guard value.signableTransaction == nil else { - throw WalletWireError.nonRoundTrippableValue( - kind: "pinned Go signable create-action result" - ) - } - writer.writeByte(1) - writer.writeWireTransactionID(transactionID) - if let transaction = value.transaction { - writer.writeByte(1) - try writer.writeVarBytes(walletWireAtomicBEEFBytes(transaction, limits: beefLimits)) - } else { writer.writeByte(0) } - try encodeOptionalOutpointBytes( + // @bsv/sdk 4.1.1 layout: txid flag, tx flag, noSendChange, sendWithResults, + // signableTransaction flag. Every part may be absent (COMP-045). + encodeOptionalTransactionID(value.transactionID, to: &writer) + try encodeOptionalAtomicBEEF(value.transaction, to: &writer, beefLimits: beefLimits) + try walletWireWriteOutpointCollection( value.noSendChange, kind: "no-send change", to: &writer, limits: limits ) try encodeSendWithResults(value.sendWithResults, to: &writer, limits: limits) - writer.writeByte(0) - case .signAction(let value): - guard let transactionID = value.transactionID else { - throw WalletWireError.nonRoundTrippableValue( - kind: "sign-action result without transaction ID" + if let signable = value.signableTransaction { + writer.writeByte(1) + try writer.writeVarBytes( + walletWireAtomicBEEFBytes(signable.transaction, limits: beefLimits) ) + try walletWireRequireActionBytes( + signable.reference.bytes.count, kind: "reference", limits: limits + ) + try writer.writeVarBytes(signable.reference.bytes) + } else { + writer.writeByte(0) } - writer.writeByte(1) - writer.writeWireTransactionID(transactionID) - if let transaction = value.transaction { - writer.writeByte(1) - try writer.writeVarBytes(walletWireAtomicBEEFBytes(transaction, limits: beefLimits)) - } else { writer.writeByte(0) } + case .signAction(let value): + encodeOptionalTransactionID(value.transactionID, to: &writer) + try encodeOptionalAtomicBEEF(value.transaction, to: &writer, beefLimits: beefLimits) try encodeSendWithResults(value.sendWithResults, to: &writer, limits: limits) case .abortAction(let value): + // A refusal travels as error code 8 (WalletWireCodec.encodeActionResult). guard value.aborted else { - throw WalletWireError.nonRoundTrippableValue(kind: "false abort-action result") + throw WalletWireResultRejection( + code: WalletWireErrorCode.abortRefused, + message: WalletWireFailureText.abortRefused + ) } case .listActions(let value): - guard let actionCount = UInt32(exactly: value.actions.count), - value.totalActions == actionCount else { - throw WalletWireError.nonRoundTrippableValue(kind: "total actions mismatch") - } + try walletWireRequirePage( + records: value.actions.count, total: UInt64(value.totalActions), call: "listActions" + ) writer.writeCompactSize(UInt64(value.totalActions)) for action in value.actions { writer.writeDisplayTransactionID(action.transactionID) @@ -74,32 +67,44 @@ extension WalletWireCodec { } case .internalizeAction(let value): guard value.accepted else { - throw WalletWireError.nonRoundTrippableValue(kind: "false internalize-action result") + throw WalletWireResultRejection(message: "The wallet did not accept the action") } case .listOutputs(let value): - guard let outputCount = UInt32(exactly: value.outputs.count), - value.totalOutputs == outputCount else { - throw WalletWireError.nonRoundTrippableValue(kind: "total outputs mismatch") + let balance: Bool + if case .listOutputs(let query)? = request { + balance = walletIsBalanceBasket(query.basket) + } else { + balance = false + } + if balance { + try walletWireRequireBalanceResult(value) + } else { + try walletWireRequirePage( + records: value.outputs.count, total: value.totalOutputs, call: "listOutputs" + ) } - writer.writeCompactSize(UInt64(value.totalOutputs)) + let spendable = listOutputsEncoding == .spendable + if !spendable, value.outputs.contains(where: { !$0.spendable }) { + throw WalletWireResultRejection( + message: WalletWireFailureText.unspendableLegacyOutputs + ) + } + // The spendable layout acknowledges the request extension with -1. + if spendable { writer.writeCompactSize(UInt64.max) } + writer.writeCompactSize(value.totalOutputs) if let beef = value.beef { try writer.writeVarBytes(walletWireBEEFBytes(beef, limits: beefLimits)) } else { writer.writeCompactSize(UInt64.max) } for output in value.outputs { - guard output.spendable else { - throw WalletWireError.nonRoundTrippableValue(kind: "unspendable listed output") - } writer.writeActionOutpoint(output.outpoint) writer.writeCompactSize(output.satoshis) if let script = output.lockingScript { - guard !script.isEmpty else { - throw WalletWireError.nonRoundTrippableValue(kind: "empty optional locking script") - } try walletWireRequireActionBytes( script.count, kind: "locking script", limits: limits ) try writer.writeVarBytes(script) } else { writer.writeCompactSize(UInt64.max) } + if spendable { writer.writeByte(output.spendable ? 1 : 0) } try walletWireWriteOptionalText( output.customInstructions, kind: "custom instructions", to: &writer, limits: limits @@ -113,7 +118,7 @@ extension WalletWireCodec { } case .relinquishOutput(let value): guard value.relinquished else { - throw WalletWireError.nonRoundTrippableValue(kind: "false relinquish-output result") + throw WalletWireResultRejection(message: "The wallet did not relinquish the output") } } try writer.requireWithinLimit(kind: "result payload") @@ -123,6 +128,8 @@ extension WalletWireCodec { static func decodeActionResultPayload( _ bytes: [UInt8], call: WalletCall, + request: WalletWireActionRequest?, + listOutputsEncoding: WalletWireListOutputsEncoding, beefLimits: BEEFLimits, limits: WalletWireLimits ) throws -> WalletWireActionResult { @@ -130,24 +137,28 @@ extension WalletWireCodec { let value: WalletWireActionResult switch call { case .createAction: - guard try reader.readByte() == 0 else { - throw WalletWireError.nonRoundTrippableValue(kind: "nested create-action failure") - } - let transactionID = try decodeRequiredGoTransactionID(from: &reader) + let transactionID = try decodeOptionalTransactionID(from: &reader) let transaction = try decodeOptionalAtomicBEEF( from: &reader, beefLimits: beefLimits ) - let noSendChange = try decodeOptionalOutpointBytes( + let noSendChange = try walletWireReadOutpointCollection( from: &reader, kind: "no-send change", limits: limits ) let sendWith = try decodeSendWithResults(from: &reader, limits: limits) + let signable: WalletSignableTransaction? switch try reader.readByte() { - case 0: break + case 0: signable = nil case 1: - // Go always re-encodes a zero transaction ID with this union. It cannot - // preserve the Swift ABI's mutually exclusive signable representation. - throw WalletWireError.nonRoundTrippableValue( - kind: "pinned Go signable create-action result" + let transaction = try walletWireParseAtomicBEEF( + reader.readVarBytes(maximum: beefLimits.maximumByteCount, kind: "Atomic BEEF"), + limits: beefLimits + ) + let reference = try reader.readVarBytes( + maximum: limits.abiLimits.maximumBytePayloadCount, kind: "reference" + ) + signable = WalletSignableTransaction( + transaction: transaction, + reference: try WalletBase64Data(reference, limits: limits.abiLimits) ) case let flag: throw WalletWireError.invalidDiscriminator(kind: "signable transaction", value: flag) @@ -157,10 +168,11 @@ extension WalletWireCodec { transaction: transaction, noSendChange: noSendChange, sendWithResults: sendWith, + signableTransaction: signable, limits: limits.abiLimits )) case .signAction: - let transactionID = try decodeRequiredGoTransactionID(from: &reader) + let transactionID = try decodeOptionalTransactionID(from: &reader) let transaction = try decodeOptionalAtomicBEEF( from: &reader, beefLimits: beefLimits ) @@ -175,13 +187,13 @@ extension WalletWireCodec { try reader.requireEnd() value = .abortAction(WalletAbortActionResult(aborted: true)) case .listActions: - let count = try reader.readCount( - maximum: limits.abiLimits.maximumCollectionCount, kind: "actions" - ) - guard let total = UInt32(exactly: count) else { throw WalletWireError.uint32Overflow } + let totalRaw = try reader.readCompactSize() + guard let total = UInt32(exactly: totalRaw) else { throw WalletWireError.uint32Overflow } + let pageLimit = walletWirePageLimit(request) var actions: [WalletAction] = [] - actions.reserveCapacity(min(count, reader.remainingCount / 40)) - for _ in 0.. UInt64(UInt32.max) { throw WalletWireError.uint32Overflow } let beefBytes = try reader.readOptionalVarBytes( maximum: beefLimits.maximumByteCount, kind: "BEEF" ) + let pageLimit = walletWirePageLimit(request) var outputs: [WalletOutput] = [] - outputs.reserveCapacity(min(count, reader.remainingCount / 34)) - for _ in 0.. Int { + switch request { + case .listActions(let value)?: Int(value.pagination.effectiveLimit) + case .listOutputs(let value)?: Int(value.pagination.effectiveLimit) + default: Int(WalletABILimits.maximumProtocolPageSize) + } +} + +func walletWireRequirePageCapacity(_ returned: Int, limit: Int, call: String) throws { + guard returned < limit else { + throw WalletWireResultRejection( + message: "Wallet Wire \(call) response exceeds the requested page limit of \(limit)" + ) + } +} + +/// A page may be shorter than its total: the total counts every matching record. +func walletWireRequirePage(records: Int, total: UInt64, call: String) throws { + guard total <= UInt64(UInt32.max) else { + throw WalletWireResultRejection( + message: "Invalid \(call) result: total \(total) does not fit in 32 bits" + ) + } + guard UInt64(records) <= total else { + throw WalletWireResultRejection( + message: "Invalid \(call) result: returned \(records) records but declared a total of \(total)" + ) + } +} + +/// BRC-112: a balance basket answers with the balance and no records or BEEF. +func walletWireRequireBalanceResult(_ value: WalletListOutputsResult) throws { + guard value.outputs.isEmpty, value.beef == nil else { + throw WalletWireResultRejection( + message: "Invalid listOutputs result: a balance basket returns no outputs or BEEF" + ) + } +} + private extension WalletWireCodec { static func actionStatusCode(_ value: WalletActionStatus) -> UInt8 { switch value { @@ -320,10 +399,10 @@ private extension WalletWireCodec { to writer: inout WalletWireWriter, limits: WalletWireLimits ) throws { - if values?.isEmpty == true { - throw WalletWireError.nonRoundTrippableValue(kind: "empty send-with results") + guard let values else { + writer.writeCompactSize(UInt64.max) + return } - let values = values ?? [] guard values.count <= limits.abiLimits.maximumCollectionCount else { throw WalletWireError.countLimitExceeded( kind: "send-with results", actual: UInt64(values.count), @@ -332,7 +411,7 @@ private extension WalletWireCodec { } writer.writeCompactSize(UInt64(values.count)) for value in values { - writer.writeWireTransactionID(value.transactionID) + writer.writeWalletTransactionID(value.transactionID) writer.writeByte(sendWithStatusCode(value.status)) } } @@ -341,72 +420,63 @@ private extension WalletWireCodec { from reader: inout WalletWireReader, limits: WalletWireLimits ) throws -> [WalletSendWithResult]? { - let count = try reader.readCount( - maximum: limits.abiLimits.maximumCollectionCount, kind: "send-with results" - ) - if count == 0 { return nil } + let rawCount = try reader.readCompactSize() + if rawCount == UInt64.max { return nil } + guard rawCount <= UInt64(limits.abiLimits.maximumCollectionCount) else { + throw WalletWireError.countLimitExceeded( + kind: "send-with results", actual: rawCount, + maximum: limits.abiLimits.maximumCollectionCount + ) + } + let count = Int(rawCount) guard count <= reader.remainingCount / 33 else { throw WalletWireError.truncated } var values: [WalletSendWithResult] = [] values.reserveCapacity(count) for _ in 0.. [Outpoint]? { - guard let bytes = try reader.readOptionalVarBytes( - maximum: limits.maximumPayloadByteCount, kind: kind - ) else { return nil } - var nested = WalletWireReader(bytes) - let values = try walletWireReadOutpointCollection( - from: &nested, kind: kind, limits: limits - ) - try nested.requireEnd() - guard let values else { - throw WalletWireError.nonRoundTrippableValue(kind: "nested absent \(kind)") - } - return values - } - - static func decodeRequiredGoTransactionID( + static func decodeOptionalTransactionID( from reader: inout WalletWireReader - ) throws -> TransactionID { + ) throws -> TransactionID? { switch try reader.readByte() { - case 1: return try reader.readWireTransactionID() - case 0: - throw WalletWireError.nonRoundTrippableValue(kind: "absent pinned Go transaction ID") + case 0: return nil + case 1: return try reader.readWalletTransactionID() case let flag: throw WalletWireError.invalidDiscriminator(kind: "transaction ID", value: flag) } } + static func encodeOptionalAtomicBEEF( + _ value: AtomicBEEF?, + to writer: inout WalletWireWriter, + beefLimits: BEEFLimits + ) throws { + guard let value else { + writer.writeByte(0) + return + } + writer.writeByte(1) + try writer.writeVarBytes(walletWireAtomicBEEFBytes(value, limits: beefLimits)) + } + static func decodeOptionalAtomicBEEF( from reader: inout WalletWireReader, beefLimits: BEEFLimits @@ -428,10 +498,7 @@ private extension WalletWireCodec { to writer: inout WalletWireWriter, limits: WalletWireLimits ) throws { - guard let values, !values.isEmpty else { - if values?.isEmpty == true { - throw WalletWireError.nonRoundTrippableValue(kind: "empty action inputs") - } + guard let values else { writer.writeCompactSize(UInt64.max) return } @@ -445,24 +512,13 @@ private extension WalletWireCodec { for value in values { writer.writeActionOutpoint(value.sourceOutpoint) writer.writeCompactSize(value.sourceSatoshis) - guard let source = value.sourceLockingScript, !source.isEmpty else { - throw WalletWireError.nonRoundTrippableValue( - kind: "absent or empty action source locking script" - ) - } - guard let unlocking = value.unlockingScript, !unlocking.isEmpty else { - throw WalletWireError.nonRoundTrippableValue( - kind: "absent or empty action unlocking script" - ) + // Scripts are present only when the request asked for them. + for script in [value.sourceLockingScript, value.unlockingScript] { + if let script { + try walletWireRequireActionBytes(script.count, kind: "script", limits: limits) + } + try writer.writeOptionalVarBytes(script) } - try walletWireRequireActionBytes( - source.count, kind: "source locking script", limits: limits - ) - try walletWireRequireActionBytes( - unlocking.count, kind: "unlocking script", limits: limits - ) - try writer.writeVarBytes(source) - try writer.writeVarBytes(unlocking) try walletWireWriteText( value.inputDescription, kind: "input description", to: &writer, limits: limits ) @@ -476,9 +532,6 @@ private extension WalletWireCodec { ) throws -> [WalletActionInput]? { let count = try reader.readCompactSize() if count == UInt64.max { return nil } - if count == 0 { - throw WalletWireError.nonRoundTrippableValue(kind: "empty action inputs") - } guard count <= UInt64(limits.abiLimits.maximumCollectionCount), count <= UInt64(Int.max) else { throw WalletWireError.countLimitExceeded( kind: "inputs", actual: count, maximum: limits.abiLimits.maximumCollectionCount @@ -489,23 +542,12 @@ private extension WalletWireCodec { for _ in 0.. [WalletActionOutput]? { let count = try reader.readCompactSize() if count == UInt64.max { return nil } - if count == 0 { - throw WalletWireError.nonRoundTrippableValue(kind: "empty action outputs") - } guard count <= UInt64(limits.abiLimits.maximumCollectionCount), count <= UInt64(Int.max) else { throw WalletWireError.countLimitExceeded( kind: "outputs", actual: count, maximum: limits.abiLimits.maximumCollectionCount @@ -587,16 +620,9 @@ private extension WalletWireCodec { let indexRaw = try reader.readCompactSize() guard let index = UInt32(exactly: indexRaw) else { throw WalletWireError.uint32Overflow } let satoshis = try reader.readCompactSize() - guard let script = try reader.readOptionalVarBytes( + let script = try reader.readOptionalVarBytes( maximum: limits.abiLimits.maximumBytePayloadCount, kind: "locking script" - ) else { - throw WalletWireError.nonRoundTrippableValue( - kind: "absent action output locking script" - ) - } - if script.isEmpty { - throw WalletWireError.nonRoundTrippableValue(kind: "empty action output locking script") - } + ) let spendable: Bool switch try reader.readByte() { case 0: spendable = false @@ -607,12 +633,13 @@ private extension WalletWireCodec { let description = try reader.readString( maximum: walletWireMaximumText(limits), kind: "output description" ) - let basket = try reader.readString( + // @bsv/sdk writes -1 when an action output has no basket. + let basket = try reader.readOptionalString( maximum: walletWireMaximumText(limits), kind: "basket" - ) - guard let tags = try walletWireReadStringSlice( + ) ?? "" + let tags = try walletWireReadStringSlice( from: &reader, kind: "tags", optional: false, limits: limits - ) else { throw WalletWireError.nonRoundTrippableValue(kind: "absent tags") } + ) ?? [] let custom = try reader.readOptionalString( maximum: walletWireMaximumText(limits), kind: "custom instructions" ) diff --git a/Sources/BSVWallet/Wire/WalletWireActionTypes.swift b/Sources/BSVWallet/Wire/WalletWireActionTypes.swift index 0f418d3..eb2590a 100644 --- a/Sources/BSVWallet/Wire/WalletWireActionTypes.swift +++ b/Sources/BSVWallet/Wire/WalletWireActionTypes.swift @@ -58,13 +58,31 @@ public struct WalletWireDecodedActionRequest: Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public let originator: String public let request: WalletWireActionRequest + /// The `listOutputs` response layout the caller asked for. + public let listOutputsEncoding: WalletWireListOutputsEncoding - public init(originator: String, request: WalletWireActionRequest) { + public init( + originator: String, + request: WalletWireActionRequest, + listOutputsEncoding: WalletWireListOutputsEncoding = .legacy + ) { self.originator = originator self.request = request + self.listOutputsEncoding = listOutputsEncoding } public var description: String { "" } public var debugDescription: String { description } public var customMirror: Mirror { Mirror(self, children: ["call": request.call.rawValue]) } } + +/// The `listOutputs` response layout a transceiver asks for. +/// +/// `.legacy` is the deployed SDK 2/3 layout, which cannot carry an unspendable +/// output. `.spendable` appends the one-byte request extension `01` and reads +/// the response with an explicit spendable flag per output (TypeScript +/// `WalletWireTransceiver` option `listOutputsEncoding: 'spendable'`). +public enum WalletWireListOutputsEncoding: Hashable, Sendable { + case legacy + case spendable +} diff --git a/Sources/BSVWallet/Wire/WalletWireCertificateCodec.swift b/Sources/BSVWallet/Wire/WalletWireCertificateCodec.swift index 83a61e6..7ed934b 100644 --- a/Sources/BSVWallet/Wire/WalletWireCertificateCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireCertificateCodec.swift @@ -561,19 +561,16 @@ private func walletWireReadCertificateFields( ) var result: [CertificateFieldName: CertificateCiphertext] = [:] result.reserveCapacity(min(count, reader.remainingCount / 2)) - var prior: CertificateFieldName? for _ in 0..() for _ in 0..() for _ in 0.., kind: String ) throws { - if let previous, !previous.lexicographicallyPrecedes(current) { - throw WalletWireError.nonRoundTrippableValue(kind: "unsorted or duplicate \(kind)") + guard previous.insert(current).inserted else { + throw WalletWireError.nonRoundTrippableValue(kind: "duplicate \(kind)") } - previous = current } func walletWireMapCertificateError(_ error: Error) -> WalletWireError { diff --git a/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift b/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift index 3a78608..6233a6a 100644 --- a/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift @@ -1,3 +1,4 @@ +import BSVCore import BSVKeys extension WalletWireCodec { @@ -15,6 +16,8 @@ extension WalletWireCodec { return try encodeResultFrame(.success(payload), limits: limits) } catch let error as WalletWireError { throw error + } catch let error as WalletWireResultRejection { + throw error } catch let error as WalletABIError { throw walletWireMapABIError(error) } catch { @@ -41,6 +44,8 @@ extension WalletWireCodec { ) } catch let error as WalletWireError { throw error + } catch let error as WalletWireResultRejection { + throw error } catch let error as WalletABIError { throw walletWireMapABIError(error) } catch { @@ -116,12 +121,11 @@ extension WalletWireCodec { limits: nestedLimits )) case .listCertificates(let value): - guard let count = UInt32(exactly: value.certificates.count), - value.totalCertificates == count else { - throw WalletWireError.nonRoundTrippableValue( - kind: "total certificates mismatch" - ) - } + try walletWireRequirePage( + records: value.certificates.count, + total: UInt64(value.totalCertificates), + call: "listCertificates" + ) guard value.certificates.count <= limits.abiLimits.maximumCollectionCount else { throw WalletWireError.countLimitExceeded( kind: "certificates", @@ -162,12 +166,7 @@ extension WalletWireCodec { } else { writer.writeByte(0) } - try walletWireWriteLinkageBytes( - item.verifier, - kind: "certificate verifier", - to: &writer, - limits: limits - ) + try walletWireWriteCertificateVerifier(item.verifier, to: &writer) } case .proveCertificate(let value): try walletWireWriteKeyring( @@ -323,14 +322,16 @@ private extension WalletWireCodec { certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws -> WalletListCertificatesResult { - let count = try reader.readCount( - maximum: limits.abiLimits.maximumCollectionCount, - kind: "certificates" - ) - guard let total = UInt32(exactly: count) else { throw WalletWireError.uint32Overflow } + // @bsv/sdk writes the total, then records until the end of the frame. + let totalRaw = try reader.readCompactSize() + guard let total = UInt32(exactly: totalRaw) else { throw WalletWireError.uint32Overflow } var certificates: [WalletCertificateResult] = [] - certificates.reserveCapacity(min(count, reader.remainingCount / 2)) - for _ in 0.. WalletDiscoverCertificatesResult { - let count = try reader.readCount( - maximum: limits.abiLimits.maximumCollectionCount, - kind: "discovered certificates" - ) - guard let total = UInt32(exactly: count) else { throw WalletWireError.uint32Overflow } + let totalRaw = try reader.readCompactSize() + guard let total = UInt32(exactly: totalRaw) else { throw WalletWireError.uint32Overflow } var certificates: [WalletIdentityCertificate] = [] - certificates.reserveCapacity(min(count, reader.remainingCount / 2)) - for _ in 0.. [UInt8] { + let length = try reader.readCompactSize() + if length == 0 { return [] } + guard length == 33 else { + throw WalletWireResultRejection( + message: "Invalid listCertificates verifier length: expected 33 bytes, received \(length)" + ) + } + let bytes = try reader.readBytes(count: 33) + do { + let key = try PublicKey(bytes) + guard key.compressedBytes == bytes else { throw WalletWireError.invalidPublicKey } + } catch { + throw WalletWireError.invalidPublicKey + } + return Array(Hex.encode(bytes).utf8) +} diff --git a/Sources/BSVWallet/Wire/WalletWireCodec.swift b/Sources/BSVWallet/Wire/WalletWireCodec.swift index 860f745..919f509 100644 --- a/Sources/BSVWallet/Wire/WalletWireCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireCodec.swift @@ -208,11 +208,26 @@ public enum WalletWireCodec { ) } + /// Encodes a key or query result frame. A false verification result is the + /// error frame `@bsv/sdk` 4.1.1 sends: code 1, "HMAC is not valid" or + /// "Signature is not valid". public static func encodeKeyQueryResult( _ result: WalletWireKeyQueryResult, limits: WalletWireLimits = .standard ) throws -> [UInt8] { - try encodeResultFrame(.success(encodeResultPayload(result, limits: limits)), limits: limits) + let refusal: String? + switch result { + case .verifyHMAC(let value) where !value.valid: refusal = WalletWireFailureText.invalidHMAC + case .verifySignature(let value) where !value.valid: + refusal = WalletWireFailureText.invalidSignature + default: refusal = nil + } + if let refusal { + return try encodeResultFrame(.failure(WalletWireRemoteError( + code: WalletWireErrorCode.unknownError, message: refusal, stack: "", limits: limits + )), limits: limits) + } + return try encodeResultFrame(.success(encodeResultPayload(result, limits: limits)), limits: limits) } public static func decodeKeyQueryResult( @@ -248,7 +263,8 @@ public enum WalletWireCodec { to: &writer, limits: limits ) - writer.writeOptionalBoolean(forSelf) + // @bsv/sdk writes -1 for an omitted forSelf, and false is its default. + writer.writeOptionalBoolean(forSelf ? true : nil) } writer.writeOptionalBoolean(value.access.seekPermission) case .encrypt(let value): @@ -331,7 +347,7 @@ public enum WalletWireCodec { counterparty: value.counterparty, access: value.access, to: &writer, limits: limits ) - writer.writeOptionalBoolean(value.forSelf) + writer.writeOptionalBoolean(value.forSelf ? true : nil) try writer.writeVarBytes(value.signature.derBytes) switch value.payload { case .data(let bytes): @@ -448,7 +464,10 @@ public enum WalletWireCodec { access: try walletWireAccessWithSeek(key.access, seek: seek) )) case .createSignature: - let key = try walletWireDecodeKeyParameters(from: &reader, limits: limits) + // An omitted counterparty means `anyone` for createSignature (BRC-100). + let key = try walletWireDecodeKeyParameters( + from: &reader, defaultCounterparty: .anyone, limits: limits + ) let payload = try decodeSignaturePayload( from: &reader, rejectEmptyData: false, diff --git a/Sources/BSVWallet/Wire/WalletWireFailures.swift b/Sources/BSVWallet/Wire/WalletWireFailures.swift new file mode 100644 index 0000000..366afd1 --- /dev/null +++ b/Sources/BSVWallet/Wire/WalletWireFailures.swift @@ -0,0 +1,115 @@ +/// A result the wallet wire answers with an error frame, as `@bsv/sdk` 4.1.1 does. +/// +/// The codecs throw this when a wallet result has no success encoding (for +/// example a page longer than its declared total). A processor sends `code` and +/// `message` in-band so the remote caller sees the same frame a TypeScript +/// processor would send. +public struct WalletWireResultRejection: Error, Equatable, Sendable, CustomStringConvertible { + public let code: UInt8 + public let message: String + + public init(code: UInt8 = 1, message: String) { + self.code = code + self.message = message + } + + public var description: String { "WalletWireResultRejection(code: \(code), message: \(message))" } +} + +/// Error codes shared with `@bsv/sdk` `walletErrors`. +enum WalletWireErrorCode { + static let unknownError: UInt8 = 1 + static let unsupportedAction: UInt8 = 2 + static let abortRefused: UInt8 = 8 + + /// `@bsv/sdk` sends codes 2 through 8 as given and every other code as 1. + static func clamped(_ code: UInt8) -> UInt8 { + (unsupportedAction...abortRefused).contains(code) ? code : unknownError + } +} + +/// Messages `@bsv/sdk` 4.1.1 puts in error frames that peers match on. +enum WalletWireFailureText { + static let abortRefused = + "The wallet refused to abort this action because it has already been broadcast" + static let invalidHMAC = "HMAC is not valid" + static let invalidSignature = "Signature is not valid" + static let unspendableLegacyOutputs = + "Non-spendable listOutputs records require the spendable encoding extension or JSON" + static let readerExhausted = "ReaderUint8Array read exceeds available data" + + static func invalidCall(_ code: UInt8) -> String { "Invalid call code: \(code)" } + + static func trailingData(_ callName: String) -> String { + "Wallet Wire \(callName) request contains trailing data" + } +} + +extension WalletCall { + /// The `@bsv/sdk` method name used in wallet-wire error text. + var wireMethodName: String { jsonMethodName } +} + +extension WalletWireError { + /// A short, specific phrase for an error frame. It never carries payload bytes. + var shortMessage: String { + switch self { + case .invalidLimit(let name, let value): "invalid limit \(name)=\(value)" + case .invalidCall(let code): WalletWireFailureText.invalidCall(code) + case .invalidDiscriminator(let kind, let value): "invalid \(kind) flag \(value)" + case .invalidUTF8(let kind): "\(kind) is not valid UTF-8" + case .byteLimitExceeded(let kind, let actual, let maximum): + "\(kind) is \(actual) bytes, above the limit of \(maximum)" + case .countLimitExceeded(let kind, let actual, let maximum): + "\(kind) count \(actual) is above the limit of \(maximum)" + case .textLimitExceeded(let kind, let actual, let maximum): + "\(kind) is \(actual) bytes, above the limit of \(maximum)" + case .noncanonicalCompactSize: "non-canonical varint" + case .uint32Overflow: "integer does not fit in 32 bits" + case .truncated: WalletWireFailureText.readerExhausted + case .trailingBytes: "trailing data" + case .invalidPublicKey: "invalid public key" + case .invalidSignature: "invalid DER signature" + case .nonRoundTrippableValue(let kind): "unsupported \(kind)" + } + } +} + +/// The message a processor sends when a request frame cannot be decoded. +func walletWireRequestFailureMessage(_ error: any Error, call: WalletCall?) -> String { + let name = call?.wireMethodName + if let wire = error as? WalletWireError { + switch wire { + case .invalidCall, .truncated: + return wire.shortMessage + case .trailingBytes: + return WalletWireFailureText.trailingData(name ?? "request") + default: + return "Invalid Wallet Wire \(name ?? "") request: \(wire.shortMessage)" + } + } + if let rejection = error as? WalletWireResultRejection { return rejection.message } + return "Invalid Wallet Wire \(name ?? "") request: \(error)" +} + +/// The message a processor sends when a wallet result cannot be encoded. +func walletWireResultFailureMessage(_ error: any Error, call: WalletCall) -> String { + if let wire = error as? WalletWireError { + return "Invalid \(call.wireMethodName) result: \(wire.shortMessage)" + } + return "Invalid \(call.wireMethodName) result: \(error)" +} + +/// Cuts a message to at most `maximum` UTF-8 bytes on a character boundary. +func walletWireTruncatedMessage(_ message: String, maximum: Int) -> String { + guard message.utf8.count > maximum else { return message } + var result = "" + var count = 0 + for character in message { + let size = String(character).utf8.count + guard count + size <= maximum else { break } + result.append(character) + count += size + } + return result +} diff --git a/Sources/BSVWallet/Wire/WalletWirePrimitives.swift b/Sources/BSVWallet/Wire/WalletWirePrimitives.swift index b8ce9bc..1cddd5b 100644 --- a/Sources/BSVWallet/Wire/WalletWirePrimitives.swift +++ b/Sources/BSVWallet/Wire/WalletWirePrimitives.swift @@ -218,9 +218,6 @@ struct WalletWireReader { mutating func readOptionalString(maximum: Int, kind: String) throws -> String? { guard let encoded = try readOptionalVarBytes(maximum: maximum, kind: kind) else { return nil } - guard !encoded.isEmpty else { - throw WalletWireError.nonRoundTrippableValue(kind: "empty optional \(kind)") - } guard let value = String(bytes: encoded, encoding: .utf8) else { throw WalletWireError.invalidUTF8(kind: kind) } @@ -319,9 +316,15 @@ func walletWireEncodeCounterparty( } } -func walletWireDecodeCounterparty(from reader: inout WalletWireReader) throws -> WalletCounterparty { +/// Reads a counterparty. `@bsv/sdk` writes `00` when the caller omitted it, which +/// selects the call's own default (`anyone` for createSignature, `self` otherwise). +func walletWireDecodeCounterparty( + from reader: inout WalletWireReader, + default defaultCounterparty: WalletCounterparty = .self +) throws -> WalletCounterparty { let discriminator = try reader.readByte() switch discriminator { + case 0x00: return defaultCounterparty case 0x0B: return .self case 0x0C: return .anyone case 0x02, 0x03: @@ -343,7 +346,8 @@ func walletWireEncodeAccess( to writer: inout WalletWireWriter, limits: WalletWireLimits ) throws { - writer.writeOptionalBoolean(access.privileged) + // `@bsv/sdk` writes -1 for an omitted privileged flag, and false is its default. + writer.writeOptionalBoolean(access.privileged ? true : nil) if let reason = access.privilegedReason { guard !reason.isEmpty else { throw WalletWireError.nonRoundTrippableValue(kind: "empty privileged reason") @@ -395,6 +399,7 @@ func walletWireEncodeKeyParameters( func walletWireDecodeKeyParameters( from reader: inout WalletWireReader, + defaultCounterparty: WalletCounterparty = .self, limits: WalletWireLimits ) throws -> WalletWireKeyParameters { let protocolID = try walletWireDecodeProtocol(from: &reader, limits: limits) @@ -405,7 +410,9 @@ func walletWireDecodeKeyParameters( let keyID: WalletKeyID do { keyID = try WalletKeyID(keyText) } catch { throw WalletWireError.nonRoundTrippableValue(kind: "key ID") } - let counterparty = try walletWireDecodeCounterparty(from: &reader) + let counterparty = try walletWireDecodeCounterparty( + from: &reader, default: defaultCounterparty + ) let access = try walletWireDecodeAccess(from: &reader, limits: limits) return WalletWireKeyParameters( protocolID: protocolID, diff --git a/Sources/BSVWallet/Wire/WalletWireTypes.swift b/Sources/BSVWallet/Wire/WalletWireTypes.swift index 5f543b9..9a9a0ab 100644 --- a/Sources/BSVWallet/Wire/WalletWireTypes.swift +++ b/Sources/BSVWallet/Wire/WalletWireTypes.swift @@ -10,7 +10,7 @@ public struct WalletWireLimits: Hashable, Sendable { originator: 255, payload: 8_388_608, text: 2_000, - remoteMessage: 2_000, + remoteMessage: 4_096, remoteStack: 8_192, abi: .standard, crypto: .standard @@ -30,7 +30,7 @@ public struct WalletWireLimits: Hashable, Sendable { maximumOriginatorUTF8ByteCount: Int = 255, maximumPayloadByteCount: Int = 8_388_608, maximumTextUTF8ByteCount: Int = 2_000, - maximumRemoteMessageUTF8ByteCount: Int = 2_000, + maximumRemoteMessageUTF8ByteCount: Int = 4_096, maximumRemoteStackUTF8ByteCount: Int = 8_192, abiLimits: WalletABILimits = .standard, cryptoLimits: WalletCryptoLimits = .standard diff --git a/Tests/BSVConformanceTests/WalletWireActionGoOracleTests.swift b/Tests/BSVConformanceTests/WalletWireActionGoOracleTests.swift index f383998..29180c8 100644 --- a/Tests/BSVConformanceTests/WalletWireActionGoOracleTests.swift +++ b/Tests/BSVConformanceTests/WalletWireActionGoOracleTests.swift @@ -30,20 +30,20 @@ final class WalletWireActionGoOracleTests: XCTestCase { outpoint: outpoint, inputDescription: "input", unlockingScriptLength: 107 )], outputs: [WalletCreateActionOutput( - lockingScript: [0x51], satoshis: 1, outputDescription: "output", tags: [""] + lockingScript: [0x51], satoshis: 1, outputDescription: "output", tags: ["t"] )], - labels: [""] + labels: ["l"] )), .signAction(try WalletSignActionRequest( reference: WalletBase64Data([1, 2]), spends: [1: WalletSignActionSpend(unlockingScript: [0x51])] )), .abortAction(WalletAbortActionRequest(reference: try WalletBase64Data([3, 4]))), - .listActions(try WalletListActionsRequest(labels: [""], pagination: .standard)), + .listActions(try WalletListActionsRequest(labels: ["l"], pagination: .standard)), .internalizeAction(try WalletInternalizeActionRequest( transaction: actionOracleAtomicBEEF(limits: beefLimits, id: id), description: "internalize", - labels: [""], + labels: ["l"], outputs: [WalletInternalizeOutput( outputIndex: 0, remittance: .walletPayment(try WalletPaymentRemittance( @@ -53,7 +53,7 @@ final class WalletWireActionGoOracleTests: XCTestCase { )) )] )), - .listOutputs(try WalletListOutputsRequest(basket: "default", tags: [""])), + .listOutputs(try WalletListOutputsRequest(basket: "default", tags: ["t"])), .relinquishOutput(try WalletRelinquishOutputRequest( basket: "default", output: outpoint )), @@ -77,16 +77,39 @@ final class WalletWireActionGoOracleTests: XCTestCase { ) } + // COMP-045: `@bsv/sdk` 4.1.1 writes an empty label or tag with length 0 + // (WalletWireTransceiver.ts:1286 `#writeUTF8Array`). The safe Go adapter + // rejects that form as lossy. Swift follows TypeScript and round-trips it. + let emptyLabelRequest = WalletWireActionRequest.listActions( + try WalletListActionsRequest(labels: [""], pagination: .standard) + ) + let emptyLabelBytes = try WalletWireCodec.encodeActionRequest( + emptyLabelRequest, originator: "oracle", beefLimits: beefLimits + ) + let goEmptyLabel = try oracleActionRequest( + client, operation: "wallet.wire.request.reencode", call: .listActions, + bytes: emptyLabelBytes, sequence: &sequence + ) + XCTAssertFalse(goEmptyLabel.ok) + XCTAssertEqual(goEmptyLabel.error?.category, "invalidArgument") + XCTAssertEqual( + try WalletWireCodec.encodeActionRequest( + WalletWireCodec.decodeActionRequest(emptyLabelBytes, beefLimits: beefLimits).request, + originator: "oracle", beefLimits: beefLimits + ), + emptyLabelBytes + ) + let listedAction = try WalletAction( transactionID: id, satoshis: 0, status: .completed, isOutgoing: false, - description: "", labels: [""], version: 0, lockTime: 0, + description: "", labels: ["l"], version: 0, lockTime: 0, inputs: [WalletActionInput( sourceOutpoint: outpoint, sourceSatoshis: 1, sourceLockingScript: [0x51], unlockingScript: [0x52], inputDescription: "", sequenceNumber: 0 )], outputs: [WalletActionOutput( - satoshis: 1, lockingScript: [0x51], spendable: true, tags: [""], + satoshis: 1, lockingScript: [0x51], spendable: true, tags: ["t"], outputIndex: 0, outputDescription: "", basket: "" )] ) @@ -100,7 +123,7 @@ final class WalletWireActionGoOracleTests: XCTestCase { totalOutputs: 1, outputs: [WalletOutput( satoshis: 1, lockingScript: [0x51], spendable: true, - tags: [""], outpoint: outpoint, labels: [""] + tags: ["t"], outpoint: outpoint, labels: ["l"] )] )), .relinquishOutput(WalletRelinquishOutputResult(relinquished: true)), @@ -109,17 +132,32 @@ final class WalletWireActionGoOracleTests: XCTestCase { let encoded = try WalletWireCodec.encodeActionResult( resultValue, beefLimits: beefLimits ) + let decoded = try WalletWireCodec.decodeActionResult( + encoded, expectedCall: resultValue.call, beefLimits: beefLimits + ) + XCTAssertEqual( + try WalletWireCodec.encodeActionResult(decoded, beefLimits: beefLimits), + encoded, + "Swift result call \(resultValue.call.rawValue)" + ) + if [WalletCall.createAction, .signAction].contains(resultValue.call) { + // COMP-046: Swift writes the `@bsv/sdk` 4.1.1 layout (txid flag + // and display-order txid, tx flag, -1 or counted collections, + // and for createAction the signable flag; + // WalletWireProcessor.ts createAction/signAction). Pinned Go + // expects its own layout and cannot read it. + let response = try oracleActionRequest( + client, operation: "wallet.wire.result.reencode", call: resultValue.call, + bytes: encoded, sequence: &sequence + ) + XCTAssertFalse(response.ok, "result call \(resultValue.call.rawValue)") + continue + } let canonical = try oracleActionBytes( client, operation: "wallet.wire.result.reencode", call: resultValue.call, bytes: encoded, sequence: &sequence ) XCTAssertEqual(canonical, encoded, "result call \(resultValue.call.rawValue)") - XCTAssertEqual( - try WalletWireCodec.decodeActionResult( - canonical, expectedCall: resultValue.call, beefLimits: beefLimits - ).call, - resultValue.call - ) } } @@ -135,6 +173,11 @@ final class WalletWireActionGoOracleTests: XCTestCase { defer { client.close() } var sequence = 50_000 + // These forms are the pinned Go adapter's own strictness. Since + // COMP-045/COMP-046 the Swift codec reads the `@bsv/sdk` 4.1.1 forms + // instead: absent createAction parts, unsorted spends, empty inputs and + // empty labels are legitimate TypeScript traffic, and absent listActions + // scripts are optional (WalletWireActionAdversarialTests covers Swift). let absentTransactionID = [UInt8](arrayLiteral: 0, 0, 0) let response = try oracleActionRequest( client, operation: "wallet.wire.result.reencode", call: .createAction, diff --git a/Tests/BSVConformanceTests/WalletWireCertificateGoOracleTests.swift b/Tests/BSVConformanceTests/WalletWireCertificateGoOracleTests.swift index cc39611..0f68b86 100644 --- a/Tests/BSVConformanceTests/WalletWireCertificateGoOracleTests.swift +++ b/Tests/BSVConformanceTests/WalletWireCertificateGoOracleTests.swift @@ -140,7 +140,9 @@ final class WalletWireCertificateGoOracleTests: XCTestCase { WalletCertificateResult( certificate: fixture.certificate, keyring: fixture.keyring, - verifier: [7] + // The ABI holds hex text; the wire holds the 33 key + // bytes, as `@bsv/sdk` and pinned Go both write them. + verifier: Array(Hex.encode(fixture.verifier.compressedBytes).utf8) ), ] )), @@ -224,6 +226,10 @@ final class WalletWireCertificateGoOracleTests: XCTestCase { XCTAssertFalse(trailingResponse.ok) XCTAssertEqual(trailingResponse.error?.category, "trailingData") + // The pinned Go adapter requires the record count to equal the total. + // COMP-048: `@bsv/sdk` 4.1.1 reads records until the frame ends and + // treats the total as the count of every match, so Swift reads this + // frame as an empty page of a two-certificate result. let multiDiscovery = [UInt8](arrayLiteral: 0, 2) let discoveryResponse = try certificateOracleRequest( client, @@ -234,6 +240,13 @@ final class WalletWireCertificateGoOracleTests: XCTestCase { ) XCTAssertFalse(discoveryResponse.ok) XCTAssertEqual(discoveryResponse.error?.category, "invalidArgument") + guard case .discoverByIdentityKey(let page) = try WalletWireCodec.decodeCertificateResult( + multiDiscovery, expectedCall: .discoverByIdentityKey + ) else { + return XCTFail("expected a discovery result") + } + XCTAssertEqual(page.totalCertificates, 2) + XCTAssertTrue(page.certificates.isEmpty) } } diff --git a/Tests/BSVConformanceTests/WalletWireGoOracleTests.swift b/Tests/BSVConformanceTests/WalletWireGoOracleTests.swift index e9f6e76..abd4621 100644 --- a/Tests/BSVConformanceTests/WalletWireGoOracleTests.swift +++ b/Tests/BSVConformanceTests/WalletWireGoOracleTests.swift @@ -263,10 +263,20 @@ final class WalletWireGoOracleTests: XCTestCase { bytes: omittedSeekBytes, sequence: &sequence ) - XCTAssertEqual(goOmittedSeekBytes, Array(omittedSeekBytes.dropLast()) + [0]) + // COMP-045: Swift writes an omitted `privileged` as -1, as `@bsv/sdk` + // 4.1.1 does (WalletWireTransceiver.ts `#encodePrivilegedParams` + // writes a byte only for a boolean). Pinned Go stores both flags as + // Bool and writes 00 for each. + var goOmittedSeekExpected = omittedSeekBytes + goOmittedSeekExpected[goOmittedSeekExpected.count - 4] = 0 + goOmittedSeekExpected[goOmittedSeekExpected.count - 1] = 0 + XCTAssertEqual(omittedSeekBytes.suffix(4), [0xFF, 0xFF, 0xFF, 0xFF]) + XCTAssertEqual(goOmittedSeekBytes, goOmittedSeekExpected) // Pinned Go preserves its optional-Boolean absence sentinel. Swift - // accepts that inbound form as false and emits the canonical 00 form. + // reads it as false and, like `@bsv/sdk` 4.1.1, writes false as absent + // (WalletWireTransceiver.ts:867 and :1225 write forSelf only for a + // boolean; COMP-045). An explicit privileged 00 likewise comes back as -1. let absentGetPublicKey = [UInt8](arrayLiteral: WalletCall.getPublicKey.rawValue, 0, 0) + keyParameters + [0xFF, 0] @@ -285,7 +295,7 @@ final class WalletWireGoOracleTests: XCTestCase { } XCTAssertFalse(forSelf) var canonicalGetPublicKey = absentGetPublicKey - canonicalGetPublicKey[2 + 1 + keyParameters.count] = 0 + canonicalGetPublicKey[3 + keyParameters.count - 2] = 0xFF XCTAssertEqual( try WalletWireCodec.encodeKeyQueryRequest( decodedGetPublicKey.request, @@ -322,7 +332,7 @@ final class WalletWireGoOracleTests: XCTestCase { } XCTAssertFalse(verifySignature.forSelf) var canonicalVerifySignature = absentVerifySignature - canonicalVerifySignature[2 + keyParameters.count] = 0 + canonicalVerifySignature[2 + keyParameters.count - 2] = 0xFF XCTAssertEqual( try WalletWireCodec.encodeKeyQueryRequest( decodedVerifySignature.request, diff --git a/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift b/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift index ba54add..d6f3979 100644 --- a/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift +++ b/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift @@ -73,12 +73,15 @@ struct WalletWireSubstrateTests { limits: limits ) - await #expect(throws: WalletWireError.trailingBytes) { - try await processor.transmit( - malformed, - maximumResponseByteCount: limits.maximumFrameByteCount - ) - } + // `@bsv/sdk` 4.1.1 answers a malformed request in-band: + // WalletWireProcessor.ts:2478 throws, its catch writes code 1 with + // "Wallet Wire getHeight request contains trailing data". + let response = try await processor.transmit( + malformed, + maximumResponseByteCount: limits.maximumFrameByteCount + ) + let message = "Wallet Wire getHeight request contains trailing data" + #expect(response == [1, UInt8(message.utf8.count)] + Array(message.utf8) + [0]) #expect(await recorder.snapshot().isEmpty) } @@ -383,15 +386,18 @@ struct WalletWireSubstrateTests { let defaultDiscovery = WalletRequest.certificate(.discoverByIdentityKey(.init( identityKey: identityKey ))) + // BRC-100 discovery defaults seekPermission to true, as every other + // call does (packages/sdk/src/wallet/Wallet.interfaces.ts:1021 and + // :1041 declare `seekPermission?: BooleanDefaultTrue`; W8). #expect(defaultDiscovery.rawSeekPermission == nil) - #expect(defaultDiscovery.effectiveSeekPermission == false) + #expect(defaultDiscovery.effectiveSeekPermission == true) let explicitDiscovery = WalletRequest.certificate(.discoverByAttributes(try .init( attributes: [:], - seekPermission: true + seekPermission: false ))) - #expect(explicitDiscovery.rawSeekPermission == true) - #expect(explicitDiscovery.effectiveSeekPermission == true) + #expect(explicitDiscovery.rawSeekPermission == false) + #expect(explicitDiscovery.effectiveSeekPermission == false) let notApplicable: [WalletRequest] = [ .action(.abortAction(WalletAbortActionRequest( diff --git a/Tests/BSVWalletTests/Wire/WalletWireActionAdversarialTests.swift b/Tests/BSVWalletTests/Wire/WalletWireActionAdversarialTests.swift index b4aacaa..0195fbb 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireActionAdversarialTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireActionAdversarialTests.swift @@ -35,20 +35,29 @@ struct WalletWireActionAdversarialTests { } } - @Test func rejectsUnsortedSpendsAndInvalidDiscriminators() throws { + @Test func acceptsUnsortedSpendsButRejectsDuplicatesAndInvalidDiscriminators() throws { let negativeOne = [UInt8](repeating: 0xff, count: 9) + // `@bsv/sdk` writes spends in `Object.keys(args.spends)` order + // (packages/sdk/src/wallet/substrates/WalletWireTransceiver.ts:357), + // so an unsorted index list is legitimate traffic. let unsorted = actionWireBytes([ [2, 0, 2, 2, 0], negativeOne, [1, 0], negativeOne, [0, 0], ]) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "unsorted or duplicate spend index" - )) { - try WalletWireCodec.decodeActionRequest( - unsorted, beefLimits: actionBEEFLimits() - ) + #expect(throws: Never.self) { + try WalletWireCodec.decodeActionRequest(unsorted, beefLimits: actionBEEFLimits()) + } + let duplicate = actionWireBytes([ + [2, 0, 2, 1, 0], negativeOne, [1, 0], negativeOne, [0, 0], + ]) + #expect(throws: WalletWireError.nonRoundTrippableValue(kind: "duplicate spend index")) { + try WalletWireCodec.decodeActionRequest(duplicate, beefLimits: actionBEEFLimits()) } - let invalidMode = [UInt8](arrayLiteral: 6, 0, 0, 0, 3) + // listOutputs: basket "", no tags, tag query mode 3, then absent include, + // include flags, limit, offset and seekPermission. + let invalidMode = actionWireBytes([ + [6, 0, 0, 0, 3, 0xff, 0xff, 0xff, 0xff], negativeOne, negativeOne, [0xff], + ]) #expect(throws: WalletWireError.invalidDiscriminator( kind: "tag query mode", value: 3 )) { @@ -74,7 +83,7 @@ struct WalletWireActionAdversarialTests { } } - @Test func rejectsInvalidBEEFAndNonRoundTrippableGoUnions() throws { + @Test func rejectsInvalidBEEFAndAcceptsAbsentCreateActionParts() throws { let invalidAtomic = [UInt8](arrayLiteral: 5, 0, 1, 0, 0, 0, 0, 0xff) #expect(throws: WalletWireError.nonRoundTrippableValue(kind: "Atomic BEEF")) { try WalletWireCodec.decodeActionRequest( @@ -82,44 +91,85 @@ struct WalletWireActionAdversarialTests { ) } - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "absent pinned Go transaction ID" - )) { + // `@bsv/sdk` 4.1.1 createAction result with every part absent + // (WalletWireProcessor.ts createAction: txid flag 0, tx flag 0, + // noSendChange -1, sendWithResults -1, signableTransaction flag 0). G3. + let negativeOne = [UInt8](repeating: 0xff, count: 9) + let empty = actionWireBytes([[0, 0, 0], negativeOne, negativeOne, [0]]) + let decoded = try WalletWireCodec.decodeActionResult( + empty, expectedCall: .createAction, beefLimits: actionBEEFLimits() + ) + guard case .createAction(let result) = decoded else { + Issue.record("expected a createAction result") + return + } + #expect(result.transactionID == nil) + #expect(result.signableTransaction == nil) + #expect(try WalletWireCodec.encodeActionResult(decoded, beefLimits: actionBEEFLimits()) == empty) + + // The Go wire's extra leading byte is no longer read: [0, 0, 0] stops + // at the sendWithResults count. + #expect(throws: WalletWireError.truncated) { try WalletWireCodec.decodeActionResult( [0, 0, 0], expectedCall: .createAction, beefLimits: actionBEEFLimits() ) } } - @Test func rejectsFalseImplicitResultsAndTotalMismatches() throws { - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "false abort-action result" - )) { - try WalletWireCodec.encodeActionResult( - .abortAction(WalletAbortActionResult(aborted: false)), - beefLimits: actionBEEFLimits() - ) + @Test func answersAbortRefusalInBandAndAllowsShortPages() throws { + // `@bsv/sdk` 4.1.1 refuses an abort with code 8 and a fixed message + // (packages/sdk/src/wallet/substrates/WalletWireProcessor.ts:817), and + // its transceiver maps code 8 to `aborted: false` + // (WalletWireTransceiver.ts:412). W5. + let message = "The wallet refused to abort this action because it has already been broadcast" + let refusal = try WalletWireCodec.encodeActionResult( + .abortAction(WalletAbortActionResult(aborted: false)), + beefLimits: actionBEEFLimits() + ) + #expect(refusal == [8, UInt8(message.utf8.count)] + Array(message.utf8) + [0]) + let decodedRefusal = try WalletWireCodec.decodeActionResult( + refusal, expectedCall: .abortAction, beefLimits: actionBEEFLimits() + ) + guard case .abortAction(let abort) = decodedRefusal else { + Issue.record("expected an abortAction result") + return } - let mismatch = try WalletListActionsResult(totalActions: 1, actions: []) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "total actions mismatch" - )) { - try WalletWireCodec.encodeActionResult( - .listActions(mismatch), beefLimits: actionBEEFLimits() + #expect(abort.aborted == false) + + // A page shorter than its total is an ordinary paginated answer. + let shortPage = try WalletListActionsResult(totalActions: 1, actions: []) + #expect(try WalletWireCodec.encodeActionResult( + .listActions(shortPage), beefLimits: actionBEEFLimits() + ) == [0, 1]) + + // More records than the declared total is still rejected. + let absent = [UInt8](repeating: 0xff, count: 9) + let overfull = actionWireBytes([ + [0, 0], [UInt8](repeating: 0, count: 32), [0, 1, 0, 0], absent, [0, 0], absent, absent, + ]) + #expect(throws: WalletWireResultRejection.self) { + try WalletWireCodec.decodeActionResult( + overfull, expectedCall: .listActions, beefLimits: actionBEEFLimits() ) } } - @Test func rejectsCreateActionNilEmptyCollisionsOnEncodeAndDecode() throws { + @Test func keepsEmptyCreateActionInputsAndRejectsEmptyLockingScripts() throws { let beefLimits = try actionBEEFLimits() + // `@bsv/sdk` writes `inputs: []` as count 0 and an omitted array as -1 + // (WalletWireTransceiver.ts createAction `args.inputs != null`), so + // both forms round-trip. let emptyInputs = try WalletCreateActionRequest(description: "", inputs: []) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "empty create-action inputs" - )) { - try WalletWireCodec.encodeActionRequest( - .createAction(emptyInputs), originator: "", beefLimits: beefLimits - ) + let emptyInputsEncoded = try WalletWireCodec.encodeActionRequest( + .createAction(emptyInputs), originator: "", beefLimits: beefLimits + ) + guard case .createAction(let emptyInputsDecoded) = try WalletWireCodec.decodeActionRequest( + emptyInputsEncoded, beefLimits: beefLimits + ).request else { + Issue.record("expected a createAction request") + return } + #expect(emptyInputsDecoded.inputs == []) let emptyOutput = try WalletCreateActionRequest( description: "", @@ -143,11 +193,13 @@ struct WalletWireActionAdversarialTests { emptyInputsFrame.append(contentsOf: absent) } emptyInputsFrame.append(0) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "empty create-action inputs" - )) { - try WalletWireCodec.decodeActionRequest(emptyInputsFrame, beefLimits: beefLimits) + guard case .createAction(let emptyFrameRequest) = try WalletWireCodec.decodeActionRequest( + emptyInputsFrame, beefLimits: beefLimits + ).request else { + Issue.record("expected a createAction request") + return } + #expect(emptyFrameRequest.inputs == []) var emptyScriptFrame: [UInt8] = [1, 0, 0] emptyScriptFrame.append(contentsOf: absent) @@ -167,106 +219,67 @@ struct WalletWireActionAdversarialTests { } } - @Test func rejectsPresentZeroLengthStringSliceEntries() throws { - let request = [UInt8](arrayLiteral: WalletCall.listActions.rawValue, 0, 1, 0) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "zero-length labels entry" - )) { - try WalletWireCodec.decodeActionRequest(request, beefLimits: actionBEEFLimits()) - } - - let result = actionWireBytes([ - [0, 1], [UInt8](repeating: 0, count: 32), [0, 1, 0, 0, 1, 0], - ]) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "zero-length labels entry" - )) { - try WalletWireCodec.decodeActionResult( - result, expectedCall: .listActions, beefLimits: actionBEEFLimits() - ) + @Test func readsZeroLengthAndAbsentStringSliceEntriesAsEmpty() throws { + // `@bsv/sdk` writes an empty label or tag with length 0 + // (WalletWireTransceiver.ts `#writeUTF8Array`), and earlier Go and + // Swift peers wrote -1. Both read as "", and "" is written as 0. + let limits = WalletWireLimits.standard + for entry in [[UInt8(0)], [UInt8](repeating: 0xff, count: 9)] { + var reader = WalletWireReader([1] + entry) + #expect(try walletWireReadStringSlice( + from: &reader, kind: "labels", optional: false, limits: limits + ) == [""]) + #expect(reader.isAtEnd) } + var writer = WalletWireWriter() + try walletWireWriteStringSlice([""], kind: "labels", to: &writer, limits: limits) + #expect(writer.bytes == [1, 0]) } - @Test func rejectsPinnedGoUnreadableListActionScriptSentinels() throws { - let absent = [UInt8](repeating: 0xff, count: 9) - let prefix = actionWireBytes([ - [0, 1], [UInt8](repeating: 0, count: 32), [0, 1, 0, 0], absent, [0, 0], - ]) - let inputPrefix = actionWireBytes([ - prefix, [1], [UInt8](repeating: 0, count: 32), [0, 0], - ]) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "absent action source locking script" - )) { - try WalletWireCodec.decodeActionResult( - actionWireBytes([inputPrefix, absent]), - expectedCall: .listActions, beefLimits: actionBEEFLimits() - ) - } - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "absent action unlocking script" - )) { - try WalletWireCodec.decodeActionResult( - actionWireBytes([inputPrefix, [1, 0x51], absent]), - expectedCall: .listActions, beefLimits: actionBEEFLimits() - ) - } - - let outputPrefix = actionWireBytes([prefix, absent, [1, 0, 0]]) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "absent action output locking script" - )) { - try WalletWireCodec.decodeActionResult( - actionWireBytes([outputPrefix, absent]), - expectedCall: .listActions, beefLimits: actionBEEFLimits() - ) - } - + @Test func roundTripsAbsentListActionScripts() throws { + // `@bsv/sdk` 4.1.1 writes an absent listActions script as -1 and reads + // it back as undefined (WalletWireProcessor.ts listActions inputs and + // outputs). G6. let outpoint = Outpoint(transactionID: try actionTransactionID(), outputIndex: 0) - func action( - inputs: [WalletActionInput]? = nil, - outputs: [WalletActionOutput]? = nil - ) throws -> WalletAction { - try WalletAction( - transactionID: try actionTransactionID(), satoshis: 0, status: .completed, - isOutgoing: false, description: "", version: 0, lockTime: 0, - inputs: inputs, outputs: outputs - ) - } - let lossyActions: [(WalletAction, String)] = [ - (try action(inputs: [WalletActionInput( + let action = try WalletAction( + transactionID: try actionTransactionID(), satoshis: 0, status: .completed, + isOutgoing: false, description: "", version: 0, lockTime: 0, + inputs: [WalletActionInput( sourceOutpoint: outpoint, sourceSatoshis: 0, sourceLockingScript: nil, - unlockingScript: [0x51], inputDescription: "", sequenceNumber: 0 - )]), "absent or empty action source locking script"), - (try action(inputs: [WalletActionInput( - sourceOutpoint: outpoint, sourceSatoshis: 0, sourceLockingScript: [0x51], unlockingScript: nil, inputDescription: "", sequenceNumber: 0 - )]), "absent or empty action unlocking script"), - (try action(outputs: [WalletActionOutput( + )], + outputs: [WalletActionOutput( satoshis: 0, lockingScript: nil, spendable: true, tags: [], outputIndex: 0, outputDescription: "", basket: "" - )]), "absent or empty action output locking script"), - ] - for (action, kind) in lossyActions { - #expect(throws: WalletWireError.nonRoundTrippableValue(kind: kind)) { - try WalletWireCodec.encodeActionResult( - .listActions(WalletListActionsResult(totalActions: 1, actions: [action])), - beefLimits: actionBEEFLimits() - ) - } + )] + ) + let result = WalletWireActionResult.listActions( + try WalletListActionsResult(totalActions: 1, actions: [action]) + ) + let encoded = try WalletWireCodec.encodeActionResult(result, beefLimits: actionBEEFLimits()) + let decoded = try WalletWireCodec.decodeActionResult( + encoded, expectedCall: .listActions, beefLimits: actionBEEFLimits() + ) + guard case .listActions(let page) = decoded, + let input = page.actions.first?.inputs?.first, + let output = page.actions.first?.outputs?.first else { + Issue.record("expected one listActions input and output") + return } + #expect(input.sourceLockingScript == nil) + #expect(input.unlockingScript == nil) + #expect(output.lockingScript == nil) + #expect(try WalletWireCodec.encodeActionResult(decoded, beefLimits: actionBEEFLimits()) == encoded) } - @Test func rejectsRemainingHostileActionResultForms() throws { + @Test func rejectsHostileActionResultForms() throws { let absent = [UInt8](repeating: 0xff, count: 9) - let signable = actionWireBytes([ - [0, 0, 1], [UInt8](repeating: 0, count: 32), [0], absent, [0, 1], - ]) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "pinned Go signable create-action result" + let badSignableFlag = actionWireBytes([[0, 0, 0], absent, absent, [2]]) + #expect(throws: WalletWireError.invalidDiscriminator( + kind: "signable transaction", value: 2 )) { try WalletWireCodec.decodeActionResult( - signable, expectedCall: .createAction, beefLimits: actionBEEFLimits() + badSignableFlag, expectedCall: .createAction, beefLimits: actionBEEFLimits() ) } @@ -289,13 +302,22 @@ struct WalletWireActionAdversarialTests { ) } - let hostileCount = [UInt8](arrayLiteral: 0, 0xfd, 0x11, 0x27) - #expect(throws: WalletWireError.countLimitExceeded( - kind: "outputs", actual: 10_001, maximum: 10_000 - )) { - try WalletWireCodec.decodeActionResult( - hostileCount, expectedCall: .listOutputs, beefLimits: actionBEEFLimits() - ) + // The total counts every matching output, not the records in this frame + // (WalletWireTransceiver.ts listOutputs reads records until the frame + // ends), so a large total with no records is a valid page. + let largeTotal = actionWireBytes([[0, 0xfd, 0x11, 0x27], absent]) + guard case .listOutputs(let page) = try WalletWireCodec.decodeActionResult( + largeTotal, expectedCall: .listOutputs, beefLimits: actionBEEFLimits() + ) else { + Issue.record("expected a listOutputs result") + return + } + #expect(page.totalOutputs == 10_001) + #expect(page.outputs.isEmpty) + + // Records beyond the page limit are rejected before more are read. + #expect(throws: WalletWireResultRejection.self) { + try walletWireRequirePageCapacity(10, limit: 10, call: "listOutputs") } } } diff --git a/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift b/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift index ecd1d8c..a5200cb 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift @@ -36,12 +36,17 @@ final class WalletWireAdversarialTests: XCTestCase { func testCounterpartyAndSignatureDiscriminatorsAreStrict() throws { let commonPrefix = [UInt8](arrayLiteral: 0, 5) + Array("wire1".utf8) + [1, 0x6B] let commonSuffix = [UInt8](arrayLiteral: 0, 0xFF) - let payload = commonPrefix + [0] + commonSuffix + [0, 0] - XCTAssertThrowsError(try WalletWireCodec.decodeKeyQueryRequest([15, 0] + payload)) { error in - XCTAssertEqual( - error as? WalletWireError, - .invalidDiscriminator(kind: "counterparty", value: 0) - ) + // 0x00 is the omitted counterparty `@bsv/sdk` writes + // (WalletWireTransceiver.ts encodes `undefined` as 0), so it decodes to + // the call's default. Every byte other than 0, 2, 3, 11 and 12 is invalid. + for discriminator in [UInt8(1), 4, 10, 13, 255] { + let payload = commonPrefix + [discriminator] + commonSuffix + [0, 0] + XCTAssertThrowsError(try WalletWireCodec.decodeKeyQueryRequest([15, 0] + payload)) { error in + XCTAssertEqual( + error as? WalletWireError, + .invalidDiscriminator(kind: "counterparty", value: discriminator) + ) + } } let validCommon = commonPrefix + [0x0B] + commonSuffix @@ -117,12 +122,19 @@ final class WalletWireAdversarialTests: XCTestCase { } func testNonRoundTrippableFalseAndEmptyVerifyDataAreRejected() throws { - XCTAssertThrowsError(try WalletWireCodec.encodeKeyQueryResult( - .verifyHMAC(WalletVerifyHMACResult(valid: false)) - )) - XCTAssertThrowsError(try WalletWireCodec.encodeKeyQueryResult( - .verifySignature(WalletVerifySignatureResult(valid: false)) - )) + // A false verification is the error frame `@bsv/sdk` 4.1.1 sends + // (ProtoWallet.ts throws "HMAC is not valid" / "Signature is not valid", + // WalletWireProcessor.ts writes it as code 1 with an empty stack). + XCTAssertEqual( + try WalletWireCodec.encodeKeyQueryResult(.verifyHMAC(WalletVerifyHMACResult(valid: false))), + [1, 17] + Array("HMAC is not valid".utf8) + [0] + ) + XCTAssertEqual( + try WalletWireCodec.encodeKeyQueryResult( + .verifySignature(WalletVerifySignatureResult(valid: false)) + ), + [1, 22] + Array("Signature is not valid".utf8) + [0] + ) XCTAssertThrowsError(try WalletWireCodec.encodeKeyQueryResult( .waitForAuthentication(WalletAuthenticatedResult(authenticated: false)) )) diff --git a/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift b/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift index 3d3b7ca..fcfe9de 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift @@ -33,7 +33,7 @@ struct WalletWireCertificateAdversarialTests { } } - @Test func rejectsNoncanonicalCountsHostileCountsAndUnsortedMaps() throws { + @Test func rejectsNoncanonicalCountsHostileCountsAndDuplicateMapNames() throws { #expect(throws: WalletWireError.noncanonicalCompactSize) { try WalletWireCodec.decodeCertificateRequest( [WalletCall.discoverByAttributes.rawValue, 0, 0xfd, 0, 0] @@ -48,6 +48,9 @@ struct WalletWireCertificateAdversarialTests { ) } + // `@bsv/sdk` writes maps in insertion order + // (packages/sdk/src/wallet/substrates/WalletWireTransceiver.ts:1962 iterates + // `Object.keys(args.attributes)`), so unsorted names are accepted. var unsorted = WalletWireWriter() unsorted.writeCompactSize(2) try unsorted.writeString("zeta") @@ -57,11 +60,28 @@ struct WalletWireCertificateAdversarialTests { unsorted.writeOptionalUInt32(nil) unsorted.writeOptionalUInt32(nil) unsorted.writeOptionalBoolean(nil) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "unsorted or duplicate certificate attributes" - )) { + let decoded = try WalletWireCodec.decodeCertificateRequest( + [WalletCall.discoverByAttributes.rawValue, 0] + unsorted.bytes + ) + guard case .discoverByAttributes(let attributes) = decoded.request else { + Issue.record("expected discoverByAttributes") + return + } + #expect(attributes.attributes.count == 2) + + // A repeated name has no map value and is still rejected. + var duplicate = WalletWireWriter() + duplicate.writeCompactSize(2) + try duplicate.writeString("alpha") + try duplicate.writeString("first") + try duplicate.writeString("alpha") + try duplicate.writeString("second") + duplicate.writeOptionalUInt32(nil) + duplicate.writeOptionalUInt32(nil) + duplicate.writeOptionalBoolean(nil) + #expect(throws: WalletWireError.self) { try WalletWireCodec.decodeCertificateRequest( - [WalletCall.discoverByAttributes.rawValue, 0] + unsorted.bytes + [WalletCall.discoverByAttributes.rawValue, 0] + duplicate.bytes ) } } diff --git a/Tests/BSVWalletTests/Wire/WalletWireCertificateTests.swift b/Tests/BSVWalletTests/Wire/WalletWireCertificateTests.swift index 937c3c8..a33b5fa 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireCertificateTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireCertificateTests.swift @@ -138,7 +138,10 @@ final class WalletWireCertificateTests: XCTestCase { WalletCertificateResult( certificate: fixture.certificate, keyring: fixture.keyring, - verifier: [7, 8] + // The ABI carries the verifier as hex text; the wire + // carries the 33 key bytes (WalletWireProcessor.ts:2144 + // writes `toArray(cert.verifier, 'hex')`). + verifier: Array(Hex.encode(fixture.verifier.compressedBytes).utf8) ), ] )), diff --git a/Tests/BSVWalletTests/Wire/WalletWireKeyQueryTests.swift b/Tests/BSVWalletTests/Wire/WalletWireKeyQueryTests.swift index efc7c80..ca4fd12 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireKeyQueryTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireKeyQueryTests.swift @@ -185,7 +185,11 @@ final class WalletWireKeyQueryTests: XCTestCase { } } - func testAbsentForSelfNormalizesToExplicitFalse() throws { + /// `@bsv/sdk` 4.1.1 writes an omitted `forSelf` as -1 + /// (packages/sdk/src/wallet/substrates/WalletWireTransceiver.ts:867 and + /// :1225 write a byte only when `typeof args.forSelf === 'boolean'`), and + /// TS callers omit `false`. Swift writes `false` as absent and reads an explicit 0 as false. + func testFalseForSelfIsWrittenAbsentAndExplicitFalseNormalizes() throws { let protocolID = try walletTestProtocol("wire normalization") let keyID = try walletTestKeyID("wire-key") @@ -209,10 +213,10 @@ final class WalletWireKeyQueryTests: XCTestCase { limits: .standard ) let getPublicKeyForSelfOffset = getPublicKeyReader.position - XCTAssertEqual(getPublicKeyFrame.parameters[getPublicKeyForSelfOffset], 0) + XCTAssertEqual(getPublicKeyFrame.parameters[getPublicKeyForSelfOffset], 0xFF) var absentGetPublicKeyParameters = getPublicKeyFrame.parameters - absentGetPublicKeyParameters[getPublicKeyForSelfOffset] = 0xFF + absentGetPublicKeyParameters[getPublicKeyForSelfOffset] = 0 let absentGetPublicKey = try WalletWireCodec.encodeRequestFrame(.init( call: .getPublicKey, originator: "", @@ -245,10 +249,10 @@ final class WalletWireKeyQueryTests: XCTestCase { var verifyReader = WalletWireReader(verifyFrame.parameters) _ = try walletWireDecodeKeyParameters(from: &verifyReader, limits: .standard) let verifyForSelfOffset = verifyReader.position - XCTAssertEqual(verifyFrame.parameters[verifyForSelfOffset], 0) + XCTAssertEqual(verifyFrame.parameters[verifyForSelfOffset], 0xFF) var absentVerifyParameters = verifyFrame.parameters - absentVerifyParameters[verifyForSelfOffset] = 0xFF + absentVerifyParameters[verifyForSelfOffset] = 0 let absentVerify = try WalletWireCodec.encodeRequestFrame(.init( call: .verifySignature, originator: "", diff --git a/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift b/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift new file mode 100644 index 0000000..65a6e9f --- /dev/null +++ b/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift @@ -0,0 +1,295 @@ +import Foundation +import BSVCore +import BSVKeys +import BSVTransaction +@testable import BSVWallet +import Testing + +/// Fixed vectors for the `@bsv/sdk` 4.1.1 wallet behaviour Swift now follows. +/// Each cites the TypeScript source in `packages/sdk/src/wallet`. These run +/// without the TypeScript toolchain; `WalletWireTypeScriptOracleTests` checks +/// the same behaviour against live TypeScript when its vectors are provided. +@Suite("Wallet wire and ProtoWallet vectors from @bsv/sdk 4.1.1") +struct WalletWireTypeScript41VectorTests { + private let absent = [UInt8](repeating: 0xff, count: 9) + + // MARK: W2 list totals + + /// substrates/WalletWireTransceiver.ts:455-467 (listActions), :726-742 + /// (listOutputs), :1617-1659 (listCertificates), :1818-1896 (discovery): + /// read the total, then records until the frame ends. + @Test func listTotalsCountEveryMatchNotTheRecordsInTheFrame() throws { + guard case .listActions(let actions) = try WalletWireCodec.decodeActionResult( + [0x00, 0xfa], expectedCall: .listActions, beefLimits: actionBEEFLimits() + ) else { + Issue.record("expected listActions") + return + } + #expect(actions.totalActions == 250) + #expect(actions.actions.isEmpty) + #expect(try WalletWireCodec.encodeActionResult( + .listActions(actions), beefLimits: actionBEEFLimits() + ) == [0x00, 0xfa]) + + let outputsFrame = [0x00, 0x03] + absent + guard case .listOutputs(let outputs) = try WalletWireCodec.decodeActionResult( + outputsFrame, expectedCall: .listOutputs, beefLimits: actionBEEFLimits() + ) else { + Issue.record("expected listOutputs") + return + } + #expect(outputs.totalOutputs == 3) + #expect(outputs.outputs.isEmpty) + #expect(try WalletWireCodec.encodeActionResult( + .listOutputs(outputs), beefLimits: actionBEEFLimits() + ) == outputsFrame) + + for call in [WalletCall.listCertificates, .discoverByIdentityKey, .discoverByAttributes] { + let decoded = try WalletWireCodec.decodeCertificateResult([0x00, 0x07], expectedCall: call) + switch decoded { + case .listCertificates(let page): + #expect(page.totalCertificates == 7) + #expect(page.certificates.isEmpty) + case .discoverByIdentityKey(let page), .discoverByAttributes(let page): + #expect(page.totalCertificates == 7) + #expect(page.certificates.isEmpty) + default: + Issue.record("unexpected result for call \(call.rawValue)") + } + #expect(try WalletWireCodec.encodeCertificateResult(decoded) == [0x00, 0x07]) + } + } + + // MARK: W3 BRC-112 balance + + /// moduleBalanceQuery.ts:1-21 defines the basket pattern; + /// WalletWireProcessor.ts:1296-1308 writes the balance as a full varint. + @Test func balanceBasketsCarryAUInt64Balance() throws { + #expect(walletIsBalanceBasket("balance default")) + #expect(walletIsBalanceBasket("p btms balance tokens")) + #expect(!walletIsBalanceBasket("balance")) + #expect(!walletIsBalanceBasket("p btms tokens")) + + let request = WalletWireActionRequest.listOutputs( + try WalletListOutputsRequest(basket: "balance default") + ) + let frame = [0x00, 0xff, 0x00, 0xf2, 0x05, 0x2a, 0x01, 0x00, 0x00, 0x00] + absent + let decoded = try WalletWireCodec.decodeActionResult( + frame, expectedCall: .listOutputs, request: request, beefLimits: actionBEEFLimits() + ) + guard case .listOutputs(let balance) = decoded else { + Issue.record("expected listOutputs") + return + } + #expect(balance.totalOutputs == 5_000_000_000) + #expect(balance.outputs.isEmpty) + #expect(try WalletWireCodec.encodeActionResult( + decoded, request: request, beefLimits: actionBEEFLimits() + ) == frame) + + let codec = try WalletBRC100JSONCodec(beefLimits: actionBEEFLimits()) + let route = try #require(WalletJSONRoute(methodName: "listOutputs")) + let json = #"{"outputs":[],"totalOutputs":5000000000}"# + let jsonResult = try codec.decodeResult(route: route, from: Array(json.utf8)) + guard case .action(.listOutputs(let jsonBalance)) = jsonResult else { + Issue.record("expected a JSON listOutputs result") + return + } + #expect(jsonBalance.totalOutputs == 5_000_000_000) + #expect(String(decoding: try codec.encodeResult(jsonResult), as: UTF8.self) == json) + } + + // MARK: W4 and G5 in-band processor errors + + /// substrates/WalletWireTransceiver.ts:124-152 downgrades only on code 2 or + /// code 1 with exactly "Invalid call code: 29"; WalletWireProcessor.ts + /// :2413-2441 answers parse failures in-band with code 1 and an empty stack. + @Test func processorAnswersUnknownCallsAndBadFramesInBand() async throws { + let processor = try vectorProcessor(result: .keyQuery(.getHeight(WalletGetHeightResult(height: 1)))) + let probe = try await processor.transmit([0x1d, 0x00, 0x00, 0x01], maximumResponseByteCount: 1 << 16) + #expect(probe == errorFrame(code: 1, "Invalid call code: 29")) + + let unknown = try await processor.transmit([0x1e, 0x00], maximumResponseByteCount: 1 << 16) + #expect(unknown == errorFrame(code: 1, "Invalid call code: 30")) + + let trailing = try await processor.transmit([0x19, 0x00, 0x00], maximumResponseByteCount: 1 << 16) + #expect(trailing == errorFrame(code: 1, "Wallet Wire getHeight request contains trailing data")) + + let truncated = try await processor.transmit([0x19, 0x05, 0x61], maximumResponseByteCount: 1 << 16) + #expect(truncated == errorFrame(code: 1, "ReaderUint8Array read exceeds available data")) + } + + /// ProtoWallet.ts throws "HMAC is not valid" / "Signature is not valid"; + /// WalletWireProcessor.ts:1566 and :1643 send them as code 1. + @Test func falseVerificationsCrossTheWireAsErrorFrames() async throws { + let hmacProcessor = try vectorProcessor( + result: .keyQuery(.verifyHMAC(WalletVerifyHMACResult(valid: false))) + ) + let request = try WalletWireCodec.encodeKeyQueryRequest(.verifyHMAC(WalletVerifyHMACRequest( + protocolID: try walletTestProtocol("wire test"), + keyID: try walletTestKeyID("key"), + data: [1], + hmac: try WalletHMAC(bytes: [UInt8](repeating: 1, count: 32)) + )), originator: "") + let response = try await hmacProcessor.transmit(request, maximumResponseByteCount: 1 << 16) + #expect(response == errorFrame(code: 1, "HMAC is not valid")) + guard case .verifyHMAC(let decoded) = try { + do { return try WalletWireCodec.decodeKeyQueryResult(response, expectedCall: .verifyHMAC) } + catch let remote as WalletWireRemoteError { + #expect(remote.message == "HMAC is not valid") + return .verifyHMAC(WalletVerifyHMACResult(valid: false)) + } + }() else { + Issue.record("expected verifyHMAC") + return + } + #expect(decoded.valid == false) + } + + // MARK: G2 display-order transaction IDs + + /// WalletWireProcessor.ts:604 and :640 write `toArray(txid, 'hex')`, the + /// display order, not the internal (wire) order. + @Test func resultTransactionIDsUseDisplayOrder() throws { + let id = try TransactionID(wireBytes: Array(0..<32)) + let encoded = try WalletWireCodec.encodeActionResult( + .signAction(try WalletSignActionResult(transactionID: id)), + beefLimits: actionBEEFLimits() + ) + #expect(Array(encoded.prefix(34)) == [0x00, 0x01] + Array((0..<32).reversed())) + #expect(Array(encoded[2..<34]) == id.displayBytes) + } + + // MARK: W6 revealSpecificKeyLinkage counterparty + + /// ProtoWallet.ts:235-240 resolves `self` to the identity key and `anyone` + /// to the public key of private key 1. + @Test func specificLinkageResolvesSelfAndAnyone() async throws { + let root = try walletTestPrivateKey(7) + let verifier = try walletTestPrivateKey(17).publicKey + let wallet = ProtoWallet(rootKey: root) + let protocolID = try walletTestProtocol("linkage vectors") + let keyID = try walletTestKeyID("1") + let forSelf = try await wallet.revealSpecificKeyLinkage(WalletRevealSpecificKeyLinkageRequest( + counterparty: .self, verifier: verifier, protocolID: protocolID, keyID: keyID + )) + #expect(forSelf.counterparty == forSelf.prover) + #expect(forSelf.prover == root.publicKey) + let forAnyone = try await wallet.revealSpecificKeyLinkage(WalletRevealSpecificKeyLinkageRequest( + counterparty: .anyone, verifier: verifier, protocolID: protocolID, keyID: keyID + )) + #expect( + Hex.encode(forAnyone.counterparty.compressedBytes) + == "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + ) + } + + // MARK: W10 spendable listOutputs extension + + /// substrates/WalletWireTransceiver.ts:745-757 appends `01`; + /// WalletWireProcessor.ts:1316-1327 answers with a -1 marker, the total, + /// the BEEF, and a spendable byte after each locking script. + @Test func spendableListOutputsExtension() throws { + let request = WalletWireActionRequest.listOutputs(try WalletListOutputsRequest(basket: "default")) + let legacy = try WalletWireCodec.encodeActionRequest( + request, originator: "", beefLimits: actionBEEFLimits() + ) + let spendable = try WalletWireCodec.encodeActionRequest( + request, originator: "", listOutputsEncoding: .spendable, beefLimits: actionBEEFLimits() + ) + #expect(spendable == legacy + [0x01]) + #expect(try WalletWireCodec.decodeActionRequest(spendable, beefLimits: actionBEEFLimits()) + .listOutputsEncoding == .spendable) + #expect(try WalletWireCodec.decodeActionRequest(legacy, beefLimits: actionBEEFLimits()) + .listOutputsEncoding == .legacy) + + let output = try WalletOutput( + satoshis: 1, lockingScript: [0x51], spendable: false, + outpoint: Outpoint(transactionID: try actionTransactionID(), outputIndex: 0) + ) + let result = WalletWireActionResult.listOutputs( + try WalletListOutputsResult(totalOutputs: 1, outputs: [output]) + ) + #expect(throws: WalletWireResultRejection( + message: "Non-spendable listOutputs records require the spendable encoding extension or JSON" + )) { + try WalletWireCodec.encodeActionResult(result, request: request, beefLimits: actionBEEFLimits()) + } + let encoded = try WalletWireCodec.encodeActionResult( + result, request: request, listOutputsEncoding: .spendable, beefLimits: actionBEEFLimits() + ) + let header: [UInt8] = [0x00] + absent + [0x01] + absent + #expect(Array(encoded.prefix(header.count)) == header) + guard case .listOutputs(let decoded) = try WalletWireCodec.decodeActionResult( + encoded, expectedCall: .listOutputs, request: request, + listOutputsEncoding: .spendable, beefLimits: actionBEEFLimits() + ) else { + Issue.record("expected listOutputs") + return + } + #expect(decoded.outputs.first?.spendable == false) + } + + // MARK: W13 JSON error code + + /// substrates/HTTPWalletJSON.ts:271-279 requires a safe-integer `code`. + @Test func redactedJSONErrorsCarryCodeOne() throws { + let payload = WalletJSONRedactingFailureMapper().payload(for: VectorFailure(), call: .getHeight) + #expect(payload.code == 1) + let codec = try WalletBRC100JSONCodec(beefLimits: actionBEEFLimits()) + let body = String(decoding: try codec.encodeError(payload), as: UTF8.self) + #expect(body.contains("\"code\":1")) + } + + // MARK: empty keyring in JSON + + /// substrates/WalletWireTransceiver.ts:1622 returns `keyring: {}` when no + /// keyring is present, and WalletWireProcessor.ts:2118 writes `{}` as no + /// keyring, so a TypeScript JSON result with `{}` decodes as no keyring. + @Test func emptyJSONKeyringReadsAsAbsent() throws { + let fixture = try WalletWireCertificateFixture() + let codec = try WalletBRC100JSONCodec(beefLimits: actionBEEFLimits()) + let route = try #require(WalletJSONRoute(methodName: "listCertificates")) + let withoutKeyring = WalletResult.certificate(.listCertificates(try .init( + totalCertificates: 1, + certificates: [WalletCertificateResult(certificate: fixture.certificate, keyring: nil, verifier: [])] + ))) + let json = String(decoding: try codec.encodeResult(withoutKeyring), as: UTF8.self) + #expect(!json.contains("keyring")) + let typeScriptJSON = json.replacingOccurrences( + of: "\"certifier\":", with: "\"keyring\":{},\"certifier\":" + ) + #expect(typeScriptJSON.contains("\"keyring\":{}")) + let decoded = try codec.decodeResult(route: route, from: Array(typeScriptJSON.utf8)) + guard case .certificate(.listCertificates(let page)) = decoded else { + Issue.record("expected listCertificates") + return + } + #expect(page.certificates.first?.keyring == nil) + } + + // MARK: helpers + + private func errorFrame(code: UInt8, _ message: String) -> [UInt8] { + [code, UInt8(message.utf8.count)] + Array(message.utf8) + [0x00] + } + + private func vectorProcessor(result: WalletResult) throws -> WalletWireProcessor { + WalletWireProcessor( + handler: VectorHandler(result: result), + failureMapper: try WalletWireRedactingFailureMapper(limits: .standard), + beefLimits: try actionBEEFLimits(), + certificateLimits: .standard, + wireLimits: .standard + ) + } +} + +private struct VectorFailure: Error {} + +private struct VectorHandler: WalletRequestHandling { + let result: WalletResult + func handle(_ request: WalletRequest, context: WalletRequestContext) async throws -> WalletResult { + result + } +} From 9d02657debb6b4621d9138160e508f07ee8952b4 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:52:09 +0000 Subject: [PATCH 3/8] Add a TypeScript wallet-wire oracle Tools/Conformance/TSOracle/generate.sh runs the real @bsv/sdk transceiver against its own processor with Bun and records every frame. The opt-in WalletWireTypeScriptOracleTests replays those frames against the Swift processor and transceiver. --- .../WalletWireTypeScriptOracleTests.swift | 233 +++++++++++ Tools/Conformance/README.md | 22 + Tools/Conformance/TSOracle/gen.ts | 392 ++++++++++++++++++ Tools/Conformance/TSOracle/generate.sh | 31 ++ 4 files changed, 678 insertions(+) create mode 100644 Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift create mode 100644 Tools/Conformance/TSOracle/gen.ts create mode 100755 Tools/Conformance/TSOracle/generate.sh diff --git a/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift b/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift new file mode 100644 index 0000000..7eb0bea --- /dev/null +++ b/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift @@ -0,0 +1,233 @@ +import Foundation +import BSVCore +import BSVTransaction +import BSVWallet +import Testing + +/// Differential vectors produced by the live TypeScript `@bsv/sdk` 4.1.1 +/// `WalletWireTransceiver` talking to its own `WalletWireProcessor`. +/// +/// Generate the vectors with `Tools/Conformance/TSOracle/generate.sh` and point +/// `BSV_TS_WALLET_WIRE_VECTORS` at the output. Without that variable the suite +/// records a skip. Generated answers are not committed (see +/// `Documentation/Compatibility/FixtureSources.md`). +@Suite("Wallet wire against the TypeScript SDK oracle") +struct WalletWireTypeScriptOracleTests { + @Test("the Swift processor answers every TypeScript request with the TypeScript bytes") + func processorMatchesTypeScript() async throws { + guard let vectors = try TSWalletWireVectors.load() else { return } + for vector in vectors.cases where vector.transceiverOnly != true { + try await checkProcessor(vector) + } + } + + @Test("the Swift transceiver sends the TypeScript request bytes and reads the TypeScript answers") + func transceiverMatchesTypeScript() async throws { + guard let vectors = try TSWalletWireVectors.load() else { return } + for vector in vectors.cases where vector.raw != true && vector.processorOnly != true { + try await checkTransceiver(vector) + } + } + + private func checkProcessor(_ vector: TSWalletWireVector) async throws { + let codec = try tsOracleCodec() + let handler = TSOracleStubHandler(vector: vector, codec: codec) + let limits = WalletWireLimits.standard + let processor = WalletWireProcessor( + handler: handler, + failureMapper: try WalletWireRedactingFailureMapper( + code: 1, + message: "Wallet operation failed", + limits: limits + ), + beefLimits: try tsOracleBEEFLimits(), + certificateLimits: .standard, + wireLimits: limits + ) + for frame in vector.frames { + let request = try Hex.decode(frame.request, maximumDecodedByteCount: 1 << 24) + let expected = try Hex.decode(frame.response, maximumDecodedByteCount: 1 << 24) + let actual: [UInt8] + do { + actual = try await processor.transmit( + request, + maximumResponseByteCount: limits.maximumFrameByteCount + ) + } catch { + Issue.record("\(vector.name): processor threw \(error)") + continue + } + if vector.isLegacyCertificateTypeDivergence, !frame.request.hasPrefix("1d") { + // A legacy (non-32-byte) certificate type has no Swift ABI value. The + // Swift processor still answers in-band with an error frame. + #expect(actual.first != 0, "\(vector.name): legacy type answered in-band") + continue + } + #expect(Hex.encode(actual) == frame.response, "\(vector.name): processor response") + _ = expected + } + } + + private func checkTransceiver(_ vector: TSWalletWireVector) async throws { + guard let method = vector.method, let args = vector.args, + let route = WalletJSONRoute(methodName: method) else { + Issue.record("\(vector.name): malformed vector") + return + } + let codec = try tsOracleCodec() + let request: WalletRequest + do { request = try codec.decodeRequest(route: route, from: Array(args.utf8)) } + catch { + if vector.isLegacyCertificateTypeDivergence { return } + Issue.record("\(vector.name): Swift JSON rejected TypeScript arguments: \(error)") + return + } + let transport = TSOracleReplayTransport(name: vector.name, frames: vector.frames) + let client = try WalletWireTransceiver( + transport: transport, + originator: vector.originator ?? "example.com", + beefLimits: try tsOracleBEEFLimits(), + certificateLimits: .standard, + wireLimits: .standard, + listOutputsEncoding: vector.spendable == true ? .spendable : .legacy + ) + let adapter = WalletInterfaceRequestHandler(wallet: client) + let context = try WalletRequestContext(rawOriginator: vector.originator ?? "example.com") + do { + let result = try await adapter.handle(request, context: context) + guard let ok = vector.outcome?.ok else { + Issue.record("\(vector.name): expected a remote failure, got a result") + return + } + let expected = try codec.decodeResult(route: route, from: Array(ok.utf8)) + #expect( + try String(decoding: codec.encodeResult(result), as: UTF8.self) + == String(decoding: codec.encodeResult(expected), as: UTF8.self), + "\(vector.name): decoded result" + ) + } catch let remote as WalletWireRemoteError { + guard let error = vector.outcome?.error else { + Issue.record("\(vector.name): unexpected remote failure \(remote.code) \(remote.message)") + return + } + #expect(Int(remote.code) == error.code, "\(vector.name): remote code") + #expect(remote.message == error.message, "\(vector.name): remote message") + } catch { + Issue.record("\(vector.name): transceiver threw \(error)") + } + #expect(await transport.remaining() == 0, "\(vector.name): unsent TypeScript frames") + } +} + +struct TSWalletWireVectors: Decodable { + let source: String + let cases: [TSWalletWireVector] + + static func load() throws -> TSWalletWireVectors? { + guard let path = ProcessInfo.processInfo.environment["BSV_TS_WALLET_WIRE_VECTORS"], + !path.isEmpty else { + print("TypeScript wallet-wire oracle vectors unavailable: BSV_TS_WALLET_WIRE_VECTORS is not set") + return nil + } + let data = try Data(contentsOf: URL(fileURLWithPath: path)) + return try JSONDecoder().decode(TSWalletWireVectors.self, from: data) + } +} + +struct TSWalletWireVector: Decodable, Sendable { + struct Frame: Decodable, Sendable { + let request: String + let response: String + } + struct Outcome: Decodable, Sendable { + let ok: String? + let error: Failure? + } + struct Failure: Decodable, Sendable { + let code: Int? + let message: String + } + + let name: String + let method: String? + let originator: String? + let raw: Bool? + let spendable: Bool? + /// The TS request keeps a form the Swift ABI does not (an omitted + /// counterparty, an explicit `false`, insertion-ordered maps). + let processorOnly: Bool? + /// The Swift processor writes maps sorted; TS writes insertion order. + let transceiverOnly: Bool? + let divergence: String? + let args: String? + let walletResult: String? + let outcome: Outcome? + let frames: [Frame] + + var isLegacyCertificateTypeDivergence: Bool { divergence == "legacy-certificate-type" } +} + +private struct TSOracleStubHandler: WalletRequestHandling { + let vector: TSWalletWireVector + let codec: WalletBRC100JSONCodec + + func handle(_ request: WalletRequest, context: WalletRequestContext) async throws -> WalletResult { + let route = WalletJSONRoute(call: request.call) + if let walletResult = vector.walletResult { + return try codec.decodeResult(route: route, from: Array(walletResult.utf8)) + } + if let ok = vector.outcome?.ok { + return try codec.decodeResult(route: route, from: Array(ok.utf8)) + } + throw TSOracleWalletFailure() + } +} + +private struct TSOracleWalletFailure: Error {} + +private actor TSOracleReplayTransport: WalletWireTransport { + let name: String + var frames: [TSWalletWireVector.Frame] + + init(name: String, frames: [TSWalletWireVector.Frame]) { + self.name = name + // The Swift transceiver does not probe call 29 (the certificate + // compatibility profile), so the TS probe frames are not replayed. + self.frames = frames.filter { !$0.request.hasPrefix("1d") } + } + + func remaining() -> Int { frames.count } + + func transmit(_ request: [UInt8], maximumResponseByteCount: Int) async throws -> [UInt8] { + guard !frames.isEmpty else { + Issue.record("\(name): Swift sent an extra frame \(Hex.encode(request))") + throw WalletWireSubstrateError.transportFailure + } + let frame = frames.removeFirst() + #expect(Hex.encode(request) == frame.request, "\(name): request frame") + return try Hex.decode(frame.response, maximumDecodedByteCount: 1 << 24) + } +} + +private func tsOracleCodec() throws -> WalletBRC100JSONCodec { + try WalletBRC100JSONCodec(beefLimits: tsOracleBEEFLimits()) +} + +private func tsOracleBEEFLimits() throws -> BEEFLimits { + try BEEFLimits( + maximumByteCount: 1_000_000, + maximumMerklePathCount: 100, + maximumTransactionCount: 1_000, + transactionLimits: try TransactionLimits( + maximumTransactionByteCount: 100_000, + maximumInputCount: 100, + maximumOutputCount: 100, + maximumScriptByteCount: 10_000 + ), + merklePathLimits: try MerklePathLimits( + maximumByteCount: 100_000, + maximumLeavesPerLevel: 100, + maximumTotalLeaves: 1_000 + ) + ) +} diff --git a/Tools/Conformance/README.md b/Tools/Conformance/README.md index ad75a9d..bc30dad 100644 --- a/Tools/Conformance/README.md +++ b/Tools/Conformance/README.md @@ -284,3 +284,25 @@ Typed errors take precedence. The one pinned message fallback is isolated and unit tested; diagnostic messages are not a compatibility surface. An operation panic is recovered as `oraclePanic`. Startup, pin, or stream corruption exits nonzero; ordinary operation errors return a response and keep `serve` alive. + +## TypeScript wallet-wire oracle + +`TSOracle` drives the real `@bsv/sdk` `WalletWireTransceiver` against its own +`WalletWireProcessor` and records every frame, request argument and result as +JSON. Like the Go oracle it only reads an external checkout and stores no +TypeScript source or generated answers here. It needs Bun. + +```sh +BSV_TS_SDK_PATH=$HOME/code/ts-stack/packages/sdk Tools/Conformance/TSOracle/generate.sh +BSV_TS_WALLET_WIRE_VECTORS=$PWD/.build/ts-oracle/ts-wallet-wire-vectors.json \ + swift test --filter WalletWireTypeScriptOracleTests +``` + +The default output is `.build/ts-oracle/ts-wallet-wire-vectors.json`. +`WalletWireTypeScriptOracleTests` checks that the Swift processor answers each +TypeScript request with the TypeScript bytes and that the Swift transceiver +sends the TypeScript request bytes and reads the TypeScript answers. Without +`BSV_TS_WALLET_WIRE_VECTORS` the suite prints a skip. Vectors marked +`processorOnly`, `transceiverOnly` or with a `divergence` record forms the +Swift ABI does not keep (an omitted counterparty, insertion-ordered maps, +certificate types other than 32 bytes); see COMP-045 and COMP-048. diff --git a/Tools/Conformance/TSOracle/gen.ts b/Tools/Conformance/TSOracle/gen.ts new file mode 100644 index 0000000..6aaabc2 --- /dev/null +++ b/Tools/Conformance/TSOracle/gen.ts @@ -0,0 +1,392 @@ +// Generates wallet-wire interop vectors from the TypeScript @bsv/sdk source. +// Each case drives the real TS WalletWireTransceiver against the real TS +// WalletWireProcessor and records every request/response frame. +// Run through generate.sh; it sets the variables read here. +const SDK = process.env.BSV_TS_SDK_PATH +const OUTPUT = process.env.BSV_TS_ORACLE_OUTPUT +const SOURCE = process.env.BSV_TS_ORACLE_SOURCE +if (!SDK || !OUTPUT || !SOURCE) { + throw new Error('BSV_TS_SDK_PATH, BSV_TS_ORACLE_OUTPUT and BSV_TS_ORACLE_SOURCE must be set (use generate.sh)') +} +const SRC = `${SDK}/src` +const { default: ProtoWallet } = await import(`${SRC}/wallet/ProtoWallet.ts`) +const { default: PrivateKey } = await import(`${SRC}/primitives/PrivateKey.ts`) +const { default: WalletWireProcessor } = await import(`${SRC}/wallet/substrates/WalletWireProcessor.ts`) +const { default: WalletWireTransceiver } = await import(`${SRC}/wallet/substrates/WalletWireTransceiver.ts`) +const { default: Transaction } = await import(`${SRC}/transaction/Transaction.ts`) +const { default: MerklePath } = await import(`${SRC}/transaction/MerklePath.ts`) +const { default: Certificate } = await import(`${SRC}/auth/certificates/Certificate.ts`) +const { stringifyBRC100 } = await import(`${SRC}/wallet/BRC100ByteEncoding.ts`) +const { default: P2PKH } = await import(`${SRC}/script/templates/P2PKH.ts`) +const { default: LockingScript } = await import(`${SRC}/script/LockingScript.ts`) +const { default: UnlockingScript } = await import(`${SRC}/script/UnlockingScript.ts`) + +const hex = (b: ArrayLike) => Buffer.from(Array.from(b)).toString('hex') +const rootKey = PrivateKey.fromHex('f0efba88c117ca2614554bb676d743f413822a31e3c8d70cfcc5fff119d20a07') +const proto = new ProtoWallet(rootKey) +const certifierKey = PrivateKey.fromHex('1111111111111111111111111111111111111111111111111111111111111111') +const certifierProto = new ProtoWallet(certifierKey) +const identityKey = (await proto.getPublicKey({ identityKey: true })).publicKey +const certifierPub = (await certifierProto.getPublicKey({ identityKey: true })).publicKey +const counterpartyKey = '03458d551018414b8fe1adbcef2d0afc17e1074bfab3fdde3e1b0750bdde58a9a7' + +// A one-transaction block makes a valid BUMP for the parent. +const lockingScript = new P2PKH().lock(rootKey.toPublicKey().toAddress()) +const parent = new Transaction(1, [], [{ lockingScript, satoshis: 5000 }], 0) +parent.inputs = [{ + sourceTXID: '00'.repeat(32), sourceOutputIndex: 0, + unlockingScript: UnlockingScript.fromHex('51'), sequence: 0xffffffff +}] +parent.merklePath = new MerklePath(800000, [[{ offset: 0, hash: parent.id('hex'), txid: true }]]) +const child = new Transaction(1, [{ + sourceTransaction: parent, sourceOutputIndex: 0, + unlockingScript: UnlockingScript.fromHex('51'), sequence: 0xffffffff +}], [{ lockingScript, satoshis: 4000 }], 0) +const childTxid = child.id('hex') +const childAtomic = child.toAtomicBEEF() +const childBEEF = child.toBEEF() + +// Signable: the request input has no unlocking script. +const signable = new Transaction(1, [{ + sourceTransaction: parent, sourceOutputIndex: 0, + unlockingScript: new UnlockingScript([]), sequence: 0xffffffff +}], [{ lockingScript, satoshis: 4000 }], 0) +const signableAtomic = signable.toAtomicBEEF(true) + +const typeA = Buffer.alloc(32, 7).toString('base64') +const serialA = Buffer.alloc(32, 9).toString('base64') +const revocation = `${'ab'.repeat(32)}.0` +async function makeCertificate(type: string, fields: Record) { + const c = new Certificate(type, serialA, identityKey, certifierPub, revocation, fields) + await c.sign(certifierProto) + return c +} +const certA = await makeCertificate(typeA, { email: 'ZW1haWw=', name: 'bmFtZQ==' }) +const certLegacy: any = await makeCertificate(typeA, { name: 'bmFtZQ==' }) +certLegacy.type = 'YWJj' +const certJSON = (c: any) => ({ + type: c.type, serialNumber: c.serialNumber, subject: c.subject, certifier: c.certifier, + revocationOutpoint: c.revocationOutpoint, fields: { ...c.fields }, signature: c.signature +}) + +let walletResults: Record = {} +function stub(method: string) { + return async (args: any) => { + const r = walletResults[method] + if (r === undefined) throw new Error(`no stub for ${method}`) + if (r instanceof Error) throw r + return typeof r === 'function' ? await r(args) : r + } +} +const wallet: any = new Proxy(proto, { + get(target: any, prop: string) { + if (typeof prop === 'string' && walletResults[prop] !== undefined) return stub(prop) + const v = target[prop] + return typeof v === 'function' ? v.bind(target) : v + } +}) + +const processor = new WalletWireProcessor(wallet) +let frames: Array<{ request: string, response: string }> = [] +// The Swift processor answers call 29 (the certificate compatibility profile) +// as a processor without the profile does: code 1, "Invalid call code: 29". +// The TypeScript transceiver downgrades on exactly that frame. This wire gives +// the same answer so every recorded frame is one the Swift processor must match. +const downgrade = [1, ...Array.from(Buffer.from([21])), ...Array.from(Buffer.from('Invalid call code: 29', 'utf8')), 0] +const wire = { + async transmitToWallet(message: number[]) { + const response = message[0] === 29 ? downgrade : await processor.transmitToWallet(message) + frames.push({ request: hex(message), response: hex(response) }) + return response + } +} + +type Case = { + name: string, method: string, args: any, result?: any, error?: any, + originator?: string, spendable?: boolean, rawRequest?: string, + // processorOnly: the TS request carries a form the Swift ABI does not keep + // (an omitted counterparty, an explicit false, insertion-ordered maps). + // transceiverOnly: the Swift processor writes maps sorted, TS in insertion order. + processorOnly?: boolean, transceiverOnly?: boolean, divergence?: string +} +const out: any[] = [] +async function run(c: Case) { + walletResults = {} + if ('result' in c) walletResults[c.method] = c.result + frames = [] + const transceiver = new WalletWireTransceiver(wire, c.spendable === true ? { listOutputsEncoding: 'spendable' } : {}) + const originator = c.originator ?? 'example.com' + let outcome: any + try { + const r = await (transceiver as any)[c.method](c.args, originator) + outcome = { ok: stringifyBRC100(r) } + } catch (e: any) { + outcome = { error: { code: e.code ?? null, message: String(e.message) } } + } + out.push({ + name: c.name, method: c.method, originator, + args: stringifyBRC100(c.args), + walletResult: 'result' in c && !(c.result instanceof Error) && typeof c.result !== 'function' + ? stringifyBRC100(c.result) : null, + spendable: c.spendable === true, + processorOnly: c.processorOnly === true, + transceiverOnly: c.transceiverOnly === true, + divergence: c.divergence ?? null, + outcome, frames + }) +} +async function raw(name: string, requestHex: string) { + frames = [] + const response = await processor.transmitToWallet(Array.from(Buffer.from(requestHex, 'hex'))) + out.push({ name, method: null, raw: true, frames: [{ request: requestHex, response: hex(response) }] }) +} + +const txA = 'a1'.repeat(32) +const txB = 'b2'.repeat(32) +const ls = lockingScript.toHex() + +// ---- actions +await run({ + name: 'createAction-txid-only', method: 'createAction', + args: { + description: 'Test action', labels: ['label one'], + outputs: [{ lockingScript: ls, satoshis: 1000, outputDescription: 'Pay out', basket: 'default', tags: ['t1', 't2'], customInstructions: 'ci' }], + lockTime: 0, version: 1, + options: { returnTXIDOnly: true, noSend: true, knownTxids: [txA], randomizeOutputs: false, acceptDelayedBroadcast: false, signAndProcess: true, trustSelf: 'known' } + }, + result: { txid: txA, noSendChange: [`${txA}.1`], sendWithResults: [{ txid: txA, status: 'sending' }] } +}) +await run({ + name: 'createAction-sendWith-only', method: 'createAction', + args: { description: 'Send batch', options: { sendWith: [txB] } }, + result: { sendWithResults: [{ txid: txB, status: 'unproven' }] } +}) +await run({ + name: 'createAction-signable', method: 'createAction', + args: { + description: 'Signable action', inputBEEF: Array.from(parent.toBEEF()), + inputs: [{ outpoint: `${parent.id('hex')}.0`, inputDescription: 'Spend parent', unlockingScriptLength: 107, sequenceNumber: 0xffffffff }], + outputs: [{ lockingScript: ls, satoshis: 4000, outputDescription: 'Change out' }] + }, + result: { signableTransaction: { tx: Array.from(signableAtomic), reference: 'cmVmZXJlbmNl' } } +}) +await run({ + name: 'createAction-with-tx', method: 'createAction', + args: { + description: 'Complete action', inputBEEF: Array.from(parent.toBEEF()), + inputs: [{ outpoint: `${parent.id('hex')}.0`, inputDescription: 'Spend parent', unlockingScript: '51', sequenceNumber: 0xffffffff }], + outputs: [{ lockingScript: ls, satoshis: 4000, outputDescription: 'Change out' }] + }, + result: { txid: childTxid, tx: Array.from(childAtomic) } +}) +await run({ + name: 'signAction-txid', method: 'signAction', + args: { spends: { 0: { unlockingScript: '51', sequenceNumber: 0xffffffff } }, reference: 'cmVmZXJlbmNl', options: { returnTXIDOnly: true, sendWith: [txB], noSend: false, acceptDelayedBroadcast: true } }, + result: { txid: txA, sendWithResults: [{ txid: txB, status: 'failed' }] } +}) +await run({ + name: 'signAction-with-tx', method: 'signAction', + args: { spends: { 0: { unlockingScript: '51' } }, reference: 'cmVmZXJlbmNl' }, + result: { txid: childTxid, tx: Array.from(childAtomic) } +}) +await run({ name: 'abortAction-true', method: 'abortAction', args: { reference: 'cmVmZXJlbmNl' }, result: { aborted: true } }) +await run({ name: 'abortAction-refused', method: 'abortAction', args: { reference: 'cmVmZXJlbmNl' }, result: { aborted: false } }) +const action = { + txid: txA, satoshis: -222, status: 'completed', isOutgoing: true, description: 'History item', + labels: ['label one'], version: 1, lockTime: 0, + inputs: [{ sourceOutpoint: `${txB}.0`, sourceSatoshis: 5000, sourceLockingScript: ls, unlockingScript: '51', inputDescription: 'Spent coin', sequenceNumber: 0xffffffff }], + outputs: [{ outputIndex: 0, satoshis: 4778, lockingScript: ls, spendable: true, outputDescription: 'Change', basket: 'default', tags: ['t1'], customInstructions: 'ci' }] +} +await run({ + name: 'listActions-paged', method: 'listActions', + args: { labels: ['label one'], labelQueryMode: 'all', includeLabels: true, includeInputs: true, includeInputSourceLockingScripts: true, includeInputUnlockingScripts: true, includeOutputs: true, includeOutputLockingScripts: true, limit: 10, offset: 5, seekPermission: false }, + result: { totalActions: 250, actions: [action] } +}) +await run({ + name: 'listActions-empty-page', method: 'listActions', + args: { labels: ['label one'] }, + result: { totalActions: 250, actions: [] } +}) +await run({ + name: 'listActions-no-scripts', method: 'listActions', + args: { labels: ['label one'], includeInputs: true, includeOutputs: true }, + result: { + totalActions: 1, actions: [{ + txid: txA, satoshis: 10, status: 'unproven', isOutgoing: false, description: '', version: 1, lockTime: 0, + inputs: [{ sourceOutpoint: `${txB}.3`, sourceSatoshis: 5000, inputDescription: '', sequenceNumber: 0 }], + outputs: [{ outputIndex: 1, satoshis: 10, spendable: false, outputDescription: '', basket: '', tags: [] }] + }] + } +}) +await run({ + name: 'internalizeAction', method: 'internalizeAction', + args: { + tx: Array.from(childAtomic), description: 'Receive payment', labels: ['incoming'], seekPermission: true, + outputs: [ + { outputIndex: 0, protocol: 'wallet payment', paymentRemittance: { senderIdentityKey: counterpartyKey, derivationPrefix: 'cHJlZml4', derivationSuffix: 'c3VmZml4' } } + ] + }, + result: { accepted: true } +}) +await run({ + name: 'internalizeAction-basket', method: 'internalizeAction', + args: { + tx: Array.from(childAtomic), description: 'Receive token', + outputs: [{ outputIndex: 0, protocol: 'basket insertion', insertionRemittance: { basket: 'tokens', customInstructions: 'ci', tags: ['x'] } }] + }, + result: { accepted: true } +}) +const output = { outpoint: `${txA}.1`, satoshis: 1000, lockingScript: ls, spendable: true, customInstructions: 'ci', tags: ['t1'], labels: ['label one'] } +await run({ + name: 'listOutputs-paged', method: 'listOutputs', + args: { basket: 'default', tags: ['t1'], tagQueryMode: 'any', include: 'locking scripts', includeCustomInstructions: true, includeTags: true, includeLabels: true, limit: 10, offset: 0, seekPermission: true }, + result: { totalOutputs: 3, outputs: [output] } +}) +await run({ + name: 'listOutputs-empty-page', method: 'listOutputs', + args: { basket: 'default' }, + result: { totalOutputs: 3, outputs: [] } +}) +await run({ + name: 'listOutputs-balance', method: 'listOutputs', + args: { basket: 'balance default' }, + result: { totalOutputs: 5000000000, outputs: [] } +}) +await run({ + name: 'listOutputs-module-balance', method: 'listOutputs', + args: { basket: 'p btms balance tokens' }, + result: { totalOutputs: 7, outputs: [] } +}) +await run({ + name: 'listOutputs-beef', method: 'listOutputs', + args: { basket: 'default', include: 'entire transactions' }, + result: { totalOutputs: 1, BEEF: Array.from(childBEEF), outputs: [{ outpoint: `${childTxid}.0`, satoshis: 4000, spendable: true }] } +}) +await run({ + name: 'listOutputs-spendable-extension', method: 'listOutputs', spendable: true, + args: { basket: 'default' }, + result: { totalOutputs: 2, outputs: [{ outpoint: `${txA}.1`, satoshis: 1000, spendable: false }] } +}) +await run({ + name: 'listOutputs-unspendable-legacy', method: 'listOutputs', + args: { basket: 'default' }, + result: { totalOutputs: 2, outputs: [{ outpoint: `${txA}.1`, satoshis: 1000, spendable: false }] } +}) +await run({ name: 'relinquishOutput', method: 'relinquishOutput', args: { basket: 'default', output: `${txA}.1` }, result: { relinquished: true } }) + +// ---- key queries through the real ProtoWallet +await run({ name: 'getPublicKey-identity', method: 'getPublicKey', args: { identityKey: true } }) +await run({ name: 'getPublicKey-derived', method: 'getPublicKey', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: counterpartyKey, forSelf: true, seekPermission: true } }) +await run({ name: 'getPublicKey-explicit-false', method: 'getPublicKey', processorOnly: true, args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: counterpartyKey, forSelf: false, privileged: false } }) +await run({ name: 'getPublicKey-anyone', method: 'getPublicKey', args: { protocolID: [0, 'wire tests'], keyID: 'k', counterparty: 'anyone' } }) +await run({ name: 'encrypt', method: 'encrypt', args: { protocolID: [1, 'wire tests'], keyID: '1', counterparty: 'self', plaintext: [1, 2, 3], privilegedReason: 'needed for test' } }) +await run({ name: 'createHmac', method: 'createHmac', args: { protocolID: [2, 'hmac key vectors'], keyID: 'k95', counterparty: 'self', data: Array.from(Buffer.from('4252432d353620484d41432074657374', 'hex')) } }) +await run({ name: 'createHmac-counterparty', method: 'createHmac', args: { protocolID: [2, 'hmac key vectors'], keyID: 'k497', counterparty: counterpartyKey, data: Array.from(Buffer.from('4252432d353620484d41432074657374', 'hex')) } }) +await run({ name: 'verifyHmac-valid', method: 'verifyHmac', args: { protocolID: [2, 'hmac key vectors'], keyID: 'k95', counterparty: 'self', data: Array.from(Buffer.from('4252432d353620484d41432074657374', 'hex')), hmac: Array.from(Buffer.from('3a968ebaa25eaa4b1cfad138f96105bb1eb738defc066d01e37b32595900d48b', 'hex')) } }) +await run({ name: 'verifyHmac-invalid', method: 'verifyHmac', args: { protocolID: [2, 'hmac key vectors'], keyID: 'k95', counterparty: 'self', data: Array.from(Buffer.from('4252432d353620484d41432074657374', 'hex')), hmac: Array.from(Buffer.from('054a0fc6a3b0e21b31dc627fb1d645f2eea4127dff71eac95b1f71b7cb13c787', 'hex')) } }) +await run({ name: 'verifyHmac-wallet-false', method: 'verifyHmac', args: { protocolID: [2, 'hmac key vectors'], keyID: 'k95', counterparty: 'self', data: [1], hmac: Array(32).fill(0) }, result: { valid: false } }) +await run({ name: 'verifySignature-wallet-false', method: 'verifySignature', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: 'self', data: [1, 2, 3], signature: [48, 6, 2, 1, 1, 2, 1, 1] }, result: { valid: false } }) +await run({ name: 'createSignature-direct-hash', method: 'createSignature', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: 'anyone', hashToDirectlySign: Array(32).fill(5) } }) +await run({ name: 'createSignature', method: 'createSignature', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: 'anyone', data: [1, 2, 3] } }) +await run({ name: 'createSignature-default-counterparty', method: 'createSignature', processorOnly: true, args: { protocolID: [2, 'wire tests'], keyID: '1', data: [1, 2, 3] } }) +const sig = (await proto.createSignature({ protocolID: [2, 'wire tests'], keyID: '1', data: [1, 2, 3], counterparty: 'self' })).signature +await run({ name: 'verifySignature-valid', method: 'verifySignature', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: 'self', data: [1, 2, 3], signature: sig, forSelf: true } }) +await run({ name: 'verifySignature-default-counterparty', method: 'verifySignature', processorOnly: true, args: { protocolID: [2, 'wire tests'], keyID: '1', data: [1, 2, 3], signature: sig, forSelf: true } }) +await run({ name: 'verifySignature-invalid', method: 'verifySignature', args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: 'self', data: [1, 2, 4], signature: sig, forSelf: true } }) +await run({ name: 'isAuthenticated', method: 'isAuthenticated', args: {}, result: { authenticated: true } }) +await run({ name: 'waitForAuthentication', method: 'waitForAuthentication', args: {}, result: { authenticated: true } }) +await run({ name: 'getHeight', method: 'getHeight', args: {}, result: { height: 800000 } }) +await run({ name: 'getHeaderForHeight', method: 'getHeaderForHeight', args: { height: 800000 }, result: { header: '01'.repeat(80) } }) +await run({ name: 'getNetwork', method: 'getNetwork', args: {}, result: { network: 'testnet' } }) +await run({ name: 'getVersion', method: 'getVersion', args: {}, result: { version: 'swift-1.0.0' } }) +await run({ name: 'revealSpecificKeyLinkage-self', method: 'revealSpecificKeyLinkage', args: { counterparty: 'self', verifier: counterpartyKey, protocolID: [2, 'wire tests'], keyID: '1' } }) +await run({ name: 'revealSpecificKeyLinkage-anyone', method: 'revealSpecificKeyLinkage', args: { counterparty: 'anyone', verifier: counterpartyKey, protocolID: [2, 'wire tests'], keyID: '1' } }) +await run({ name: 'revealCounterpartyKeyLinkage', method: 'revealCounterpartyKeyLinkage', args: { counterparty: counterpartyKey, verifier: certifierPub, privileged: true, privilegedReason: 'audit test' } }) + +// ---- certificates +await run({ + name: 'acquireCertificate-direct', method: 'acquireCertificate', + args: { ...certJSON(certA), acquisitionProtocol: 'direct', keyringRevealer: 'certifier', keyringForSubject: { email: 'a2V5MQ==', name: 'a2V5Mg==' } }, + result: certJSON(certA) +}) +await run({ + name: 'listCertificates', method: 'listCertificates', + args: { certifiers: [certifierPub], types: [typeA], limit: 10, offset: 0 }, + result: { totalCertificates: 7, certificates: [{ ...certJSON(certA), keyring: { email: 'a2V5MQ==' }, verifier: counterpartyKey }] } +}) +await run({ + name: 'listCertificates-unsorted-keyring', method: 'listCertificates', transceiverOnly: true, + args: { certifiers: [certifierPub], types: [typeA] }, + result: { totalCertificates: 1, certificates: [{ ...certJSON(certA), keyring: { name: 'a2V5Mg==', email: 'a2V5MQ==' } }] } +}) +await run({ + name: 'acquireCertificate-unsorted-keyring', method: 'acquireCertificate', processorOnly: true, + args: { ...certJSON(certA), acquisitionProtocol: 'direct', keyringRevealer: counterpartyKey, keyringForSubject: { name: 'a2V5Mg==', email: 'a2V5MQ==' }, privileged: false }, + result: certJSON(certA) +}) +await run({ + name: 'acquireCertificate-issuance', method: 'acquireCertificate', + args: { type: typeA, certifier: certifierPub, acquisitionProtocol: 'issuance', certifierUrl: 'https://certifier.example.com', fields: { email: 'a@example.com', name: 'Alice' } }, + result: certJSON(certA) +}) +await run({ + name: 'acquireCertificate-issuance-unsorted', method: 'acquireCertificate', processorOnly: true, + args: { type: typeA, certifier: certifierPub, acquisitionProtocol: 'issuance', certifierUrl: 'https://certifier.example.com', fields: { name: 'Alice', email: 'a@example.com' } }, + result: certJSON(certA) +}) +await run({ + name: 'listCertificates-empty-types', method: 'listCertificates', + args: { certifiers: [certifierPub], types: [] }, + result: { totalCertificates: 7, certificates: [] } +}) +await run({ + name: 'listCertificates-legacy-type', divergence: 'legacy-certificate-type', method: 'listCertificates', + args: { certifiers: [certifierPub], types: ['YWJj'] }, + result: { totalCertificates: 1, certificates: [certJSON(certLegacy)] } +}) +await run({ + name: 'proveCertificate', method: 'proveCertificate', + args: { certificate: certJSON(certA), fieldsToReveal: ['email'], verifier: counterpartyKey }, + result: { keyringForVerifier: { email: 'a2V5MQ==' } } +}) +await run({ + name: 'proveCertificate-legacy', divergence: 'legacy-certificate-type', method: 'proveCertificate', + args: { certificate: certJSON(certLegacy), fieldsToReveal: ['name'], verifier: counterpartyKey }, + result: { keyringForVerifier: { name: 'a2V5MQ==' } } +}) +await run({ + name: 'relinquishCertificate', method: 'relinquishCertificate', + args: { type: typeA, serialNumber: serialA, certifier: certifierPub }, result: { relinquished: true } +}) +await run({ + name: 'relinquishCertificate-legacy', divergence: 'legacy-certificate-type', method: 'relinquishCertificate', + args: { type: 'YWJj', serialNumber: serialA, certifier: certifierPub }, result: { relinquished: true } +}) +const discovered = { ...certJSON(certA), certifierInfo: { name: 'Certifier', iconUrl: 'https://example.com/i.png', description: 'Trusted cert', trust: 5 }, publiclyRevealedKeyring: { email: 'a2V5MQ==' }, decryptedFields: { email: 'user@example.com' } } +await run({ + name: 'discoverByIdentityKey', method: 'discoverByIdentityKey', + args: { identityKey, limit: 10, offset: 0 }, + result: { totalCertificates: 3, certificates: [discovered] } +}) +await run({ + name: 'discoverByAttributes', method: 'discoverByAttributes', + args: { attributes: { email: 'user@example.com' }, limit: 5, offset: 1, seekPermission: false }, + result: { totalCertificates: 1, certificates: [discovered] } +}) +await run({ + name: 'discoverByAttributes-legacy', divergence: 'legacy-certificate-type', method: 'discoverByAttributes', + args: { attributes: { name: 'Alice' } }, + result: { totalCertificates: 1, certificates: [{ ...certJSON(certLegacy), certifierInfo: discovered.certifierInfo, publiclyRevealedKeyring: { name: 'a2V5MQ==' }, decryptedFields: { name: 'Alice' } }] } +}) + +// ---- raw processor behaviour +await raw('unknown-call-30', '1e00') +await raw('truncated-getHeight-frame', '19') +await raw('trailing-getHeight', '190000') + +await Bun.write(OUTPUT, JSON.stringify({ + source: SOURCE, + rootKey: 'f0efba88c117ca2614554bb676d743f413822a31e3c8d70cfcc5fff119d20a07', + cases: out +}, null, 1)) +console.log(out.map(c => `${c.name}: ${c.outcome ? JSON.stringify(c.outcome).slice(0, 140) : 'raw'} frames=${c.frames.length}`).join('\n')) diff --git a/Tools/Conformance/TSOracle/generate.sh b/Tools/Conformance/TSOracle/generate.sh new file mode 100755 index 0000000..c802bdf --- /dev/null +++ b/Tools/Conformance/TSOracle/generate.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Generates the TypeScript wallet-wire oracle vectors with Bun. +# +# BSV_TS_SDK_PATH=/path/to/ts-stack/packages/sdk Tools/Conformance/TSOracle/generate.sh [output] +# +# The default output is .build/ts-oracle/ts-wallet-wire-vectors.json. Point +# BSV_TS_WALLET_WIRE_VECTORS at it when running `swift test`. The external +# checkout is only read; generated vectors are never committed. +set -eu + +oracle_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P) +repository_dir=$(CDPATH= cd -- "$oracle_dir/../../.." && pwd -P) +sdk_dir=${BSV_TS_SDK_PATH:?BSV_TS_SDK_PATH must name the @bsv/sdk package directory (packages/sdk)} +sdk_dir=$(CDPATH= cd -- "$sdk_dir" && pwd -P) +output=${1:-"$repository_dir/.build/ts-oracle/ts-wallet-wire-vectors.json"} + +[ -f "$sdk_dir/src/wallet/substrates/WalletWireProcessor.ts" ] || { + echo "$sdk_dir is not the @bsv/sdk package directory" >&2 + exit 3 +} +command -v bun >/dev/null 2>&1 || { echo "bun is required" >&2; exit 3; } + +version=$(bun -e "console.log(require('$sdk_dir/package.json').version)") +commit=$(git -C "$sdk_dir" rev-parse --short HEAD 2>/dev/null || echo unknown) +mkdir -p "$(dirname -- "$output")" + +BSV_TS_SDK_PATH="$sdk_dir" \ +BSV_TS_ORACLE_OUTPUT="$output" \ +BSV_TS_ORACLE_SOURCE="@bsv/sdk $version ($commit)" \ + bun "$oracle_dir/gen.ts" >/dev/null +echo "$output" From 7648c289f8887c6908faa33acc2fd820a805001d Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:52:09 +0000 Subject: [PATCH 4/8] Rewrite the wallet-wire rulings for TypeScript 4.1.1 COMP-045, 046, 048 and 050 now say why the wire follows @bsv/sdk 4.1.1 and what still differs from pinned Go. COMP-064 replaces the HMAC part of COMP-002. --- Documentation/Compatibility/GoSDK-v1.3.3.md | 18 +-- Documentation/Compatibility/Rulings.md | 11 +- .../COMP-045-Wallet-Wire-Strictness.md | 113 +++++++-------- .../Rulings/COMP-046-Wallet-Wire-Actions.md | 113 ++++++++------- .../COMP-048-Wallet-Wire-Certificates.md | 96 ++++++------- .../COMP-050-Wallet-Wire-Substrates.md | 135 ++++++++---------- 6 files changed, 220 insertions(+), 266 deletions(-) diff --git a/Documentation/Compatibility/GoSDK-v1.3.3.md b/Documentation/Compatibility/GoSDK-v1.3.3.md index e0a0a08..d2a3dff 100644 --- a/Documentation/Compatibility/GoSDK-v1.3.3.md +++ b/Documentation/Compatibility/GoSDK-v1.3.3.md @@ -465,17 +465,19 @@ are accepted for action calls 1 through 7, key calls 8 and 11 through 16, and queries 23 through 28. Certificate and linkage calls 9, 10, and 17 through 22 are also accepted. Canonical CompactSize, exact discriminators and fixed results, checked UInt32 conversion, complete error frames, and redacted bounded -remote errors follow COMP-045 and COMP-046. Go's absent `forSelf` value is -accepted and normalized to the required Swift value `false`; canonical Swift -output uses the explicit false byte. Action codecs require explicit BEEF limits -and a payload-bounded writer. They reject nil/empty collisions and the three -list-action script sentinels that the pinned Go writer emits but its reader -cannot consume. They add no wallet execution, transport, storage, or permission -policy. +remote errors follow COMP-045 and COMP-046. Since the 4.1.1 interop work the +wallet wire follows `@bsv/sdk` 4.1.1 where it differs from this Go release: +false `privileged` and `forSelf` are written as absent, list totals count +every match, createAction and signAction results use the TypeScript layout +with display-order txids, and processor failures are answered in-band +(COMP-050). The Go-oracle tests record each difference. Action codecs require +explicit BEEF limits and a payload-bounded writer and add no wallet execution, +transport, storage, or permission policy. Certificate wire codecs follow COMP-048. They use the existing strict BRC-52 binary codec, display-order revocation transaction IDs, low-S DER, bounded -UTF-8-byte-sorted maps, and exact keyring presence. `nil` keyring emits `00`; +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. A present empty keyring is rejected. 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 diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 267f8b4..23f5772 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -11,7 +11,7 @@ behind the general rule. | ID | Conflict | Proposed Swift behavior | Reason and test obligation | | --- | --- | --- | --- | | COMP-001 | CompactSize decoding in Go accepts non-minimal forms and some callers use max-u64 as “-1”. | Provide bounded permissive and canonical-required decoding policies. Encode canonically. Model max-u64 absence as a named sentinel only in formats that specify it; never as an ordinary length. | Preserves wire import compatibility without allowing ambiguous canonical output or unbounded allocation. Test every prefix boundary, truncation, non-minimal form, max-u64, and per-call maximum. | -| COMP-002 | BRC-2 prose describes a shared-secret hash input that disagrees with the published vectors and Go. | Follow the published vectors and Go v1.3.3 padded-x-coordinate derivation. Mark the prose conflict and do not offer a second silent variant. | The vectors are interoperable evidence. Test exact ciphertext, plaintext, HMAC, wrong counterparty/protocol/key ID, tag tampering, and IV/tag truncation. | +| COMP-002 | BRC-2 prose describes a shared-secret hash input that disagrees with the published vectors and Go. | Follow the published vectors and Go v1.3.3 padded-x-coordinate derivation for the AES-GCM key. Mark the prose conflict and do not offer a second silent variant. The HMAC key is ruled separately by COMP-064. | The vectors are interoperable evidence. Test exact ciphertext, plaintext, HMAC, wrong counterparty/protocol/key ID, tag tampering, and IV/tag truncation. | | COMP-003 | BRC-30 says four-byte source satoshis; Go and Bitcoin amounts use eight bytes. | Parse and emit unsigned 64-bit little-endian source amounts. Do not emit the ambiguous four-byte form. | Matches Go Extended Format and the transaction amount domain. Test Go↔Swift bytes and overflow/truncation. | | COMP-004 | BRC-43 gives 280/1033 limits; BRC-100 and Go use 400/800. Go's Unicode-aware trimming and lowercasing can also admit names outside a stable ASCII derivation profile. BRC-44 reserves `admin` protocols for trusted wallet internals. | Use protocol names of 5…400 UTF-8 bytes and key IDs of 1…800 UTF-8 bytes. Protocol names trim ASCII whitespace, lowercase ASCII, allow only letters, digits, and single spaces, reject the `admin` prefix and ` protocol` suffix, and do not normalize key IDs. The one wallet-internal WPM metadata identifier is available only as the explicit `WalletProtocolID.walletMetadataEncryption` constant; generic construction and application JSON/wire encoding and decoding continue to reject it. | Newer wallet limits and the parity baseline agree. The stricter Swift identifier policy fails closed rather than deriving a different key from Unicode or reserved-name artifacts. The named constant makes the wallet-internal exception auditable without widening external encoders or decoders. Tests cover byte boundaries, every ASCII character, Unicode rejection, reserved names, exact local fields and ProtoWallet output, boundary rejection, and distinct composed/decomposed key IDs. | | COMP-005 | BRC-48 specifies lock-after PushDrop; Go creates both but decodes only lock-before. | Decode and construct spec-conformant lock-after. Support lock-before through an explicitly named compatibility mode. | Achieves BRC conformance without losing Go ecosystem inputs. Test that no auto-detection ambiguity changes pushed data. | @@ -52,12 +52,12 @@ behind the general rule. | 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. | -| COMP-045 | Pinned Go wallet-wire readers accept nonminimal or lossy primitive forms, truncate UInt32 values, leave several result payloads partially consumed, normalize high-S ECDSA signatures to low-S, and do not bound raw result/error data. | Swift requires canonical CompactSize, exact optional-Boolean and counterparty discriminators, checked UInt32 conversion, full consumption for fixed/empty results and error frames, strict SEC1/DER/enums, low-S signatures, and explicit frame/payload/text/error bounds. Values that cannot survive Go-compatible re-encoding are rejected. Go's absent `forSelf` value is accepted and normalized to the required Swift value `false`, which emits as `00`. The oracle runs a non-allocating, call-aware complete-grammar preflight before the selected pinned serializers. | Canonical packets for the 13 key/query calls remain interoperable while hostile or ambiguous input fails predictably. Tests cover CompactSize prefix widths through MaxUInt64, count-limit versus truncation classification, fixed-field truncations, discriminators, UInt32 overflow, DER scalar range and low-S boundaries, applicable trailing-byte families, exact frame maxima, and checked size overflow; a persistent pinned-Go oracle re-encodes independently authored canonical packets without importing Go fixtures. | -| COMP-046 | Go wallet-wire action readers accept lossy values, and fixed-array result transaction IDs cannot represent absence. The create-action signable union re-encodes with a fixed zero transaction ID. Go also collapses empty create inputs and zero-length string entries, and its list-action result writer can emit three absent-script sentinels that its reader cannot consume. | Swift provides payload-bounded typed codecs for calls 1 through 7. It requires explicit BEEF limits, sorted unique spend indexes, field-specific transaction ID byte order, exact discriminators, checked UInt32 values, full consumption, matching result totals, nonempty create inputs/scripts where Go loses the distinction, and present list-action result scripts. It rejects values that cannot round-trip through the pinned codec. | Canonical action packets remain byte-compatible with Go v1.3.3. The packet adds serialization only. It does not add wallet behavior, transport, storage, or permission policy. | +| COMP-045 | Pinned Go and `@bsv/sdk` 4.1.1 write different wallet-wire primitives: Go writes false optional Booleans as `00`, rejects zero-length list entries and sends false verifications as transport errors. | Follow TypeScript 4.1.1: omitted `privileged` and `forSelf` are `ff`, an omitted counterparty `00` reads as the call default, empty list entries have length 0, false verifications are code-1 error frames, error codes are clamped to 1…8 and messages to 4,096 bytes with an empty stack. Keep canonical CompactSize, explicit bounds, checked UInt32 and low-S DER. | TypeScript wallets and apps are the 1Sat wallet's peers, so the wire must match their bytes; the bounds reject only hostile input. Tests cite TypeScript source lines, a live TypeScript oracle replays every call, and Go-oracle tests record the Go divergences. See [COMP-045](Rulings/COMP-045-Wallet-Wire-Strictness.md). | +| COMP-046 | Pinned Go and `@bsv/sdk` 4.1.1 use different action layouts: Go adds a leading byte to createAction results, writes wire-order txids, requires result txids, list totals equal to record counts, sorted spends and nonempty inputs. | Follow TypeScript 4.1.1 for calls 1 through 7: TS createAction and signAction layouts with optional txid and signable transaction, display-order txids, abort refusal as code 8, totals that count every match with records to the end of the frame, UInt64 BRC-112 balances, the optional spendable listOutputs extension, optional listActions scripts, empty inputs, any spend order. Keep BEEF limits, payload bounds and full consumption. | The createAction/signAction flow, paged history and balances must cross the wire with TypeScript peers. Tests cite TypeScript source lines; Go-oracle tests record that pinned Go cannot read the TypeScript createAction and signAction results. See [COMP-046](Rulings/COMP-046-Wallet-Wire-Actions.md). | | COMP-047 | Pinned Go Script JSON emits a quoted lowercase hexadecimal string, but its exported unmarshal method trims quote bytes from both ends instead of parsing exactly one JSON string token. It accepts uppercase hex, unquoted hex, and extra quote bytes, while JSON escape sequences fail as hexadecimal input. | Swift accepts one unescaped lowercase hexadecimal JSON string, permits only RFC JSON whitespace around it, consumes the full document, and requires caller-selected JSON and Script byte limits. It rejects uppercase, escaped, non-string, and trailing forms instead of normalizing them. | Canonical documents remain byte-compatible in both directions. Strict parsing prevents invalid JSON tokens and multiple wire images from entering the typed Script model. Live pinned-Go tests record each shared and divergent form through hex-encoded document bytes. | -| COMP-048 | Pinned Go certificate wire readers accept noncanonical or lossy forms. Its list result collapses absent and present-empty keyrings, its prove-result writer does not sort map entries, and its identity-certificate reader checks for end of input inside each item so it cannot read a discovery result with more than one certificate. | Swift provides strict bounded typed codecs for calls 9, 10, and 17 through 22. It requires canonical CompactSize, compressed keys, checked UInt32 values, display-order certificate outpoint transaction IDs, low-S DER, complete consumption, and raw UTF-8-byte-sorted unique maps. `WalletCertificateResult.keyring` is optional: `nil` is `00`, and a nonempty value is `01` plus the map. A present empty keyring is rejected. Swift implements the intended bounded multi-certificate discovery grammar; the live-Go adapter rejects multiple items before the defective pinned reader runs. | Canonical zero- and one-certificate packets remain byte-compatible with Go v1.3.3, while Swift does not inherit the pinned reader defect. Persistent live-Go tests cover every call and both keyring presence arms. Swift tests cover multiple discovery certificates. The packet adds serialization only; it does not add transport, storage, permission policy, or revocation lookup. | +| COMP-048 | Pinned Go certificate wire requires sorted maps and record counts equal to totals and cannot read multi-record discovery; `@bsv/sdk` 4.1.1 writes insertion-ordered maps, page totals and probes call 29. | Follow TypeScript 4.1.1: read maps in any order and reject duplicates, treat totals as the count of every match, carry the listCertificates verifier as 33 key bytes, read JSON `keyring: {}` as no keyring, and answer call 29 with code 1 `Invalid call code: 29`. Keep canonical CompactSize, compressed keys, low-S DER and full consumption. | TypeScript peers must be able to list, discover and prove certificates with a Swift wallet. The full call-29 profile is not implemented because it carries certificate types other than 32 bytes. See [COMP-048](Rulings/COMP-048-Wallet-Wire-Certificates.md). | | COMP-049 | Pinned Go transaction JSON gives `hex` priority and ignores inconsistent expanded fields. Without `hex`, it discards inputs and outputs. It accepts unknown and duplicate keys, missing component fields, short or uppercase input transaction IDs, and unsafe `uint64` JSON numbers. Raw empty collections marshal as `null`. | Swift requires one complete bounded object. It rejects unknown and duplicate keys, invalid UTF-8, noncanonical hex and IDs, trailing values, and integers above 9,007,199,254,740,991. The transaction ID and every expanded field must match the raw transaction in `hex`. It emits canonical `null` empty collections and accepts `null` or `[]` as empty. | Canonical compact documents remain byte-compatible in both directions. Construction metadata is not part of this raw-transaction JSON format. Persistent pinned-Go tests record the shared format and the lossy Go differences. | -| COMP-050 | Go provides wallet-wire processors and transceivers that pass the originator to each wallet method and do not require explicit resource limits. | Swift provides bounded transport-neutral processors and transceivers. A required authorizer checks the originator before wallet dispatch. The processor uses the existing strict codecs for all 28 calls. | Preserves the Go binary wallet-wire boundary without adding HTTP, WebSocket, persistence, retry, or wallet policy. | +| COMP-050 | Go wallet-wire processors return malformed requests as transport errors and pass the originator to each wallet method; `@bsv/sdk` 4.1.1 answers every failure in-band. | Swift provides bounded transport-neutral processors and transceivers with a required originator authorizer. Every processor failure, including unknown calls and malformed requests, is an error frame with the TypeScript message. | A TypeScript transceiver must see an error frame, not a dead transport, and must be able to fall back after the call-29 probe. See [COMP-050](Rulings/COMP-050-Wallet-Wire-Substrates.md). | | COMP-051 | Go's interpreter debugger stores mutable callback lists and clones mutable VM state; its declared rewind option is unimplemented. | Swift uses an opt-in bounded immutable `Sendable` event stream, redacts descriptions/reflection, and omits rewind. | Preserves deterministic lifecycle observability without exposing mutable execution state or creating callback races. | | COMP-052 | Pinned Go auth accepts variable nonce lengths, can lose random-source failures, authenticates an unsigned initial request, and does not enforce the expected peer identity. BRC-103 uses version `0.1`, while some BRC-104 material shows `1.0`. | Swift emits and accepts BRC-103 version `0.1`, accepts 32-byte nonces and the exact 48-byte Go form, propagates random failures, binds the expected peer, and authenticates a responder only after a signed general message. The transport-neutral BRC-104 payload has no separate version field. | Canonical shared messages and payloads remain interoperable. Strict JSON, low-S DER, replay checks, cancellation, session limits, and payload limits prevent the pinned defects and ambiguous input from entering session state. | | COMP-053 | Go combines overlay values with HTTP facilitators, mutable resolver defaults, wallet-backed admin tokens, and `any`-typed lookup values. | `BSVOverlay` provides only bounded SHIP/SLAP values and transport-neutral async facilitator protocols with typed byte payloads. | Preserves useful Go vocabulary without accepting unbounded data, hidden network policy, or mutable or erased result state. | @@ -71,6 +71,7 @@ behind the general rule. | COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It validates the exact four-field advertisement, binds it to the requested identifier, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the canonical `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | +| COMP-064 | BRC-56 HMAC key: COMP-002 used the 32-byte padded X coordinate (Go v1.3.3); `@bsv/sdk` 4.1.1 and earlier TypeScript SDKs use the minimal-length X coordinate and reject padded-key tags. | `createHMAC` uses the minimal-length key. `verifyHMAC` accepts the minimal or the 32-byte padded key. AES-GCM keeps the 32-byte key. | TypeScript wallets and apps are the 1Sat wallet's peers; tags must verify both ways. Accepting padded tags keeps earlier Swift and Go tags valid. Tests use the six TypeScript BRC-56 vectors. See [COMP-064](Rulings/COMP-064-Wallet-HMAC-Key.md). | ## Scope decisions diff --git a/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md b/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md index 4e1038a..0245b9a 100644 --- a/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md +++ b/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md @@ -1,70 +1,55 @@ -# COMP-045: Canonical and bounded wallet-wire decoding +# COMP-045: Wallet-wire primitives follow TypeScript 4.1.1 -## Context +Status: Accepted. Revised: the wire now follows `@bsv/sdk` 4.1.1 instead of +pinned Go v1.3.3. -Pinned Go wallet serializers accept several values that cannot be reproduced -without ambiguity or unsafe allocation. Their readers accept nonminimal -CompactSize counts, optional Boolean bytes `02...fe`, UInt32 truncation, and an -uninitialized counterparty byte. Some result readers ignore trailing payload, -accept unknown enum bytes as zero values, or consume only the first 32 HMAC -bytes. Error-result framing also permits trailing bytes after the stack. -Pinned Go's ECDSA parser also normalizes a valid high-S signature to low-S, so -deserializing and reserializing call-16 requests or call-15 results can change -their bytes even when the DER structure is canonical. +## Why the wire follows TypeScript -## Ruling - -Swift emits canonical CompactSize and applies explicit frame, payload, text, -originator, error-message, and error-stack bounds before copying fields. It -accepts optional Boolean only as `00`, `01`, or one-byte `ff`; a missing -privileged reason is one-byte `ff`. Public counterparties are self, anyone, or -one exact compressed SEC1 key. UInt32 values do not truncate. - -The Swift request models store `forSelf` as a required Boolean. Swift accepts -the Go optional-Boolean absence byte and normalizes it to `false`. Canonical -Swift output emits `00` for `false` and `01` for `true`. It does not emit the -absence byte for this required value. +TypeScript wallets and apps are the 1Sat wallet's peers. Every binary +wallet-wire frame a Swift processor or transceiver exchanges with them must +have the bytes `@bsv/sdk` 4.1.1 writes and must accept the bytes it sends. +Where pinned Go v1.3.3 differs, Swift now follows TypeScript and records the +Go difference as a divergence in the Go-oracle tests. -The pinned-Go oracle applies a non-allocating, call-aware byte-index preflight -before invoking a selected wallet serializer. For calls 8, 11 through 16, and -23 through 28 it checks the complete request and success-result grammar: -canonical CompactSize widths, bounded counts before slicing, exact fixed -fields and sentinels, checked UInt32 heights, protocol/key/access/counterparty -fields, both public-key request arms, signature data/digest arms, bounded DER -structure, empty-call shapes, and full consumption. A declaration above its -field or operation maximum is a resource-limit failure; a declaration within -the maximum that exceeds the remaining packet is a truncation. Remote-error -message and stack counts use the same distinction. The final process-level -panic recovery remains a sanitized last resort and never includes packet data. -DER preflight validates nonzero R and S scalars below the secp256k1 order with -fixed-width byte comparisons and requires S at or below the curve half-order. -High-S is rejected as non-round-trippable before pinned Go can normalize it. +Safety bounds stay. They reject hostile or malformed input but never +legitimate TypeScript traffic. -Typed result decoding requires exact HMAC, public-key, DER-signature, header, -authentication, network, and empty-success shapes. A verification or -wait-for-authentication success represents only `true`; `false` cannot be -encoded through a Go-compatible success frame. Empty optional strings/bytes -that Go changes into absence, and empty verify-signature data that changes the -semantic arm, are rejected as non-round-trippable. - -## Consequences +## Ruling -Canonical Swift values for the 13 key/query calls remain byte-compatible with -Go v1.3.3. A Go absent `forSelf` value is the documented exception: Swift -accepts it and emits explicit false on re-encoding. Malformed inputs fail with -redacted typed errors rather than being normalized, truncated, ignored, or -used to allocate without a bound. Raw -request framing still recognizes all defined calls 1 through 28, but the typed -key/query API is intentionally closed to calls 8, 11 through 16, and 23 through -28. COMP-046 adds the separate typed action subset. Certificate, transport, -wallet behavior, persistence, and permission policy remain outside this -checkpoint. The hostile Go matrix specifically -covers FD/FE/FF CompactSize widths including -MaxUInt64, noncanonical and truncated encodings, bounded-versus-short declared -counts, fixed-field truncations, invalid discriminators, UInt32 overflow, DER -structure and scalar boundaries, high-S rejection, empty/fixed result shapes, -and trailing bytes in the applicable -request and result grammar families. Swift tests cover exact success/failure -frame maxima, CompactSize prefix growth, checked-add overflow, and limit -relationships. A persistent pinned-Go oracle checks canonical request and -result re-encoding in both directions without importing Go fixtures. +Encoding follows the TypeScript writers in +`packages/sdk/src/wallet/substrates/WalletWireTransceiver.ts` and +`WalletWireProcessor.ts`: + +- An omitted optional Boolean is `ff`. TypeScript writes a byte only for a + boolean value, and its callers omit `false`, so Swift writes `privileged` + and `forSelf` as `ff` when they are false. It reads `00`, `01` and `ff`. +- An omitted counterparty is `00`. Swift reads it as the call's default + (`self`, or `anyone` for `createSignature`). +- An empty string in a label or tag list is written with length 0. Length 0 + and `-1` both read as the empty string. +- An omitted optional string in a request may be empty. +- A false `verifyHMAC` or `verifySignature` result is the error frame + TypeScript sends: code 1 with `HMAC is not valid` or + `Signature is not valid`. +- Error frames carry a code from 1 to 8. Any other code is sent as 1. The + message is cut to 4,096 UTF-8 bytes on a character boundary, and the stack + is empty. The standard remote message limit is 4,096 bytes. + +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. + +## Divergence from pinned Go v1.3.3 + +Go stores `privileged`, `forSelf` and `seekPermission` as plain Booleans and +writes `00` for false where Swift and TypeScript write `ff`. The safe Go +adapter rejects zero-length list entries. `WalletWireGoOracleTests` and +`WalletWireActionGoOracleTests` assert both differences. + +## Tests + +`WalletWireKeyQueryTests`, `WalletWireAdversarialTests` and +`WalletWireTypeScript41VectorTests` cover the vectors with TypeScript source +citations. `WalletWireTypeScriptOracleTests` compares every call with live +TypeScript frames when `BSV_TS_WALLET_WIRE_VECTORS` is set +(`Tools/Conformance/TSOracle/generate.sh`). diff --git a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md index 3931ec2..a27c172 100644 --- a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md +++ b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md @@ -1,60 +1,59 @@ -# COMP-046: Strict wallet-wire action values - -## Context - -Go v1.3.3 has useful wallet-wire serializers for calls 1 through 7. Some -readers also accept values that they cannot reproduce. Examples include -unordered or duplicate spend indexes, truncated UInt32 values, permissive -Boolean bytes, empty optional data, and result payloads with trailing data. -Go also decodes a present empty create-input slice as absent and decodes an -empty create-output locking script through its optional-byte helper. Both -forms change or fail when Go writes or reads them again. A present zero-length -string-slice element becomes the absent-string sentinel when Go writes it. -The Go action-result structs also store a transaction ID as a fixed array. -Their serializers always emit that field, even when a caller did not set it. -The create-action serializer cannot preserve its signable-transaction union -without also emitting this fixed zero transaction ID. +# COMP-046: Wallet-wire action calls follow TypeScript 4.1.1 + +Status: Accepted. Revised: calls 1 through 7 now use the `@bsv/sdk` 4.1.1 +layouts instead of pinned Go v1.3.3. + +## Why the wire follows TypeScript + +TypeScript wallets and apps are the 1Sat wallet's peers (COMP-045). The +two-step `createAction` and `signAction` flow, paged history and BRC-112 +balances must cross the wire between Swift and TypeScript in both directions. ## Ruling -Swift provides stateless, bounded, typed codecs for create, sign, abort, list, -internalize, list-output, and relinquish-output calls. Callers must supply -explicit `BEEFLimits`. Swift parses BEEF and Atomic BEEF values before it -admits them to the typed model. - -Swift emits spend-map entries in ascending input-index order. It rejects -duplicate or unordered indexes on input. It uses the exact Go field-specific -transaction ID order: display order in action and outpoint fields, and wire -order in transaction-ID lists and completed-action results. It requires -canonical CompactSize, exact discriminators, checked UInt32 conversion, -bounded text and collections, and full payload consumption. - -The encoder writes through a payload-bounded destination. It uses checked size -arithmetic and stops an append before the destination can exceed the caller's -`maximumPayloadByteCount`. - -Swift rejects values that the Go codec cannot reproduce without loss. This -includes an absent transaction ID in create-action and sign-action results, -the pinned Go signable create-action result artifact, false values for -implicit-success results, empty optional values that become absent, and list -totals that do not match their item counts. - -Swift also rejects a present empty create-input slice, an empty create-output -locking script, and a present zero-length string-slice element. Required slice -fields cannot use the absent sentinel. The Swift ABI cannot preserve the Go -distinction between an absent required slice and an empty slice, so accepting -the sentinel would normalize the value and change its bytes. - -Pinned Go v1.3.3 writes list-action input source locking scripts, input -unlocking scripts, and output locking scripts with its optional-byte writer, -but reads the same three fields with its required-byte reader. The sentinel -that the writer emits for `nil` is not readable by that reader. The Swift -subset therefore requires all three scripts and rejects the sentinel before -the pinned reader runs. - -## Consequences - -Canonical packets in the Swift action subset round-trip through the pinned Go -v1.3.3 serializers. Hostile or lossy packets fail before the oracle calls Go. -The codec does not add wallet execution, a processor, transport, storage, or -permission policy. +- **createAction result.** Txid flag and display-order txid, tx flag and + Atomic BEEF, `noSendChange` count or `-1` and outpoints, `sendWithResults` + count or `-1` with display-order txid and status byte, then the signable + flag with transaction and reference. There is no extra leading byte. The + txid and the signable transaction may each be absent. +- **signAction result.** Txid flag and display-order txid, tx flag and Atomic + BEEF, `sendWithResults` as above. Either part may be absent. +- **Transaction IDs** in results, `knownTxids` and `sendWith` use display + order, as TypeScript writes `toArray(txid, 'hex')`. +- **abortAction refusal.** `aborted: false` is the error frame with code 8 and + `The wallet refused to abort this action because it has already been + broadcast`. The transceiver reads code 8 as `aborted: false`. +- **List totals.** `totalActions` and `totalOutputs` count every match. The + page follows the total with no record count and ends at the end of the + frame. A page may be shorter than its total. Swift rejects a page with more + records than its total, or more records than the request's limit (BRC-100 + default 10). +- **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. +- **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 + non-spendable output is refused with the TypeScript message. +- **Optional values.** Empty `createAction` inputs (count 0) and absent inputs + (`-1`) are distinct and both allowed. An absent tag or label list reads as + empty. listActions input and output scripts may be absent. Spend indexes may + arrive in any order; duplicates are rejected. + +Swift keeps explicit BEEF limits, payload-bounded writing, checked arithmetic, +exact discriminators and full consumption. + +## Divergence from pinned Go v1.3.3 + +Go uses its own createAction and signAction result layouts and wire-order +txids there, requires list totals to equal the record count, and rejects +absent result parts, unsorted spends, empty inputs and zero-length list +entries. `WalletWireActionGoOracleTests` asserts that pinned Go cannot read +the TypeScript createAction and signAction results. All other canonical action +frames still match Go byte for byte. + +## Tests + +`WalletWireActionAdversarialTests`, `WalletWireActionTests` and +`WalletWireTypeScript41VectorTests` cover the layouts with TypeScript source +citations. `WalletWireTypeScriptOracleTests` replays live TypeScript frames. diff --git a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md index 70dda08..5de6b74 100644 --- a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md +++ b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md @@ -1,59 +1,49 @@ -# COMP-048: Wallet-wire certificate strictness +# COMP-048: Wallet-wire certificate calls follow TypeScript 4.1.1 -Status: Accepted. +Status: Accepted. Revised: certificate calls now accept the `@bsv/sdk` 4.1.1 +forms instead of requiring pinned Go v1.3.3 ordering and totals. -## Context +## Why the wire follows TypeScript -Pinned Go v1.3.3 defines wallet-wire calls 9, 10, and 17 through 22. Its -canonical writers sort most certificate maps, use display-order transaction ID -bytes in certificate revocation outpoints, and use CompactSize for lengths and -counts. - -The pinned implementation also has three observable artifacts: - -- A list-certificate result uses `00` for an absent keyring and `01` plus a map - for a present keyring. Its reader turns a present empty map into absence. -- The prove-certificate result writer ranges over its map without sorting. -- The identity-certificate reader checks for end of input inside one item. It - cannot read a discovery result that contains more than one certificate. - -The separate Go maintainer report tracks this issue as -[GO-001](../GoSDK-v1.3.3-Defects.md#go-001-discovery-results-cannot-contain-more-than-one-identity-certificate). - -Several pinned readers also accept nonminimal CompactSize, unchecked UInt32 -conversion, unsorted or duplicate maps, non-low-S signatures, loose presence -bytes, or trailing data. +TypeScript wallets and apps are the 1Sat wallet's peers (COMP-045). Their +certificate frames must be read and answered without rejection. ## Ruling -Swift provides strict bounded typed request and result codecs for the eight -calls. The codecs: - -- Require canonical CompactSize and complete input consumption. -- Check all counts and lengths before collection allocation or copying. -- Require canonical compressed public keys and low-S DER signatures. -- Use display-order transaction ID bytes for certificate revocation outpoints. -- Emit and require unique map keys in raw UTF-8 byte order. -- Require canonical Base64 in embedded certificate field values. -- Use checked UInt32 conversions for outpoint indexes and pagination. -- Keep request, result, direct ABI, and reflection diagnostics redacted. - -`WalletCertificateResult.keyring` is optional. `nil` encodes as `00`. A -nonempty map encodes as `01` followed by the map. The initializer and decoder -reject a present empty map because Go cannot preserve that state. - -Swift implements the intended bounded nested grammar for discovery results and -supports multiple certificates. Live-Go byte parity covers zero or one item. -The safe Go adapter rejects multiple items before it calls the defective pinned -reader. For a prove-certificate result, the live Go adapter performs strict -canonical preflight and pinned typed parsing, then returns the validated input -bytes. It does not return nondeterministic pinned map-writer output. - -## Consequences - -Canonical zero- and one-certificate packets have the same bytes in Swift and -pinned Go v1.3.3. Swift also supports bounded multi-certificate discovery -packets, although pinned Go cannot read them. Malformed, lossy, or -nondeterministic forms fail with bounded typed errors. The packet supplies -serialization only. It does not supply wallet execution, persistence, -transport, permission prompts, certificate revocation checks, or trust policy. +- **Map order.** TypeScript writes keyrings, fields and attributes in object + insertion order. Swift reads maps in any order and rejects only a repeated + name. Swift writes maps sorted by raw UTF-8 bytes, which TypeScript accepts. +- **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, and never longer than the + request's limit. +- **listCertificates verifier.** The wire carries the 33 compressed key bytes, + or length 0 when absent. The ABI and JSON keep the hex text. Any other + length is refused. +- **Keyring presence.** `nil` is `00`; a nonempty map is `01` and the map. + TypeScript writes an empty keyring as `00` and returns `{}` for it, so JSON + `keyring: {}` reads as no keyring. +- **Call 29.** TypeScript 4.x probes call 29 (certificate compatibility + profile) before discovery and some list, prove and relinquish calls. A Swift + processor answers code 1 `Invalid call code: 29`, the exact answer on which + the TypeScript transceiver falls back to the plain calls. The full profile + is not implemented: it exists to carry certificate types other than 32 bytes, + which Swift `CertificateTypeID` cannot represent. + +Swift keeps canonical CompactSize, compressed keys, low-S DER, checked UInt32 +values, canonical Base64 and full consumption. + +## Divergence from pinned Go v1.3.3 + +The safe Go adapter requires sorted maps and a record count equal to the +total, and the pinned identity-certificate reader cannot read more than one +discovery record (GO-001). `WalletWireCertificateGoOracleTests` asserts the +total difference. Canonical certificate frames with sorted maps still match Go +byte for byte. + +## Tests + +`WalletWireCertificateTests`, `WalletWireCertificateAdversarialTests` and +`WalletWireTypeScript41VectorTests` cover these forms. +`WalletWireTypeScriptOracleTests` replays live TypeScript frames, including the +call-29 probe and fallback. diff --git a/Documentation/Compatibility/Rulings/COMP-050-Wallet-Wire-Substrates.md b/Documentation/Compatibility/Rulings/COMP-050-Wallet-Wire-Substrates.md index 085f34a..aad2e09 100644 --- a/Documentation/Compatibility/Rulings/COMP-050-Wallet-Wire-Substrates.md +++ b/Documentation/Compatibility/Rulings/COMP-050-Wallet-Wire-Substrates.md @@ -1,90 +1,67 @@ # COMP-050: Transport-neutral wallet-wire substrates -Status: Accepted +Status: Accepted. Revised: processor failures are answered in-band, as +`@bsv/sdk` 4.1.1 does. -## Scope - -This ruling covers the Go SDK v1.3.3 `wallet/substrates` binary wallet-wire -processor and transceiver. It covers call discriminators 1 through 28. - -HTTP JSON, HTTP wallet-wire, WebSocket, retry, persistence, and wallet -implementation behavior are outside this scope. - -## Decision +## Why the wire follows TypeScript -Swift provides these transport-neutral boundaries: +TypeScript wallets and apps are the 1Sat wallet's peers (COMP-045). A +TypeScript transceiver reads every processor failure, including a request it +built wrongly or a call the processor does not know, as an error frame. A +transport error instead looks like a dead connection, and the call-29 probe +fails outright. -- `WalletWireTransport` sends one bounded request. Each call supplies the - maximum response byte count. The transport must enforce that limit before it - buffers or copies a larger response. -- `WalletWireProcessor` decodes a complete request, authorizes its originator, - calls a supplied `WalletInterface`, and encodes one result. -- `WalletWireTransceiver` binds one validated originator to one transport and - implements `WalletInterface`. -- `WalletWireOriginatorAuthorizing` is a required injected capability. The - processor does not silently accept an originator. -- `WalletWireFailureMapping` controls conversion of wallet and authorization - failures to remote errors. `WalletWireRedactingFailureMapper` preserves an - existing bounded remote error and redacts any other error. - -The processor and transceiver require explicit `WalletWireLimits`, -`BEEFLimits`, and `CertificateLimits`. They use the existing wallet-wire codecs. -They do not add a second serializer. +## Scope -## Originator model +Binary wallet-wire processor and transceiver, calls 1 through 28, plus the +in-band answer to call 29. HTTP JSON, WebSocket, retry, persistence and +wallet behavior are out of scope. -Go passes the originator string to every wallet method. The current Swift -`WalletInterface` methods do not take an originator. Swift therefore enforces -originator policy at an injected processor boundary before wallet dispatch. -The transceiver stores one originator that its initializer validates. +## Decision -An application that needs originator-specific wallet state must construct an -originator-bound processor and wallet facade. Its authorizer must reject every -other originator. The substrate does not use task-local state or an implicit -global originator. +- `WalletWireTransport` sends one bounded request with a caller-supplied + response limit. +- `WalletWireProcessor` decodes a request, authorizes its originator, calls + the wallet and encodes one result frame. +- `WalletWireTransceiver` binds one originator to one transport and + implements `WalletInterface`. Its `listOutputsEncoding` selects the + optional spendable listOutputs extension (COMP-046). +- `WalletWireOriginatorAuthorizing` is required. The processor never accepts + an originator silently. +- `WalletWireFailureMapping` turns authorization and wallet failures into + remote errors. `WalletWireRedactingFailureMapper` keeps an existing bounded + remote error and otherwise sends `Wallet operation failed`, as TypeScript + does for an error that is not a `WalletError`. +- Processor and transceiver require explicit wire, BEEF and certificate + limits. ## Error and cancellation model -Malformed requests fail as processor transport errors. This matches the pinned -Go processor contract. Malformed results fail with the strict typed codec -errors. The processor does not call the authorizer or wallet for malformed -operation parameters. - -Authorization and wallet failures use a result failure frame. The standard -mapper does not copy the source error text. `WalletWireRemoteError` keeps its -existing redacted description and reflection behavior. A caller can inspect -its explicit bounded `code`, `message`, and `stack` properties. - -Transport failures become `WalletWireSubstrateError.transportFailure`. This -error does not retain transport text. `CancellationError` stays cancellation -at the client, authorizer, processor, wallet, and transport boundaries. - -## Intentional differences from Go v1.3.3 - -- Go constructors do not require resource limits. Swift requires all limits. -- Go passes originator to the wallet method. Swift uses the required injected - originator authorizer because `WalletInterface` has no originator parameter. -- The Go processor returns wallet failures through the transport error path. - Swift encodes them as bounded result failure frames so a remote transport can - preserve the protocol distinction. -- Swift hides arbitrary transport and wallet error text by default. -- Swift rejects noncanonical or trailing operation data through the existing - strict codecs. - -## Supported calls - -All 28 calls map to current typed models and codecs: - -- Calls 1 through 7 use the action and output codecs. -- Calls 8 and 11 through 16, and calls 23 through 28, use the key and query - codecs. -- Calls 9, 10, and 17 through 22 use the certificate, linkage, and discovery - codecs. - -There is no model gap for this packet. - -The substrate inherits the existing codec representability rules. Examples -include false verification results, false completion results, and the pinned -Go create-action signable union. A wallet result that the codec marks as -non-round-trippable fails at the processor boundary. The substrate does not -replace it with a different value. +Every failure becomes an error frame (code, message, empty stack), as +`WalletWireProcessor.ts` does: + +- An unknown call, including 29, is code 1 `Invalid call code: N`. +- A truncated request is code 1 + `ReaderUint8Array read exceeds available data`. +- Trailing request bytes are code 1 + `Wallet Wire request contains trailing data`. +- Any other malformed request is code 1 `Invalid Wallet Wire request:` + followed by a short reason that never contains payload bytes. +- A wallet result the codec cannot write is code 1 `Invalid result:` + and a short reason. `WalletWireResultRejection` carries a specific code and + message, such as code 8 for an abort refusal. +- Authorization and wallet failures use the failure mapper. + +Codes outside 2 through 8 are sent as 1. Messages are cut to the configured +limit (4,096 bytes by default). The malformed request never reaches the +authorizer or the wallet. `CancellationError` still propagates at every +boundary, and transport failures stay `WalletWireSubstrateError.transportFailure`. + +## Differences from pinned Go v1.3.3 + +- Go returns malformed requests through the transport error path. Swift and + TypeScript answer in-band. +- Go constructors do not require limits. Swift requires them. +- Go passes the originator to each wallet method. Swift uses the injected + authorizer because `WalletInterface` has no originator parameter. +- Swift hides arbitrary wallet error text by default. From 31462534a9147e53c880407e568f5a90e7c9159a Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:56:22 +0000 Subject: [PATCH 5/8] Explain wallet-wire refusals in plain words WalletWireResultRejection gets an errorDescription a wallet can show. The message keeps the exact @bsv/sdk wire text and description keeps both for logs. --- .../BSVWallet/Wire/WalletWireFailures.swift | 16 ++++++++++++ .../WalletWireFailureDescriptionTests.swift | 26 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 Tests/BSVWalletTests/Wire/WalletWireFailureDescriptionTests.swift diff --git a/Sources/BSVWallet/Wire/WalletWireFailures.swift b/Sources/BSVWallet/Wire/WalletWireFailures.swift index 366afd1..250e00e 100644 --- a/Sources/BSVWallet/Wire/WalletWireFailures.swift +++ b/Sources/BSVWallet/Wire/WalletWireFailures.swift @@ -1,3 +1,5 @@ +import Foundation + /// A result the wallet wire answers with an error frame, as `@bsv/sdk` 4.1.1 does. /// /// The codecs throw this when a wallet result has no success encoding (for @@ -16,6 +18,20 @@ public struct WalletWireResultRejection: Error, Equatable, Sendable, CustomStrin public var description: String { "WalletWireResultRejection(code: \(code), message: \(message))" } } +/// Plain sentences a wallet can show. `message` keeps the exact `@bsv/sdk` +/// text that goes on the wire, and `description` keeps code and message for logs. +extension WalletWireResultRejection: LocalizedError { + public var errorDescription: String? { + if code == WalletWireErrorCode.abortRefused { + return "The wallet could not cancel this action because it was already broadcast." + } + if message.hasPrefix("Invalid ") || message.hasPrefix("Wallet Wire ") || message.hasPrefix("Missing ") { + return "The wallet's answer was not in a form the other side can read." + } + return message.hasSuffix(".") ? message : message + "." + } +} + /// Error codes shared with `@bsv/sdk` `walletErrors`. enum WalletWireErrorCode { static let unknownError: UInt8 = 1 diff --git a/Tests/BSVWalletTests/Wire/WalletWireFailureDescriptionTests.swift b/Tests/BSVWalletTests/Wire/WalletWireFailureDescriptionTests.swift new file mode 100644 index 0000000..d49c898 --- /dev/null +++ b/Tests/BSVWalletTests/Wire/WalletWireFailureDescriptionTests.swift @@ -0,0 +1,26 @@ +import BSVWallet +import Foundation +import Testing + +/// What a wallet shows when the wallet wire refuses a result. +@Suite("Wallet wire refusal descriptions") +struct WalletWireFailureDescriptionTests { + @Test("refusals read as plain sentences and keep the wire text for logs") + func refusalSentences() { + let abort = WalletWireResultRejection( + code: 8, + message: "The wallet refused to abort this action because it has already been broadcast" + ) + #expect(abort.localizedDescription + == "The wallet could not cancel this action because it was already broadcast.") + + let page = WalletWireResultRejection( + message: "Invalid listActions result: returned 3 records but declared a total of 2" + ) + #expect(page.localizedDescription == "The wallet's answer was not in a form the other side can read.") + #expect(String(describing: page).contains("returned 3 records but declared a total of 2")) + + let relinquish = WalletWireResultRejection(message: "The wallet did not relinquish the output") + #expect(relinquish.localizedDescription == "The wallet did not relinquish the output.") + } +} From 4b2f533a5a8dc9bc8fd95b15323e713aa8205db7 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:57:46 +0000 Subject: [PATCH 6/8] Renumber the wallet HMAC key ruling to COMP-065 COMP-064 is taken by the interpreter Chronicle rules ruling. --- Documentation/Compatibility/Rulings.md | 4 ++-- ...OMP-064-Wallet-HMAC-Key.md => COMP-065-Wallet-HMAC-Key.md} | 2 +- Tests/BSVWalletTests/ProtoWalletTests.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) rename Documentation/Compatibility/Rulings/{COMP-064-Wallet-HMAC-Key.md => COMP-065-Wallet-HMAC-Key.md} (98%) diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index fa4a23b..b1f3cd9 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -11,7 +11,7 @@ behind the general rule. | ID | Conflict | Proposed Swift behavior | Reason and test obligation | | --- | --- | --- | --- | | COMP-001 | CompactSize decoding in Go accepts non-minimal forms and some callers use max-u64 as “-1”. | Provide bounded permissive and canonical-required decoding policies. Encode canonically. Model max-u64 absence as a named sentinel only in formats that specify it; never as an ordinary length. | Preserves wire import compatibility without allowing ambiguous canonical output or unbounded allocation. Test every prefix boundary, truncation, non-minimal form, max-u64, and per-call maximum. | -| COMP-002 | BRC-2 prose describes a shared-secret hash input that disagrees with the published vectors and Go. | Follow the published vectors and Go v1.3.3 padded-x-coordinate derivation for the AES-GCM key. Mark the prose conflict and do not offer a second silent variant. The HMAC key is ruled separately by COMP-064. | The vectors are interoperable evidence. Test exact ciphertext, plaintext, HMAC, wrong counterparty/protocol/key ID, tag tampering, and IV/tag truncation. | +| COMP-002 | BRC-2 prose describes a shared-secret hash input that disagrees with the published vectors and Go. | Follow the published vectors and Go v1.3.3 padded-x-coordinate derivation for the AES-GCM key. Mark the prose conflict and do not offer a second silent variant. The HMAC key is ruled separately by COMP-065. | The vectors are interoperable evidence. Test exact ciphertext, plaintext, HMAC, wrong counterparty/protocol/key ID, tag tampering, and IV/tag truncation. | | COMP-003 | BRC-30 says four-byte source satoshis; Go and Bitcoin amounts use eight bytes. | Parse and emit unsigned 64-bit little-endian source amounts. Do not emit the ambiguous four-byte form. | Matches Go Extended Format and the transaction amount domain. Test Go↔Swift bytes and overflow/truncation. | | COMP-004 | BRC-43 gives 280/1033 limits; BRC-100 and Go use 400/800. Go's Unicode-aware trimming and lowercasing can also admit names outside a stable ASCII derivation profile. BRC-44 reserves `admin` protocols for trusted wallet internals. | Use protocol names of 5…400 UTF-8 bytes and key IDs of 1…800 UTF-8 bytes. Protocol names trim ASCII whitespace, lowercase ASCII, allow only letters, digits, and single spaces, reject the `admin` prefix and ` protocol` suffix, and do not normalize key IDs. The one wallet-internal WPM metadata identifier is available only as the explicit `WalletProtocolID.walletMetadataEncryption` constant; generic construction and application JSON/wire encoding and decoding continue to reject it. | Newer wallet limits and the parity baseline agree. The stricter Swift identifier policy fails closed rather than deriving a different key from Unicode or reserved-name artifacts. The named constant makes the wallet-internal exception auditable without widening external encoders or decoders. Tests cover byte boundaries, every ASCII character, Unicode rejection, reserved names, exact local fields and ProtoWallet output, boundary rejection, and distinct composed/decomposed key IDs. | | COMP-005 | BRC-48 specifies lock-after PushDrop; Go creates both but decodes only lock-before. | Decode and construct spec-conformant lock-after. Support lock-before through an explicitly named compatibility mode. | Achieves BRC conformance without losing Go ecosystem inputs. Test that no auto-detection ambiguity changes pushed data. | @@ -71,7 +71,7 @@ behind the general rule. | COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It authenticates the signed six-field TypeScript advertisement, binds it to the requested hash, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the TypeScript `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | -| COMP-064 | BRC-56 HMAC key: COMP-002 used the 32-byte padded X coordinate (Go v1.3.3); `@bsv/sdk` 4.1.1 and earlier TypeScript SDKs use the minimal-length X coordinate and reject padded-key tags. | `createHMAC` uses the minimal-length key. `verifyHMAC` accepts the minimal or the 32-byte padded key. AES-GCM keeps the 32-byte key. | TypeScript wallets and apps are the 1Sat wallet's peers; tags must verify both ways. Accepting padded tags keeps earlier Swift and Go tags valid. Tests use the six TypeScript BRC-56 vectors. See [COMP-064](Rulings/COMP-064-Wallet-HMAC-Key.md). | +| COMP-065 | BRC-56 HMAC key: COMP-002 used the 32-byte padded X coordinate (Go v1.3.3); `@bsv/sdk` 4.1.1 and earlier TypeScript SDKs use the minimal-length X coordinate and reject padded-key tags. | `createHMAC` uses the minimal-length key. `verifyHMAC` accepts the minimal or the 32-byte padded key. AES-GCM keeps the 32-byte key. | TypeScript wallets and apps are the 1Sat wallet's peers; tags must verify both ways. Accepting padded tags keeps earlier Swift and Go tags valid. Tests use the six TypeScript BRC-56 vectors. See [COMP-065](Rulings/COMP-065-Wallet-HMAC-Key.md). | ## Scope decisions diff --git a/Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md b/Documentation/Compatibility/Rulings/COMP-065-Wallet-HMAC-Key.md similarity index 98% rename from Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md rename to Documentation/Compatibility/Rulings/COMP-065-Wallet-HMAC-Key.md index db130c7..eb753a2 100644 --- a/Documentation/Compatibility/Rulings/COMP-064-Wallet-HMAC-Key.md +++ b/Documentation/Compatibility/Rulings/COMP-065-Wallet-HMAC-Key.md @@ -1,4 +1,4 @@ -# COMP-064: Wallet HMAC key length +# COMP-065: Wallet HMAC key length Status: Accepted. Replaces the HMAC part of COMP-002. diff --git a/Tests/BSVWalletTests/ProtoWalletTests.swift b/Tests/BSVWalletTests/ProtoWalletTests.swift index 763b35d..5fca0ed 100644 --- a/Tests/BSVWalletTests/ProtoWalletTests.swift +++ b/Tests/BSVWalletTests/ProtoWalletTests.swift @@ -449,7 +449,7 @@ final class ProtoWalletTests: XCTestCase { /// BRC-56 HMAC key vectors from `@bsv/sdk` 4.1.1 /// (packages/sdk/src/wallet/__tests/ProtoWallet.brc56-hmac-key.test.ts:9-70). - /// Tags use the minimal-length X coordinate as the HMAC key (W1, COMP-064). + /// Tags use the minimal-length X coordinate as the HMAC key (W1, COMP-065). /// TypeScript rejects `rejectedTag` (made with the zero-padded 32-byte key); /// Swift still accepts it so tags Swift and Go peers made before the switch /// keep verifying. From 8fe5b1a16d3e45577fe286a9d7f49c6be25bf03e Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 19:31:27 +0000 Subject: [PATCH 7/8] Read certificate fields in any order @bsv/sdk 4.1.1 writes certificate fields sorted with localeCompare (auth/certificates/Certificate.ts:290), so cardholder comes before cardNumber. The decoder rejected that as out of order, which lost whole acquireCertificate, listCertificates and discovery results from TS wallets. It now reads any order and still rejects a repeated name. Swift keeps writing byte order. --- .../Certificates/CertificateBinary.swift | 16 +++++++++------- .../BRC52CertificateBinaryTests.swift | 11 +++++++++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/Sources/BSVWallet/Certificates/CertificateBinary.swift b/Sources/BSVWallet/Certificates/CertificateBinary.swift index e18e1a0..bc40b93 100644 --- a/Sources/BSVWallet/Certificates/CertificateBinary.swift +++ b/Sources/BSVWallet/Certificates/CertificateBinary.swift @@ -63,9 +63,14 @@ extension Certificate { /// 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. + /// /// Unlike the pinned Go decoder, this rejects nonminimal CompactSize values, - /// unsorted fields, duplicate names, high-width vouts, noncanonical Base64, - /// noncanonical DER, and DER trailing bytes. + /// duplicate names, high-width vouts, noncanonical Base64, noncanonical DER, + /// and DER trailing bytes. public init(binary bytes: [UInt8], limits: CertificateLimits = .standard) throws { guard bytes.count <= limits.maximumBinaryByteCount else { throw CertificateError.certificateTooLarge(actual: bytes.count, maximum: limits.maximumBinaryByteCount) @@ -85,7 +90,7 @@ extension Certificate { throw CertificateError.tooManyFields(actual: Int(clamping: fieldCount), maximum: limits.maximumFieldCount) } var fields: [CertificateFieldName: CertificateCiphertext] = [:] - var previous: [UInt8]? + var seenNames = Set<[UInt8]>() for _ in 0.. Date: Mon, 16 Nov 2026 19:31:27 +0000 Subject: [PATCH 8/8] Follow @bsv/sdk 4.1.1 on page limits, options and error text - Accept createAction noSendChange without noSend, as TS does. - Keep ABI and certificate errors as they are, so the error frame says which value was wrong instead of "unsupported wallet action value". - Log processor decode and encode failures with full detail (dev.opl.swift-sdk, BSVWallet) and send the peer a fixed short text for errors the codecs do not describe. - Refuse list and discovery results longer than the request's limit with the TS text, and read certificate pages only up to that limit. - Store an empty certificate keyring as absent and write flag 0. - Use the TS wording for false relinquishCertificate and waitForAuthentication, page totals, non-UTF-8 originators, a bad identityKey flag and a call-29 probe with trailing data. - Keep the underlying error in resolvedCounterparty. - Add the review cases to the TS oracle and fixed vectors from it. --- Documentation/Compatibility/GoSDK-v1.3.3.md | 5 +- Documentation/Compatibility/Rulings.md | 2 +- .../COMP-045-Wallet-Wire-Strictness.md | 12 + .../Rulings/COMP-046-Wallet-Wire-Actions.md | 14 +- .../COMP-048-Wallet-Wire-Certificates.md | 26 +- Sources/BSVWallet/ABI/WalletActionABI.swift | 5 +- .../BSVWallet/ABI/WalletCertificateABI.swift | 13 +- .../BSVWallet/Crypto/WalletKeyDeriver.swift | 7 +- Sources/BSVWallet/Substrates/WalletLog.swift | 31 ++ .../Substrates/WalletWireProcessor.swift | 5 + .../Substrates/WalletWireTransceiver.swift | 1 + .../Wire/WalletWireActionPrimitives.swift | 14 +- .../Wire/WalletWireActionResultCodec.swift | 74 +++- .../WalletWireCertificatePrimitives.swift | 23 +- .../WalletWireCertificateResultCodec.swift | 80 +++-- Sources/BSVWallet/Wire/WalletWireCodec.swift | 9 +- .../BSVWallet/Wire/WalletWireFailures.swift | 132 ++++++- .../Wire/WalletWireAdversarialTests.swift | 11 +- ...alletWireCertificateAdversarialTests.swift | 47 ++- .../Wire/WalletWireReviewVectorTests.swift | 325 ++++++++++++++++++ .../WalletWireTypeScriptOracleTests.swift | 10 + Tools/Conformance/TSOracle/gen.ts | 172 +++++++++ 22 files changed, 910 insertions(+), 108 deletions(-) create mode 100644 Sources/BSVWallet/Substrates/WalletLog.swift create mode 100644 Tests/BSVWalletTests/Wire/WalletWireReviewVectorTests.swift diff --git a/Documentation/Compatibility/GoSDK-v1.3.3.md b/Documentation/Compatibility/GoSDK-v1.3.3.md index 548be27..81dac64 100644 --- a/Documentation/Compatibility/GoSDK-v1.3.3.md +++ b/Documentation/Compatibility/GoSDK-v1.3.3.md @@ -478,7 +478,10 @@ Certificate wire codecs follow COMP-048. They use the existing strict BRC-52 binary codec, display-order revocation transaction IDs, low-S DER, bounded 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. A present empty keyring is rejected. +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. 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 b1f3cd9..d7b9f6f 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, while the binary certificate orders field names by raw UTF-8 bytes. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, raw UTF-8 field-name order, and explicit size limits. 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. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, field order, signature binding, field encryption, verifier projection, all-or-nothing failure, and secret redaction. | +| 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, while the binary certificate orders field names by raw UTF-8 bytes. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, raw UTF-8 field-name order when writing (any order with no repeated name when reading, because TypeScript writes `localeCompare` order; COMP-048), and explicit size limits. 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. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, field order, signature binding, field encryption, verifier projection, all-or-nothing failure, and secret redaction. | | 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 0245b9a..06a3196 100644 --- a/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md +++ b/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md @@ -31,9 +31,21 @@ Encoding follows the TypeScript writers in - A false `verifyHMAC` or `verifySignature` result is the error frame TypeScript sends: code 1 with `HMAC is not valid` or `Signature is not valid`. +- A false `waitForAuthentication` result is code 1 with `Wallet did not + affirmatively authenticate` (`WalletWireProcessor.ts:1683`). - Error frames carry a code from 1 to 8. Any other code is sent as 1. The message is cut to 4,096 UTF-8 bytes on a character boundary, and the stack is empty. The standard remote message limit is 4,096 bytes. +- Error text follows TypeScript where peers see it: an originator that is not + UTF-8 is `The encoded data was not valid for encoding utf-8` (a fatal + `TextDecoder`, `primitives/utils.ts:237`), and a bad getPublicKey + `identityKey` byte is `Invalid identityKey flag: expected 0 or 1, received N` + (`WalletWireProcessor.ts:49`). Other request failures name the field and the + reason, for example `Invalid Wallet Wire createAction request: `. +- 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`). Swift keeps these bounds: canonical CompactSize, explicit frame, payload, text, originator and error limits, checked UInt32 values, low-S DER diff --git a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md index a27c172..835911a 100644 --- a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md +++ b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md @@ -25,9 +25,17 @@ balances must cross the wire between Swift and TypeScript in both directions. broadcast`. The transceiver reads code 8 as `aborted: false`. - **List totals.** `totalActions` and `totalOutputs` count every match. The page follows the total with no record count and ends at the end of the - frame. A page may be shorter than its total. Swift rejects a page with more - records than its total, or more records than the request's limit (BRC-100 - default 10). + frame. A page may be shorter than its total. A Swift processor checks a + wallet's page in TypeScript order and with its text: more records than the + total (`Invalid listOutputs result totalOutputs: expected at least N`), more + than the request's limit, BRC-100 default 10 (`... expected at most the + requested limit of N`, `wallet/WalletResultValidation.ts:1932-1951`), then a + total above UInt32 (`Invalid listOutputs result total: expected an integer + from 0 to 4294967295, received N`, `WalletWireProcessor.ts:178-191`). A + transceiver stops reading at the request's limit. +- **createAction options.** `noSendChange` is accepted with or without + `noSend`, as TypeScript validates and reads it + (`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. diff --git a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md index 5de6b74..1dc333a 100644 --- a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md +++ b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md @@ -13,20 +13,36 @@ certificate frames must be read and answered without rejection. - **Map order.** TypeScript writes keyrings, fields and attributes in object insertion order. Swift reads maps in any order and rejects only a repeated name. Swift writes maps sorted by raw UTF-8 bytes, which TypeScript accepts. +- **Certificate field order.** TypeScript writes the fields inside certificate + binary sorted with `localeCompare` (`auth/certificates/Certificate.ts:290`), + 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. - **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, and never longer than the - request's limit. + shorter than its total but never longer. A processor refuses a page longer + than the request's limit with the TypeScript text (`Invalid listCertificates + result certificates: expected at most the requested limit of N`, + `wallet/WalletResultValidation.ts:1948`); a transceiver stops reading at the + request's limit, 10 when it gives none (`WalletWireTransceiver.ts:2097-2102`). - **listCertificates verifier.** The wire carries the 33 compressed key bytes, or length 0 when absent. The ABI and JSON keep the hex text. Any other length is refused. - **Keyring presence.** `nil` is `00`; a nonempty map is `01` and the map. - TypeScript writes an empty keyring as `00` and returns `{}` for it, so JSON - `keyring: {}` reads as no keyring. + TypeScript writes an empty keyring as `00` (`WalletWireProcessor.ts:2118`) + and reads `01` with no entries as `{}`. Swift stores an empty keyring as no + keyring, from the ABI, from JSON `keyring: {}` and from the wire. +- **False relinquish.** `relinquished: false` is code 1 `The wallet did not + relinquish the certificate` (`WalletWireProcessor.ts:2293`). - **Call 29.** TypeScript 4.x probes call 29 (certificate compatibility profile) before discovery and some list, prove and relinquish calls. A Swift processor answers code 1 `Invalid call code: 29`, the exact answer on which - the TypeScript transceiver falls back to the plain calls. The full profile + the TypeScript transceiver falls back to the plain calls. A probe with + trailing bytes gets the TypeScript text `Wallet Wire certificate + compatibility probe request contains trailing data`. The full profile is not implemented: it exists to carry certificate types other than 32 bytes, which Swift `CertificateTypeID` cannot represent. diff --git a/Sources/BSVWallet/ABI/WalletActionABI.swift b/Sources/BSVWallet/ABI/WalletActionABI.swift index df66bf9..b885776 100644 --- a/Sources/BSVWallet/ABI/WalletActionABI.swift +++ b/Sources/BSVWallet/ABI/WalletActionABI.swift @@ -162,12 +162,11 @@ public struct WalletCreateActionOptions: Equatable, Sendable { ) } if let noSendChange { + // TS 4.1.1 takes noSendChange whatever noSend says (validationHelpers.ts:680, + // WalletWireProcessor.ts:539-556), and its clients send it that way. try walletABIRequireCount( noSendChange.count, kind: "no-send change", maximum: limits.maximumCollectionCount ) - guard noSend == true else { - throw WalletABIError.invalidFieldRelation("noSendChange requires noSend to be true") - } } if let sendWith { try walletABIRequireCount( diff --git a/Sources/BSVWallet/ABI/WalletCertificateABI.swift b/Sources/BSVWallet/ABI/WalletCertificateABI.swift index c660385..6cde7c3 100644 --- a/Sources/BSVWallet/ABI/WalletCertificateABI.swift +++ b/Sources/BSVWallet/ABI/WalletCertificateABI.swift @@ -257,9 +257,10 @@ public struct WalletListCertificatesRequest: Equatable, Sendable { public struct WalletCertificateResult: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public let certificate: Certificate - /// `nil` means that the wallet did not return a keyring. A present keyring - /// must contain at least one entry because the pinned Go reader cannot - /// preserve the distinction between an empty map and an absent map. + /// `nil` means that the wallet did not return a keyring. An empty keyring is + /// stored as `nil`: `@bsv/sdk` 4.1.1 writes flag 0 for it + /// (wallet/substrates/WalletWireProcessor.ts:2118), and the pinned Go reader + /// cannot tell an empty map from an absent one. public let keyring: [CertificateFieldName: CertificateCiphertext]? public let verifier: [UInt8] public init( @@ -268,12 +269,8 @@ public struct WalletCertificateResult: verifier: [UInt8], limits: WalletABILimits = .standard ) throws { + let keyring = keyring?.isEmpty == true ? nil : keyring if let keyring { - guard !keyring.isEmpty else { - throw WalletABIError.invalidFieldRelation( - "a present certificate keyring must not be empty" - ) - } try walletABIRequireCount( keyring.count, kind: "certificate keyring", diff --git a/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift b/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift index feb3e92..698118a 100644 --- a/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift +++ b/Sources/BSVWallet/Crypto/WalletKeyDeriver.swift @@ -154,12 +154,9 @@ public struct WalletKeyDeriver: /// The public key a counterparty stands for: the identity key for `self` /// and the public key of private key 1 for `anyone`. + /// Rethrows the underlying error unchanged, so a caller's log keeps the cause. public func resolvedCounterparty(_ counterparty: WalletCounterparty) throws -> PublicKey { - do { - return try normalizedCounterparty(counterparty) - } catch { - throw WalletCryptoError.keyDerivationFailed - } + try normalizedCounterparty(counterparty) } private func normalizedCounterparty(_ counterparty: WalletCounterparty) throws -> PublicKey { diff --git a/Sources/BSVWallet/Substrates/WalletLog.swift b/Sources/BSVWallet/Substrates/WalletLog.swift new file mode 100644 index 0000000..df30d2e --- /dev/null +++ b/Sources/BSVWallet/Substrates/WalletLog.swift @@ -0,0 +1,31 @@ +import Foundation +#if canImport(os) +import os +#endif + +/// The wallet log: subsystem `dev.opl.swift-sdk`, category `BSVWallet`. +/// +/// 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 category = "BSVWallet" + + package static func error(_ message: String) { + #if canImport(os) + Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") + #endif + } + + /// A failure answered in-band: what was being done, the call, and the underlying error. + package static func failure(_ operation: String, call: WalletCall?, underlying: any Error) { + error(line(operation, call: call, underlying: underlying)) + } + + package static func line(_ operation: String, call: WalletCall?, underlying: any Error) -> String { + let name = call?.wireMethodName ?? "unknown call" + return "\(operation) (\(name)) failed: \(type(of: underlying)): \(String(reflecting: underlying))" + } +} diff --git a/Sources/BSVWallet/Substrates/WalletWireProcessor.swift b/Sources/BSVWallet/Substrates/WalletWireProcessor.swift index 2131320..f7d7a1c 100644 --- a/Sources/BSVWallet/Substrates/WalletWireProcessor.swift +++ b/Sources/BSVWallet/Substrates/WalletWireProcessor.swift @@ -72,6 +72,7 @@ public struct WalletWireProcessor: } catch is CancellationError { throw CancellationError() } catch { + WalletLog.failure("Wallet wire request decode", call: call, underlying: error) response = try failureFrame( code: WalletWireErrorCode.unknownError, message: walletWireRequestFailureMessage(error, call: call), @@ -95,6 +96,7 @@ public struct WalletWireProcessor: // Call 29 is the @bsv/sdk 4.1 certificate compatibility profile. This // processor answers it as an older processor does, with exactly the // error a TypeScript transceiver downgrades on (see COMP-050). + try walletWireRejectCompatibilityProfile(request) let frame = try WalletWireCodec.decodeRequestFrame(request, limits: wireLimits) switch frame.call { case .createAction, .signAction, .abortAction, .listActions, @@ -199,6 +201,7 @@ public struct WalletWireProcessor: return try encodeResult(call: decoded.request.call, limits: responseLimits) { try WalletWireCodec.encodeCertificateResult( result, + request: decoded.request, certificateLimits: certificateLimits, limits: responseLimits ) @@ -251,12 +254,14 @@ public struct WalletWireProcessor: do { return try encode() } catch let rejection as WalletWireResultRejection { + WalletLog.failure("Wallet wire result", call: call, underlying: rejection) return try failureFrame( code: WalletWireErrorCode.clamped(rejection.code), message: rejection.message, limits: limits ) } catch { + WalletLog.failure("Wallet wire result encode", call: call, underlying: error) return try failureFrame( code: WalletWireErrorCode.unknownError, message: walletWireResultFailureMessage(error, call: call), diff --git a/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift b/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift index 32a064c..8bd28b4 100644 --- a/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift +++ b/Sources/BSVWallet/Substrates/WalletWireTransceiver.swift @@ -334,6 +334,7 @@ public struct WalletWireTransceiver: return try WalletWireCodec.decodeCertificateResult( response, expectedCall: request.call, + request: request, certificateLimits: certificateLimits, limits: wireLimits ) diff --git a/Sources/BSVWallet/Wire/WalletWireActionPrimitives.swift b/Sources/BSVWallet/Wire/WalletWireActionPrimitives.swift index 46df12c..f655fc5 100644 --- a/Sources/BSVWallet/Wire/WalletWireActionPrimitives.swift +++ b/Sources/BSVWallet/Wire/WalletWireActionPrimitives.swift @@ -38,18 +38,20 @@ func walletWireRequireActionBytes( } } -func walletWireMapABIError(_ error: WalletABIError) -> WalletWireError { +/// Maps size failures to wire limits and keeps every other ABI error as it is, so +/// the error frame and the log both say which value was wrong. +func walletWireMapABIError(_ error: WalletABIError) -> any Error { switch error { case .countLimitExceeded(let kind, let actual, let maximum): - return .countLimitExceeded(kind: kind, actual: UInt64(max(0, actual)), maximum: maximum) + return WalletWireError.countLimitExceeded(kind: kind, actual: UInt64(max(0, actual)), maximum: maximum) case .byteLimitExceeded(let kind, let actual, let maximum): - return .byteLimitExceeded(kind: kind, actual: actual, maximum: maximum) + return WalletWireError.byteLimitExceeded(kind: kind, actual: actual, maximum: maximum) case .aggregatePayloadTooLarge(let actual, let maximum): - return .byteLimitExceeded(kind: "aggregate wallet payload", actual: actual, maximum: maximum) + return WalletWireError.byteLimitExceeded(kind: "aggregate wallet payload", actual: actual, maximum: maximum) case .sizeOverflow: - return .byteLimitExceeded(kind: "aggregate wallet payload", actual: Int.max, maximum: Int.max) + return WalletWireError.byteLimitExceeded(kind: "aggregate wallet payload", actual: Int.max, maximum: Int.max) default: - return .nonRoundTrippableValue(kind: "wallet action value") + return error } } diff --git a/Sources/BSVWallet/Wire/WalletWireActionResultCodec.swift b/Sources/BSVWallet/Wire/WalletWireActionResultCodec.swift index 5309d1c..2395fdc 100644 --- a/Sources/BSVWallet/Wire/WalletWireActionResultCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireActionResultCodec.swift @@ -45,8 +45,14 @@ extension WalletWireCodec { ) } case .listActions(let value): - try walletWireRequirePage( - records: value.actions.count, total: UInt64(value.totalActions), call: "listActions" + try walletWireRequireResultPage( + records: value.actions.count, + total: UInt64(value.totalActions), + limit: walletWireRequestedPageLimit(request), + call: "listActions", + totalField: "totalActions", + entriesField: "actions", + resultName: "listActions result" ) writer.writeCompactSize(UInt64(value.totalActions)) for action in value.actions { @@ -79,8 +85,14 @@ extension WalletWireCodec { if balance { try walletWireRequireBalanceResult(value) } else { - try walletWireRequirePage( - records: value.outputs.count, total: value.totalOutputs, call: "listOutputs" + try walletWireRequireResultPage( + records: value.outputs.count, + total: value.totalOutputs, + limit: walletWireRequestedPageLimit(request), + call: "listOutputs", + totalField: "totalOutputs", + entriesField: "outputs", + resultName: "listOutputs result" ) } let spendable = listOutputsEncoding == .spendable @@ -225,7 +237,7 @@ extension WalletWireCodec { limits: limits.abiLimits )) } - try walletWireRequirePage(records: actions.count, total: totalRaw, call: "listActions") + try walletWireRequireResponsePage(records: actions.count, total: totalRaw, call: "listActions") value = .listActions(try WalletListActionsResult( totalActions: total, actions: actions, limits: limits.abiLimits )) @@ -295,7 +307,7 @@ extension WalletWireCodec { if balance { try walletWireRequireBalanceResult(result) } else { - try walletWireRequirePage(records: outputs.count, total: total, call: "listOutputs") + try walletWireRequireResponsePage(records: outputs.count, total: total, call: "listOutputs") } value = .listOutputs(result) case .relinquishOutput: @@ -309,6 +321,15 @@ extension WalletWireCodec { } } +/// The page size a list request asks for, or nil when there is no request to check against. +func walletWireRequestedPageLimit(_ request: WalletWireActionRequest?) -> Int? { + switch request { + case .listActions(let value)?: Int(value.pagination.effectiveLimit) + case .listOutputs(let value)?: Int(value.pagination.effectiveLimit) + default: nil + } +} + /// The page size a list request allows: its limit, or the BRC-100 default of 10. func walletWirePageLimit(_ request: WalletWireActionRequest?) -> Int { switch request { @@ -326,16 +347,49 @@ func walletWireRequirePageCapacity(_ returned: Int, limit: Int, call: String) th } } -/// A page may be shorter than its total: the total counts every matching record. -func walletWireRequirePage(records: Int, total: UInt64, call: String) throws { +/// Checks a wallet's list result before a processor writes it, in `@bsv/sdk` 4.1.1 order: +/// the result checks (`wallet/WalletResultValidation.ts:1932-1951`), then the wire total +/// (`wallet/substrates/WalletWireProcessor.ts:178-191`). A page may be shorter than its +/// total, because the total counts every matching record, but never longer than the +/// request's limit (10 when the request gives none). +func walletWireRequireResultPage( + records: Int, + total: UInt64, + limit: Int?, + call: String, + totalField: String, + entriesField: String, + resultName: String +) throws { + let maximumSafeInteger: UInt64 = 9_007_199_254_740_991 + guard total <= maximumSafeInteger else { + throw WalletWireResultRejection( + message: "Invalid \(call) result \(totalField): expected an integer from 0 to \(maximumSafeInteger)" + ) + } + guard UInt64(records) <= total else { + throw WalletWireResultRejection( + message: "Invalid \(call) result \(totalField): expected at least \(records)" + ) + } + if let limit, records > limit { + throw WalletWireResultRejection( + message: "Invalid \(call) result \(entriesField): expected at most the requested limit of \(limit)" + ) + } guard total <= UInt64(UInt32.max) else { throw WalletWireResultRejection( - message: "Invalid \(call) result: total \(total) does not fit in 32 bits" + message: "Invalid \(resultName) total: expected an integer from 0 to \(UInt32.max), received \(total)" ) } +} + +/// A page read from a peer may be shorter than its total, never longer +/// (`wallet/substrates/WalletWireTransceiver.ts:2088-2094`). +func walletWireRequireResponsePage(records: Int, total: UInt64, call: String) throws { guard UInt64(records) <= total else { throw WalletWireResultRejection( - message: "Invalid \(call) result: returned \(records) records but declared a total of \(total)" + message: "Wallet Wire \(call) response returned \(records) records but declared a total of \(total)" ) } } diff --git a/Sources/BSVWallet/Wire/WalletWireCertificatePrimitives.swift b/Sources/BSVWallet/Wire/WalletWireCertificatePrimitives.swift index df8d236..7cad2f9 100644 --- a/Sources/BSVWallet/Wire/WalletWireCertificatePrimitives.swift +++ b/Sources/BSVWallet/Wire/WalletWireCertificatePrimitives.swift @@ -246,14 +246,13 @@ private func walletWireRequireStrictMapOrder( } } -func walletWireMapCertificateError(_ error: Error) -> WalletWireError { - if let wire = error as? WalletWireError { return wire } - guard let certificate = error as? CertificateError else { - return .nonRoundTrippableValue(kind: "certificate value") - } +/// Maps certificate size and encoding failures to wire errors and keeps every other +/// error as it is, so the error frame and the log both say what was wrong. +func walletWireMapCertificateError(_ error: Error) -> any Error { + guard let certificate = error as? CertificateError else { return error } switch certificate { case .tooManyFields(let actual, let maximum): - return .countLimitExceeded( + return WalletWireError.countLimitExceeded( kind: "certificate fields", actual: UInt64(max(0, actual)), maximum: maximum @@ -262,20 +261,20 @@ func walletWireMapCertificateError(_ error: Error) -> WalletWireError { .fieldValueTooLarge(let actual, let maximum), .keyringValueTooLarge(let actual, let maximum), .certificateTooLarge(let actual, let maximum): - return .byteLimitExceeded( + return WalletWireError.byteLimitExceeded( kind: "certificate value", actual: actual, maximum: maximum ) case .nonCanonicalCompactSize: - return .noncanonicalCompactSize + return WalletWireError.noncanonicalCompactSize case .truncatedCertificate: - return .truncated + return WalletWireError.truncated case .invalidPublicKey: - return .invalidPublicKey + return WalletWireError.invalidPublicKey case .invalidSignature: - return .invalidSignature + return WalletWireError.invalidSignature default: - return .nonRoundTrippableValue(kind: "certificate value") + return certificate } } diff --git a/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift b/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift index 6233a6a..1659c20 100644 --- a/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireCertificateResultCodec.swift @@ -2,14 +2,18 @@ import BSVCore import BSVKeys extension WalletWireCodec { + /// Encodes a certificate result. Given the `request` it answers, a list or discovery + /// result may hold no more records than the request's limit, as `@bsv/sdk` 4.1.1 checks. public static func encodeCertificateResult( _ result: WalletWireCertificateResult, + request: WalletWireCertificateRequest? = nil, certificateLimits: CertificateLimits = .standard, limits: WalletWireLimits = .standard ) throws -> [UInt8] { do { let payload = try encodeCertificateResultPayload( result, + requestedLimit: walletWireRequestedPageLimit(request), certificateLimits: certificateLimits, limits: limits ) @@ -25,9 +29,12 @@ extension WalletWireCodec { } } + /// Decodes a certificate result. Given the `request` it answers, a list or discovery + /// page is read up to the request's limit (10 when it gives none), as `@bsv/sdk` 4.1.1 does. public static func decodeCertificateResult( _ bytes: [UInt8], expectedCall: WalletCall, + request: WalletWireCertificateRequest? = nil, certificateLimits: CertificateLimits = .standard, limits: WalletWireLimits = .standard ) throws -> WalletWireCertificateResult { @@ -39,6 +46,7 @@ extension WalletWireCodec { return try decodeCertificateResultPayload( payload, call: expectedCall, + requestedLimit: walletWireRequestedPageLimit(request), certificateLimits: certificateLimits, limits: limits ) @@ -56,6 +64,7 @@ extension WalletWireCodec { private static func encodeCertificateResultPayload( _ result: WalletWireCertificateResult, + requestedLimit: Int?, certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws -> [UInt8] { @@ -121,10 +130,14 @@ extension WalletWireCodec { limits: nestedLimits )) case .listCertificates(let value): - try walletWireRequirePage( + try walletWireRequireResultPage( records: value.certificates.count, total: UInt64(value.totalCertificates), - call: "listCertificates" + limit: requestedLimit, + call: "listCertificates", + totalField: "totalCertificates", + entriesField: "certificates", + resultName: "listCertificates result" ) guard value.certificates.count <= limits.abiLimits.maximumCollectionCount else { throw WalletWireError.countLimitExceeded( @@ -149,12 +162,9 @@ extension WalletWireCodec { includingSignature: true, limits: nestedLimits )) - if let keyring = item.keyring { - guard !keyring.isEmpty else { - throw WalletWireError.nonRoundTrippableValue( - kind: "empty present certificate keyring" - ) - } + // TS writes flag 0 for an absent or empty keyring + // (wallet/substrates/WalletWireProcessor.ts:2118). + if let keyring = item.keyring, !keyring.isEmpty { writer.writeByte(1) try walletWireWriteKeyring( keyring, @@ -178,13 +188,14 @@ extension WalletWireCodec { ) case .relinquishCertificate(let value): guard value.relinquished else { - throw WalletWireError.nonRoundTrippableValue( - kind: "false relinquish-certificate result" - ) + // wallet/substrates/WalletWireProcessor.ts:2293 + throw WalletWireResultRejection(message: WalletWireFailureText.notRelinquishedCertificate) } case .discoverByIdentityKey(let value), .discoverByAttributes(let value): try encodeDiscoveryResult( value, + call: result.call, + requestedLimit: requestedLimit, to: &writer, certificateLimits: certificateLimits, limits: limits @@ -197,6 +208,7 @@ extension WalletWireCodec { private static func decodeCertificateResultPayload( _ bytes: [UInt8], call: WalletCall, + requestedLimit: Int?, certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws -> WalletWireCertificateResult { @@ -278,6 +290,7 @@ extension WalletWireCodec { case .listCertificates: result = .listCertificates(try decodeListCertificatesResult( from: &reader, + requestedLimit: requestedLimit, certificateLimits: certificateLimits, limits: limits )) @@ -299,12 +312,14 @@ extension WalletWireCodec { case .discoverByIdentityKey: result = .discoverByIdentityKey(try decodeDiscoveryResult( from: &reader, + requestedLimit: requestedLimit, certificateLimits: certificateLimits, limits: limits )) case .discoverByAttributes: result = .discoverByAttributes(try decodeDiscoveryResult( from: &reader, + requestedLimit: requestedLimit, certificateLimits: certificateLimits, limits: limits )) @@ -319,6 +334,7 @@ extension WalletWireCodec { private extension WalletWireCodec { static func decodeListCertificatesResult( from reader: inout WalletWireReader, + requestedLimit: Int?, certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws -> WalletListCertificatesResult { @@ -329,7 +345,7 @@ private extension WalletWireCodec { while !reader.isAtEnd { try walletWireRequirePageCapacity( certificates.count, - limit: limits.abiLimits.maximumCollectionCount, + limit: requestedLimit ?? limits.abiLimits.maximumCollectionCount, call: "listCertificates" ) let certificateBytes = try reader.readVarBytes( @@ -343,18 +359,13 @@ private extension WalletWireCodec { case 0: keyring = nil case 1: - let decoded = try walletWireReadKeyring( + // TS reads flag 1 with no entries as an empty keyring; it is stored as nil. + keyring = try walletWireReadKeyring( from: &reader, kind: "certificate keyring", certificateLimits: certificateLimits, limits: limits ) - guard !decoded.isEmpty else { - throw WalletWireError.nonRoundTrippableValue( - kind: "empty present certificate keyring" - ) - } - keyring = decoded case let flag: throw WalletWireError.invalidDiscriminator( kind: "certificate keyring presence", @@ -369,7 +380,7 @@ private extension WalletWireCodec { limits: limits.abiLimits )) } - try walletWireRequirePage( + try walletWireRequireResponsePage( records: certificates.count, total: totalRaw, call: "listCertificates" ) return try WalletListCertificatesResult( @@ -381,14 +392,20 @@ private extension WalletWireCodec { static func encodeDiscoveryResult( _ value: WalletDiscoverCertificatesResult, + call: WalletCall, + requestedLimit: Int?, to writer: inout WalletWireWriter, certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws { - try walletWireRequirePage( + try walletWireRequireResultPage( records: value.certificates.count, total: UInt64(value.totalCertificates), - call: "discoverCertificates" + limit: requestedLimit, + call: call.wireMethodName, + totalField: "totalCertificates", + entriesField: "certificates", + resultName: "discovery result" ) guard value.certificates.count <= limits.abiLimits.maximumCollectionCount else { throw WalletWireError.countLimitExceeded( @@ -410,6 +427,7 @@ private extension WalletWireCodec { static func decodeDiscoveryResult( from reader: inout WalletWireReader, + requestedLimit: Int?, certificateLimits: CertificateLimits, limits: WalletWireLimits ) throws -> WalletDiscoverCertificatesResult { @@ -419,8 +437,8 @@ private extension WalletWireCodec { while !reader.isAtEnd { try walletWireRequirePageCapacity( certificates.count, - limit: limits.abiLimits.maximumCollectionCount, - call: "discoverCertificates" + limit: requestedLimit ?? limits.abiLimits.maximumCollectionCount, + call: "discover" ) certificates.append(try decodeIdentityCertificate( from: &reader, @@ -428,8 +446,8 @@ private extension WalletWireCodec { limits: limits )) } - try walletWireRequirePage( - records: certificates.count, total: totalRaw, call: "discoverCertificates" + try walletWireRequireResponsePage( + records: certificates.count, total: totalRaw, call: "discover" ) return try WalletDiscoverCertificatesResult( totalCertificates: total, @@ -644,3 +662,13 @@ func walletWireReadCertificateVerifier(from reader: inout WalletWireReader) thro } return Array(Hex.encode(bytes).utf8) } + +/// The page size a certificate list or discovery request asks for (10 when it gives none). +func walletWireRequestedPageLimit(_ request: WalletWireCertificateRequest?) -> Int? { + switch request { + case .listCertificates(let value)?: Int(value.pagination.effectiveLimit) + case .discoverByIdentityKey(let value)?: Int(value.pagination.effectiveLimit) + case .discoverByAttributes(let value)?: Int(value.pagination.effectiveLimit) + default: nil + } +} diff --git a/Sources/BSVWallet/Wire/WalletWireCodec.swift b/Sources/BSVWallet/Wire/WalletWireCodec.swift index 919f509..d64ad6a 100644 --- a/Sources/BSVWallet/Wire/WalletWireCodec.swift +++ b/Sources/BSVWallet/Wire/WalletWireCodec.swift @@ -208,9 +208,10 @@ public enum WalletWireCodec { ) } - /// Encodes a key or query result frame. A false verification result is the - /// error frame `@bsv/sdk` 4.1.1 sends: code 1, "HMAC is not valid" or - /// "Signature is not valid". + /// Encodes a key or query result frame. A false verification or + /// waitForAuthentication result is the error frame `@bsv/sdk` 4.1.1 sends: + /// code 1, "HMAC is not valid", "Signature is not valid" or "Wallet did not + /// affirmatively authenticate" (WalletWireProcessor.ts:1683). public static func encodeKeyQueryResult( _ result: WalletWireKeyQueryResult, limits: WalletWireLimits = .standard @@ -220,6 +221,8 @@ public enum WalletWireCodec { case .verifyHMAC(let value) where !value.valid: refusal = WalletWireFailureText.invalidHMAC case .verifySignature(let value) where !value.valid: refusal = WalletWireFailureText.invalidSignature + case .waitForAuthentication(let value) where !value.authenticated: + refusal = WalletWireFailureText.notAuthenticated default: refusal = nil } if let refusal { diff --git a/Sources/BSVWallet/Wire/WalletWireFailures.swift b/Sources/BSVWallet/Wire/WalletWireFailures.swift index 250e00e..e5abff2 100644 --- a/Sources/BSVWallet/Wire/WalletWireFailures.swift +++ b/Sources/BSVWallet/Wire/WalletWireFailures.swift @@ -50,12 +50,25 @@ enum WalletWireFailureText { "The wallet refused to abort this action because it has already been broadcast" static let invalidHMAC = "HMAC is not valid" static let invalidSignature = "Signature is not valid" + static let notAuthenticated = "Wallet did not affirmatively authenticate" + static let notRelinquishedCertificate = "The wallet did not relinquish the certificate" + static let probeTrailingData = + "Wallet Wire certificate compatibility probe request contains trailing data" static let unspendableLegacyOutputs = "Non-spendable listOutputs records require the spendable encoding extension or JSON" static let readerExhausted = "ReaderUint8Array read exceeds available data" static func invalidCall(_ code: UInt8) -> String { "Invalid call code: \(code)" } + /// What a strict UTF-8 decode throws in `@bsv/sdk` (`primitives/utils.ts:237`, + /// a fatal `TextDecoder`), as Bun and Node word it. + static let invalidUTF8 = "The encoded data was not valid for encoding utf-8" + + /// `wallet/substrates/WalletWireProcessor.ts:49`. + static func invalidBooleanFlag(_ field: String, _ flag: UInt8) -> String { + "Invalid \(field) flag: expected 0 or 1, received \(flag)" + } + static func trailingData(_ callName: String) -> String { "Wallet Wire \(callName) request contains trailing data" } @@ -92,6 +105,10 @@ extension WalletWireError { } /// The message a processor sends when a request frame cannot be decoded. +/// +/// Wallet wire, ABI and certificate errors get a short, specific phrase. Any other +/// error gets a fixed text, so type and case names never reach the peer; the +/// processor logs the full error locally. func walletWireRequestFailureMessage(_ error: any Error, call: WalletCall?) -> String { let name = call?.wireMethodName if let wire = error as? WalletWireError { @@ -100,20 +117,127 @@ func walletWireRequestFailureMessage(_ error: any Error, call: WalletCall?) -> S return wire.shortMessage case .trailingBytes: return WalletWireFailureText.trailingData(name ?? "request") + case .invalidUTF8: + return WalletWireFailureText.invalidUTF8 + case .invalidDiscriminator(kind: "identity key", let flag): + return WalletWireFailureText.invalidBooleanFlag("identityKey", flag) default: return "Invalid Wallet Wire \(name ?? "") request: \(wire.shortMessage)" } } if let rejection = error as? WalletWireResultRejection { return rejection.message } - return "Invalid Wallet Wire \(name ?? "") request: \(error)" + if let reason = walletWireShortReason(error) { + return "Invalid Wallet Wire \(name ?? "") request: \(reason)" + } + return "Invalid Wallet Wire \(name ?? "") request" } /// The message a processor sends when a wallet result cannot be encoded. func walletWireResultFailureMessage(_ error: any Error, call: WalletCall) -> String { - if let wire = error as? WalletWireError { - return "Invalid \(call.wireMethodName) result: \(wire.shortMessage)" + if let reason = walletWireShortReason(error) { + return "Invalid \(call.wireMethodName) result: \(reason)" + } + return "Invalid \(call.wireMethodName) result" +} + +/// A short phrase for the errors whose cases name a value, never a payload. +func walletWireShortReason(_ error: any Error) -> String? { + if let wire = error as? WalletWireError { return wire.shortMessage } + if let abi = error as? WalletABIError { return abi.shortMessage } + if let certificate = error as? CertificateError { return certificate.shortMessage } + return nil +} + +extension WalletABIError { + /// A short, specific phrase for an error frame. + var shortMessage: String { + switch self { + case .invalidLimits: "invalid wallet limits" + case .invalidEnumText(let type, let value): "\(value) is not a valid \(type)" + case .conflictingUnionMembers(let what): "conflicting values: \(what)" + case .countLimitExceeded(let kind, let actual, let maximum): + "\(kind) count \(actual) is above the limit of \(maximum)" + case .byteLimitExceeded(let kind, let actual, let maximum): + "\(kind) is \(actual) bytes, above the limit of \(maximum)" + case .aggregatePayloadTooLarge(let actual, let maximum): + "wallet payload is \(actual) bytes, above the limit of \(maximum)" + case .invalidFieldRelation(let what): what + case .invalidPaginationLimit(let limit): "page limit \(limit) is out of range" + case .invalidCanonicalBase64: "value is not canonical base64" + case .sizeOverflow: "wallet payload size overflows" + } + } +} + +extension CertificateError { + /// A short, specific phrase for an error frame. + var shortMessage: String { + switch self { + case .invalidLimits: "invalid certificate limits" + case .sizeOverflow: "certificate size overflows" + case .invalidIdentifierByteCount(let expected, let actual): + "certificate identifier is \(actual) bytes, expected \(expected)" + case .invalidCanonicalBase64: "certificate value is not canonical base64" + case .invalidPublicKey: "certificate holds an invalid public key" + case .invalidRevocationOutpoint: "certificate revocation outpoint is invalid" + case .emptyFieldName: "certificate field name is empty" + case .fieldNameTooLong(let actual, let maximum): + "certificate field name is \(actual) bytes, above the limit of \(maximum)" + case .tooManyFields(let actual, let maximum): + "certificate has \(actual) fields, above the limit of \(maximum)" + case .duplicateFieldName: "certificate repeats a field name" + case .fieldsNotInCanonicalOrder: "certificate fields are out of order" + case .fieldValueTooLarge(let actual, let maximum): + "certificate field value is \(actual) bytes, above the limit of \(maximum)" + case .keyringValueTooLarge(let actual, let maximum): + "certificate keyring value is \(actual) bytes, above the limit of \(maximum)" + case .certificateTooLarge(let actual, let maximum): + "certificate is \(actual) bytes, above the limit of \(maximum)" + case .certificateJSONTooLarge(let actual, let maximum): + "certificate JSON is \(actual) bytes, above the limit of \(maximum)" + case .truncatedCertificate: "certificate is truncated" + case .nonCanonicalCompactSize: "certificate holds a non-canonical varint" + case .invalidOutputIndex: "certificate revocation output index is invalid" + case .invalidUTF8: "certificate text is not valid UTF-8" + case .invalidSignature: "certificate signature is invalid" + case .missingSignature: "certificate is not signed" + case .alreadySigned: "certificate is already signed" + case .requirementMismatch: "certificate does not match the request" + case .signatureMismatch: "certificate signature does not match" + case .keyringMismatch: "certificate keyring does not match its fields" + case .fieldNotFound: "certificate field not found" + case .randomGenerationFailed: "random generation failed" + case .encryptionFailed: "certificate field encryption failed" + case .decryptionFailed: "certificate field decryption failed" + case .walletIdentityMismatch: "certificate subject is not this wallet" + case .invalidJSON: "certificate JSON is invalid" + } + } +} + +/// The `@bsv/sdk` 4.1 certificate compatibility call. +let walletWireCertificateCompatibilityCall: UInt8 = 29 + +/// Answers call 29 as a processor without the compatibility profile does: "Invalid call +/// code: 29", which a TypeScript transceiver downgrades on. A well-formed probe that +/// carries trailing bytes gets the text `@bsv/sdk` 4.1.1 sends for it +/// (wallet/substrates/CertificateWireCompatibility.ts:118-119). +func walletWireRejectCompatibilityProfile(_ request: [UInt8]) throws { + guard request.first == walletWireCertificateCompatibilityCall else { return } + var reader = WalletWireReader(request) + let probeHasTrailingData: Bool = { + guard (try? reader.readByte()) != nil, + let originatorCount = try? reader.readByte(), + (try? reader.readBytes(count: Int(originatorCount))) != nil, + let mode = try? reader.readByte(), + let version = try? reader.readByte(), + mode == 0, version == 1 else { return false } + return !reader.isAtEnd + }() + if probeHasTrailingData { + throw WalletWireResultRejection(message: WalletWireFailureText.probeTrailingData) } - return "Invalid \(call.wireMethodName) result: \(error)" + throw WalletWireError.invalidCall(walletWireCertificateCompatibilityCall) } /// Cuts a message to at most `maximum` UTF-8 bytes on a character boundary. diff --git a/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift b/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift index a5200cb..2e23108 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireAdversarialTests.swift @@ -135,9 +135,14 @@ final class WalletWireAdversarialTests: XCTestCase { ), [1, 22] + Array("Signature is not valid".utf8) + [0] ) - XCTAssertThrowsError(try WalletWireCodec.encodeKeyQueryResult( - .waitForAuthentication(WalletAuthenticatedResult(authenticated: false)) - )) + // WalletWireProcessor.ts:1683: a false waitForAuthentication is code 1, + // "Wallet did not affirmatively authenticate". + XCTAssertEqual( + try WalletWireCodec.encodeKeyQueryResult( + .waitForAuthentication(WalletAuthenticatedResult(authenticated: false)) + ), + [1, 41] + Array("Wallet did not affirmatively authenticate".utf8) + [0] + ) let request = WalletVerifySignatureRequest( protocolID: try walletTestProtocol("wire test"), diff --git a/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift b/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift index fcfe9de..d61563c 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireCertificateAdversarialTests.swift @@ -5,32 +5,43 @@ import Testing @Suite("Wallet-wire certificate hostile input") struct WalletWireCertificateAdversarialTests { - @Test func rejectsPresentEmptyKeyringAtABIAndWireBoundaries() throws { + /// `@bsv/sdk` 4.1.1 writes flag 0 for an empty keyring + /// (packages/sdk/src/wallet/substrates/WalletWireProcessor.ts:2118) and its + /// transceiver reads flag 1 with no entries as `{}`. Swift stores either as nil. + @Test func emptyKeyringIsStoredAsAbsentAndWrittenAsFlagZero() throws { let fixture = try WalletWireCertificateFixture() - #expect(throws: WalletABIError.invalidFieldRelation( - "a present certificate keyring must not be empty" - )) { - _ = try WalletCertificateResult( - certificate: fixture.certificate, - keyring: [:], - verifier: [] - ) - } + let empty = try WalletCertificateResult( + certificate: fixture.certificate, + keyring: [:], + verifier: [] + ) + #expect(empty.keyring == nil) + let certificateBytes = try fixture.certificate.binary(includingSignature: true) var payload = WalletWireWriter() payload.writeCompactSize(1) - try payload.writeVarBytes(fixture.certificate.binary(includingSignature: true)) + try payload.writeVarBytes(certificateBytes) payload.writeByte(1) payload.writeCompactSize(0) payload.writeCompactSize(0) - #expect(throws: WalletWireError.nonRoundTrippableValue( - kind: "empty present certificate keyring" - )) { - try WalletWireCodec.decodeCertificateResult( - [0] + payload.bytes, - expectedCall: .listCertificates - ) + let decoded = try WalletWireCodec.decodeCertificateResult( + [0] + payload.bytes, + expectedCall: .listCertificates + ) + guard case .listCertificates(let list) = decoded else { + Issue.record("expected a listCertificates result") + return } + #expect(list.certificates.first?.keyring == nil) + + var expected = WalletWireWriter() + expected.writeCompactSize(1) + try expected.writeVarBytes(certificateBytes) + expected.writeByte(0) + expected.writeCompactSize(0) + #expect(try WalletWireCodec.encodeCertificateResult( + .listCertificates(WalletListCertificatesResult(totalCertificates: 1, certificates: [empty])) + ) == [0] + expected.bytes) } @Test func rejectsNoncanonicalCountsHostileCountsAndDuplicateMapNames() throws { diff --git a/Tests/BSVWalletTests/Wire/WalletWireReviewVectorTests.swift b/Tests/BSVWalletTests/Wire/WalletWireReviewVectorTests.swift new file mode 100644 index 0000000..9418b40 --- /dev/null +++ b/Tests/BSVWalletTests/Wire/WalletWireReviewVectorTests.swift @@ -0,0 +1,325 @@ +import Foundation +import BSVCore +import BSVKeys +import BSVTransaction +@testable import BSVWallet +import Testing + +/// Frames from the live `@bsv/sdk` 4.1.1 oracle (Tools/Conformance/TSOracle/gen.ts, +/// the X- review cases), fixed here so they run without the TypeScript toolchain. +/// TS paths are in `packages/sdk/src`. +@Suite("Wallet wire review vectors from @bsv/sdk 4.1.1") +struct WalletWireReviewVectorTests { + // MARK: M1 certificate field order + + /// One certificate whose fields TS sorted with `localeCompare` + /// (auth/certificates/Certificate.ts:290): `cardholder` before `cardNumber`, + /// the reverse of byte order. + private static let mixedCaseCertificate = + "0707070707070707070707070707070707070707070707070707070707070707" + + "0909090909090909090909090909090909090909090909090909090909090909" + + "035818cd7cc614fea816c8b39eebe6e43cafc635451ec5a873f8757b418aaae91a" + + "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa" + + "abababababababababababababababababababababababababababababababab00" + + "02" + "0a63617264686f6c646572085a5731686157773d" + + "0a636172644e756d62657208626d46745a513d3d" + + "3045022100c07e93b06a4d095e3b5a54f99a23d9fb047bf97c281639284639482e0cbd3cbb" + + "0220182d292dfa53425744adcbfab1f95fb607aeef4248162f2cf0902dad87369865" + + /// X-acquireCertificate-, X-listCertificates- and X-discover-mixed-case-fields: + /// the TS processor's answers. WalletWireTransceiver.ts:1532 reads them with + /// `Certificate.fromBinary`, which takes any order. + @Test func readsTypeScriptCertificatesWithLocaleCompareFieldOrder() throws { + let certificate = try Certificate(binary: try hex(Self.mixedCaseCertificate)) + #expect(Set(certificate.fields.keys.map(\.value)) == ["cardholder", "cardNumber"]) + + let acquired = try WalletWireCodec.decodeCertificateResult( + [0x00] + hex(Self.mixedCaseCertificate), + expectedCall: .acquireCertificate + ) + guard case .acquireCertificate(let value) = acquired else { + Issue.record("expected acquireCertificate") + return + } + #expect(value.fields.count == 2) + + let listed = try WalletWireCodec.decodeCertificateResult( + [0x00, 0x01] + listRecord(), + expectedCall: .listCertificates + ) + guard case .listCertificates(let page) = listed else { + Issue.record("expected listCertificates") + return + } + #expect(page.certificates.first?.certificate.fields.count == 2) + + let discovered = try WalletWireCodec.decodeCertificateResult( + [0x00, 0x01] + discoveryRecord(), + expectedCall: .discoverByIdentityKey + ) + guard case .discoverByIdentityKey(let found) = discovered else { + Issue.record("expected discoverByIdentityKey") + return + } + #expect(found.certificates.first?.certificate.fields.count == 2) + } + + // MARK: S1 noSendChange without noSend + + /// X-createAction-noSendChange-without-noSend. TS reads noSendChange whatever + /// noSend says (wallet/validationHelpers.ts:680, WalletWireProcessor.ts:539-556). + @Test func acceptsNoSendChangeWithoutNoSend() async throws { + let request = try hex( + "010b6578616d706c652e636f6d0c4f7074696f6e732068657265" + + "ffffffffffffffffffffffffffffffffffff" + + "011976a914ca9de335082b64a8030b48d5a6d3432efc5d4aba88ac0107506179206f7574" + + String(repeating: "ff", count: 54) + + "01ffffffffffffffffffffffff01ff" + + "01a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a102" + + "01b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2ff" + ) + let response = try await answer( + request, + walletResult: #"{"txid":"a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"}"# + ) + #expect(Hex.encode(response) == "0001" + String(repeating: "a1", count: 32) + + "00" + "ffffffffffffffffff" + "ffffffffffffffffff" + "00") + } + + /// The peer reads which value was wrong, not "unsupported wallet action value". + @Test func abiFailuresKeepTheirReason() { + let relation = WalletABIError.invalidFieldRelation("fieldsToReveal contains duplicates") + #expect(walletWireMapABIError(relation) as? WalletABIError == relation) + #expect(walletWireRequestFailureMessage(relation, call: .proveCertificate) + == "Invalid Wallet Wire proveCertificate request: fieldsToReveal contains duplicates") + #expect(walletWireRequestFailureMessage( + WalletABIError.invalidEnumText(type: "trust self", value: "all"), call: .createAction + ) == "Invalid Wallet Wire createAction request: all is not a valid trust self") + #expect(walletWireMapCertificateError(CertificateError.fieldNotFound) as? CertificateError + == .fieldNotFound) + } + + // MARK: S2 fixed text to the peer, detail to the log + + @Test func otherErrorsSendFixedTextAndLogTheirDetail() { + let error = ReviewInternalFailure(secret: "internal-detail") + let request = walletWireRequestFailureMessage(error, call: .getHeight) + let result = walletWireResultFailureMessage(error, call: .listOutputs) + #expect(request == "Invalid Wallet Wire getHeight request") + #expect(result == "Invalid listOutputs result") + for message in [request, result] { + #expect(!message.contains("ReviewInternalFailure")) + #expect(!message.contains("internal-detail")) + } + let line = WalletLog.line("Wallet wire result encode", call: .listOutputs, underlying: error) + #expect(line.contains("listOutputs")) + #expect(line.contains("ReviewInternalFailure")) + #expect(line.contains("internal-detail")) + #expect(WalletLog.subsystem == "dev.opl.swift-sdk") + #expect(WalletLog.category == "BSVWallet") + } + + // MARK: S3 requested page limit + + /// X-listOutputs-over-limit and X-listCertificates-over-limit + /// (wallet/WalletResultValidation.ts:1945-1949). + @Test func processorRefusesMoreRecordsThanTheRequestAllows() async throws { + let outputs = try await answer( + hex("060b6578616d706c652e636f6d0764656661756c7400ffffffffff01ffffffffffffffffffff"), + walletResult: #"{"totalOutputs":5,"outputs":[{"outpoint":"\#(Self.txA).1","satoshis":1,"spendable":true},{"outpoint":"\#(Self.txA).2","satoshis":1,"spendable":true}]}"# + ) + #expect(outputs == errorFrame( + "Invalid listOutputs result outputs: expected at most the requested limit of 1" + )) + + let certificate = try Certificate(binary: try hex(Self.mixedCaseCertificate)) + let item = try WalletCertificateResult(certificate: certificate, keyring: nil, verifier: []) + let result = WalletWireCertificateResult.listCertificates( + try WalletListCertificatesResult(totalCertificates: 3, certificates: [item, item]) + ) + let request = WalletWireCertificateRequest.listCertificates(try WalletListCertificatesRequest( + certifiers: [certificate.certifier], + types: [certificate.type], + pagination: try WalletPagination(limit: 1) + )) + #expect(throws: WalletWireResultRejection( + message: "Invalid listCertificates result certificates: expected at most the requested limit of 1" + )) { + try WalletWireCodec.encodeCertificateResult(result, request: request) + } + // Without a request there is nothing to check against. + #expect(try WalletWireCodec.encodeCertificateResult(result).first == 0) + } + + /// WalletWireTransceiver.ts:1617, :1837 and :2097-2102: a reader stops at the + /// requested limit (10 when the request gives none). + @Test func transceiverReadsCertificatePagesUpToTheRequestedLimit() throws { + let certificate = try Certificate(binary: try hex(Self.mixedCaseCertificate)) + let list = WalletWireCertificateRequest.listCertificates(try WalletListCertificatesRequest( + certifiers: [certificate.certifier], + types: [certificate.type], + pagination: try WalletPagination(limit: 1) + )) + let listFrame: [UInt8] = [0x00, 0x02] + (try listRecord()) + (try listRecord()) + #expect(throws: WalletWireResultRejection( + message: "Wallet Wire listCertificates response exceeds the requested page limit of 1" + )) { + try WalletWireCodec.decodeCertificateResult( + listFrame, expectedCall: .listCertificates, request: list + ) + } + + let discover = WalletWireCertificateRequest.discoverByIdentityKey( + WalletDiscoverByIdentityKeyRequest( + identityKey: certificate.subject, + pagination: try WalletPagination(limit: 1) + ) + ) + let record = try discoveryRecord() + let discoveryFrame: [UInt8] = [0x00, 0x02] + record + record + #expect(throws: WalletWireResultRejection( + message: "Wallet Wire discover response exceeds the requested page limit of 1" + )) { + try WalletWireCodec.decodeCertificateResult( + discoveryFrame, expectedCall: .discoverByIdentityKey, request: discover + ) + } + + let defaultLimit = WalletWireCertificateRequest.discoverByIdentityKey( + WalletDiscoverByIdentityKeyRequest(identityKey: certificate.subject) + ) + var eleven: [UInt8] = [0x00, 0x0b] + for _ in 0..<11 { eleven += record } + #expect(throws: WalletWireResultRejection( + message: "Wallet Wire discover response exceeds the requested page limit of 10" + )) { + try WalletWireCodec.decodeCertificateResult( + eleven, expectedCall: .discoverByIdentityKey, request: defaultLimit + ) + } + } + + // MARK: N2 error wording + + /// X-relinquishCertificate-false (WalletWireProcessor.ts:2293), + /// X-waitForAuthentication-false (:1683), X-listOutputs-not-balance (:178-191), + /// X-listOutputs-more-than-total (WalletResultValidation.ts:1942). + @Test func refusalsUseTheTypeScriptWording() async throws { + let relinquish = try await answer( + hex("140b6578616d706c652e636f6d" + + String(repeating: "07", count: 32) + String(repeating: "09", count: 32) + + "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa"), + walletResult: #"{"relinquished":false}"# + ) + #expect(relinquish == errorFrame("The wallet did not relinquish the certificate")) + + let wait = try await answer( + hex("180b6578616d706c652e636f6d"), walletResult: #"{"authenticated":false}"# + ) + #expect(wait == errorFrame("Wallet did not affirmatively authenticate")) + + let notBalance = try await answer( + hex("060b6578616d706c652e636f6d0d702062746d7320746f6b656e7300" + + String(repeating: "ff", count: 24)), + walletResult: #"{"totalOutputs":5000000000,"outputs":[]}"# + ) + #expect(notBalance == errorFrame( + "Invalid listOutputs result total: expected an integer from 0 to 4294967295, received 5000000000" + )) + + let moreThanTotal = try await answer( + hex("060b6578616d706c652e636f6d0764656661756c7400" + String(repeating: "ff", count: 24)), + walletResult: #"{"totalOutputs":1,"outputs":[{"outpoint":"\#(Self.txA).1","satoshis":1,"spendable":true},{"outpoint":"\#(Self.txA).2","satoshis":1,"spendable":true}]}"# + ) + #expect(moreThanTotal == errorFrame("Invalid listOutputs result totalOutputs: expected at least 2")) + } + + /// X-raw-call-29-probe-trailing (substrates/CertificateWireCompatibility.ts:118-119), + /// X-raw-originator-bad-utf8 (primitives/utils.ts:237, a fatal TextDecoder), + /// X-raw-getPublicKey-bad-flag (WalletWireProcessor.ts:49, :1437). + @Test func malformedFramesUseTheTypeScriptWording() async throws { + let probe = try await answer(hex("1d00000100"), walletResult: nil) + #expect(probe == errorFrame( + "Wallet Wire certificate compatibility probe request contains trailing data" + )) + // A well-formed probe still gets the text TS clients downgrade on. + let plainProbe = try await answer(hex("1d000001"), walletResult: nil) + #expect(plainProbe == errorFrame("Invalid call code: 29")) + + let originator = try await answer(hex("1902c328"), walletResult: nil) + #expect(originator == errorFrame("The encoded data was not valid for encoding utf-8")) + + let flag = try await answer(hex("080002"), walletResult: nil) + #expect(flag == errorFrame("Invalid identityKey flag: expected 0 or 1, received 2")) + } + + // MARK: helpers + + private static let txA = String(repeating: "a1", count: 32) + + private func hex(_ text: String) throws -> [UInt8] { + try Hex.decode(text, maximumDecodedByteCount: 1 << 16) + } + + /// A listCertificates record: certificate, keyring flag 0, empty verifier. + private func listRecord() throws -> [UInt8] { + let certificate = try hex(Self.mixedCaseCertificate) + var writer = WalletWireWriter() + try writer.writeVarBytes(certificate) + writer.writeByte(0) + writer.writeCompactSize(0) + return writer.bytes + } + + /// A discovery record as X-discover-mixed-case-fields carries it. + private func discoveryRecord() throws -> [UInt8] { + let certificate = try hex(Self.mixedCaseCertificate) + var writer = WalletWireWriter() + try writer.writeVarBytes(certificate) + writer.writeBytes(try hex( + "09436572746966696572" + + "1968747470733a2f2f6578616d706c652e636f6d2f692e706e67" + + "0c54727573746564206365727405" + "00" + "00" + )) + return writer.bytes + } + + private func errorFrame(_ message: String) -> [UInt8] { + [1, UInt8(message.utf8.count)] + Array(message.utf8) + [0x00] + } + + private func answer(_ request: [UInt8], walletResult: String?) async throws -> [UInt8] { + let processor = WalletWireProcessor( + handler: ReviewJSONHandler(walletResult: walletResult, codec: try reviewCodec()), + failureMapper: try WalletWireRedactingFailureMapper(limits: .standard), + beefLimits: try actionBEEFLimits(), + certificateLimits: .standard, + wireLimits: .standard + ) + return try await processor.transmit(request, maximumResponseByteCount: 1 << 16) + } +} + +private struct ReviewInternalFailure: Error { + let secret: String +} + +private struct ReviewNoResult: Error {} + +private func reviewCodec() throws -> WalletBRC100JSONCodec { + try WalletBRC100JSONCodec(beefLimits: actionBEEFLimits()) +} + +/// Answers with the wallet result the TS oracle's stub wallet returned. +private struct ReviewJSONHandler: WalletRequestHandling { + let walletResult: String? + let codec: WalletBRC100JSONCodec + + func handle(_ request: WalletRequest, context: WalletRequestContext) async throws -> WalletResult { + guard let walletResult else { throw ReviewNoResult() } + return try codec.decodeResult( + route: WalletJSONRoute(call: request.call), + from: Array(walletResult.utf8) + ) + } +} diff --git a/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift b/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift index 7eb0bea..af253a9 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireTypeScriptOracleTests.swift @@ -63,6 +63,15 @@ struct WalletWireTypeScriptOracleTests { #expect(actual.first != 0, "\(vector.name): legacy type answered in-band") continue } + if vector.isCertificateFieldOrderDivergence, !frame.request.hasPrefix("1d") { + // TS writes certificate fields in localeCompare order + // (auth/certificates/Certificate.ts:290); the Swift processor writes + // byte order until BSVWallet signs in that order too. Same fields, + // same length, another order. + #expect(actual.first == 0, "\(vector.name): processor answered in-band") + #expect(actual.count == expected.count, "\(vector.name): processor response length") + continue + } #expect(Hex.encode(actual) == frame.response, "\(vector.name): processor response") _ = expected } @@ -165,6 +174,7 @@ struct TSWalletWireVector: Decodable, Sendable { let frames: [Frame] var isLegacyCertificateTypeDivergence: Bool { divergence == "legacy-certificate-type" } + var isCertificateFieldOrderDivergence: Bool { divergence == "certificate-field-order" } } private struct TSOracleStubHandler: WalletRequestHandling { diff --git a/Tools/Conformance/TSOracle/gen.ts b/Tools/Conformance/TSOracle/gen.ts index 6aaabc2..bacfded 100644 --- a/Tools/Conformance/TSOracle/gen.ts +++ b/Tools/Conformance/TSOracle/gen.ts @@ -384,6 +384,178 @@ await raw('unknown-call-30', '1e00') await raw('truncated-getHeight-frame', '19') await raw('trailing-getHeight', '190000') +// ---- review cases (wallet-pr-review.md): mixed-case certificate fields, empty +// arrays, balance baskets, page limits, false results and raw malformed frames. +// TS sorts certificate fields with localeCompare (auth/certificates/Certificate.ts:290): +// 'cardholder' comes before 'cardNumber'. The Swift processor still writes byte +// order, so its answer differs in field order only (divergence certificate-field-order); +// the Swift transceiver must read the TS bytes. +const certMixed = await makeCertificate(typeA, { cardNumber: 'bmFtZQ==', cardholder: 'ZW1haWw=' }) +await run({ + name: 'X-listCertificates-mixed-case-fields', divergence: 'certificate-field-order', method: 'listCertificates', + args: { certifiers: [certifierPub], types: [typeA] }, + result: { totalCertificates: 1, certificates: [{ ...certJSON(certMixed), keyring: {} }] } +}) +await run({ + name: 'X-acquireCertificate-mixed-case-fields', divergence: 'certificate-field-order', method: 'acquireCertificate', + args: { ...certJSON(certMixed), acquisitionProtocol: 'direct', keyringRevealer: 'certifier', keyringForSubject: { cardNumber: 'a2V5MQ==', cardholder: 'a2V5Mg==' } }, + result: certJSON(certMixed) +}) +await run({ + name: 'X-discover-mixed-case-fields', divergence: 'certificate-field-order', method: 'discoverByIdentityKey', + args: { identityKey }, + result: { totalCertificates: 1, certificates: [{ ...certJSON(certMixed), certifierInfo: { name: 'Certifier', iconUrl: 'https://example.com/i.png', description: 'Trusted cert', trust: 5 }, publiclyRevealedKeyring: {}, decryptedFields: {} }] } +}) +await run({ + name: 'X-proveCertificate-mixed-case-fields', method: 'proveCertificate', + args: { certificate: certJSON(certMixed), fieldsToReveal: ['cardholder'], verifier: counterpartyKey }, + result: { keyringForVerifier: { cardholder: 'a2V5MQ==' } } +}) +await run({ + name: 'X-listCertificates-empty-keyring-no-verifier', method: 'listCertificates', + args: { certifiers: [certifierPub], types: [typeA] }, + result: { totalCertificates: 1, certificates: [{ ...certJSON(certA), keyring: {} }] } +}) +await run({ + name: 'X-listCertificates-over-limit', method: 'listCertificates', + args: { certifiers: [certifierPub], types: [typeA], limit: 1 }, + result: { totalCertificates: 3, certificates: [{ ...certJSON(certA) }, { ...certJSON(certMixed) }] } +}) +await run({ name: 'X-isAuthenticated-false', method: 'isAuthenticated', args: {}, result: { authenticated: false } }) +await run({ + name: 'X-createAction-empty-arrays', method: 'createAction', processorOnly: true, + args: { + description: 'Empty arrays', inputs: [], labels: [], + outputs: [{ lockingScript: ls, satoshis: 1, outputDescription: 'Pay out', tags: [], basket: 'default' }], + options: { noSendChange: [`${txA}.2`], sendWith: [txB, txA], knownTxids: [], returnTXIDOnly: true } + }, + result: { txid: txA } +}) +await run({ + name: 'X-createAction-options-roundtrip', method: 'createAction', + args: { + description: 'Options here', + outputs: [{ lockingScript: ls, satoshis: 1, outputDescription: 'Pay out' }], + options: { noSendChange: [`${txA}.2`], sendWith: [txB, txA], noSend: true, returnTXIDOnly: true } + }, + result: { txid: txA, noSendChange: [] } +}) +// A TS client may send noSendChange without noSend (validationHelpers.ts:680). +await run({ + name: 'X-createAction-noSendChange-without-noSend', method: 'createAction', + args: { + description: 'Options here', + outputs: [{ lockingScript: ls, satoshis: 1, outputDescription: 'Pay out' }], + options: { noSendChange: [`${txA}.2`], sendWith: [txB], returnTXIDOnly: true } + }, + result: { txid: txA } +}) +await run({ + name: 'X-createAction-input-no-script', method: 'createAction', processorOnly: true, + args: { + description: 'No script len', inputBEEF: Array.from(parent.toBEEF()), + inputs: [{ outpoint: `${parent.id('hex')}.0`, inputDescription: 'Spend parent', unlockingScriptLength: 0 }] + }, + result: { signableTransaction: { tx: Array.from(signableAtomic), reference: 'cmVmZXJlbmNl' } } +}) +await run({ + name: 'X-listOutputs-empty-strings', method: 'listOutputs', + args: { basket: 'default', tags: [], includeCustomInstructions: true, includeTags: true, includeLabels: true }, + result: { totalOutputs: 1, outputs: [{ outpoint: `${txA}.1`, satoshis: 0, lockingScript: '', spendable: true, customInstructions: '', tags: [], labels: [] }] } +}) +await run({ + name: 'X-listOutputs-balance-zero', method: 'listOutputs', + args: { basket: 'balance default' }, + result: { totalOutputs: 0, outputs: [] } +}) +await run({ + name: 'X-listOutputs-balance-huge', method: 'listOutputs', + args: { basket: 'balance default' }, + result: { totalOutputs: 2100000000000000, outputs: [] } +}) +await run({ + name: 'X-listOutputs-not-balance', method: 'listOutputs', + args: { basket: 'p btms tokens' }, + result: { totalOutputs: 5000000000, outputs: [] } +}) +await run({ + name: 'X-listOutputs-spendable-balance', method: 'listOutputs', spendable: true, + args: { basket: 'balance default' }, + result: { totalOutputs: 5000000000, outputs: [] } +}) +await run({ + name: 'X-listOutputs-over-limit', method: 'listOutputs', + args: { basket: 'default', limit: 1 }, + result: { totalOutputs: 5, outputs: [{ outpoint: `${txA}.1`, satoshis: 1, spendable: true }, { outpoint: `${txA}.2`, satoshis: 1, spendable: true }] } +}) +await run({ + name: 'X-listOutputs-more-than-total', method: 'listOutputs', + args: { basket: 'default' }, + result: { totalOutputs: 1, outputs: [{ outpoint: `${txA}.1`, satoshis: 1, spendable: true }, { outpoint: `${txA}.2`, satoshis: 1, spendable: true }] } +}) +await run({ + name: 'X-listActions-positive-big', method: 'listActions', + args: { labels: [] }, + result: { totalActions: 1, actions: [{ txid: txA, satoshis: 5000000000, status: 'failed', isOutgoing: false, description: 'Big one', version: 2, lockTime: 4294967295 }] } +}) +await run({ + name: 'X-listActions-output-no-basket', transceiverOnly: true, method: 'listActions', + args: { labels: [], includeOutputs: true }, + result: { totalActions: 1, actions: [{ txid: txA, satoshis: -1, status: 'nosend', isOutgoing: true, description: 'No basket', version: 1, lockTime: 0, outputs: [{ outputIndex: 0, satoshis: 1, spendable: true, outputDescription: 'An output' }] }] } +}) +await run({ + name: 'X-getPublicKey-privileged', method: 'getPublicKey', + args: { identityKey: true, privileged: true, privilegedReason: 'needed for test', seekPermission: false } +}) +await run({ + name: 'X-verifySignature-hash', method: 'verifySignature', + args: { protocolID: [2, 'wire tests'], keyID: '1', counterparty: counterpartyKey, hashToDirectlyVerify: Array(32).fill(5), signature: sig } +}) +await run({ + name: 'X-encrypt-default-counterparty', method: 'encrypt', processorOnly: true, + args: { protocolID: [1, 'wire tests'], keyID: '1', plaintext: [] } +}) +await run({ + name: 'X-internalize-no-tags-empty-labels', method: 'internalizeAction', processorOnly: true, + args: { + tx: Array.from(childAtomic), description: 'Receive token', labels: [], + outputs: [{ outputIndex: 0, protocol: 'basket insertion', insertionRemittance: { basket: 'tokens' } }] + }, + result: { accepted: true } +}) +await run({ + name: 'X-internalize-refused', method: 'internalizeAction', + args: { + tx: Array.from(childAtomic), description: 'Receive token', + outputs: [{ outputIndex: 0, protocol: 'basket insertion', insertionRemittance: { basket: 'tokens' } }] + }, + result: { accepted: false } +}) +await run({ name: 'X-relinquishOutput-false', method: 'relinquishOutput', args: { basket: 'default', output: `${txA}.1` }, result: { relinquished: false } }) +await run({ + name: 'X-relinquishCertificate-false', method: 'relinquishCertificate', + args: { type: typeA, serialNumber: serialA, certifier: certifierPub }, result: { relinquished: false } +}) +await run({ name: 'X-waitForAuthentication-false', method: 'waitForAuthentication', args: {}, result: { authenticated: false } }) +await run({ + name: 'X-discoverByAttributes-unsorted', method: 'discoverByAttributes', processorOnly: true, + args: { attributes: { name: 'Alice', email: 'user@example.com' } }, + result: { totalCertificates: 0, certificates: [] } +}) +await run({ name: 'X-empty-originator', method: 'getHeight', originator: '', args: {}, result: { height: 1 } }) +await run({ + name: 'X-revealSpecific-pubkey', method: 'revealSpecificKeyLinkage', + args: { counterparty: counterpartyKey, verifier: certifierPub, protocolID: [0, 'wire tests'], keyID: 'key one', privileged: false }, processorOnly: true +}) +await raw('X-raw-empty', '') +await raw('X-raw-call-0', '0000') +await raw('X-raw-call-29-probe-trailing', '1d00000100') +await raw('X-raw-originator-truncated', '1905ab') +await raw('X-raw-originator-bad-utf8', '1902c328') +await raw('X-raw-listOutputs-ext-2', '0600' + '0764656661756c74' + '00' + 'ffffffffff' + 'ffffffffffffffffff' + 'ffffffffffffffffff' + 'ff' + '02') +await raw('X-raw-listOutputs-ext-trailing', '0600' + '0764656661756c74' + '00' + 'ffffffffff' + 'ffffffffffffffffff' + 'ffffffffffffffffff' + 'ff' + '0100') +await raw('X-raw-getPublicKey-bad-flag', '080002') + await Bun.write(OUTPUT, JSON.stringify({ source: SOURCE, rootKey: 'f0efba88c117ca2614554bb676d743f413822a31e3c8d70cfcc5fff119d20a07',