Skip to content
Merged
23 changes: 14 additions & 9 deletions Documentation/Compatibility/GoSDK-v1.3.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,18 +465,23 @@ 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`;
a nonempty keyring emits `01` and its map. A present empty keyring is rejected.
maps that Swift writes UTF-8-byte-sorted and reads in any order (as
`@bsv/sdk` 4.1.1 writes them), and exact keyring presence. `nil` keyring emits `00`;
a nonempty keyring emits `01` and its map. An empty keyring is stored as `nil`
and emits `00`, as `@bsv/sdk` 4.1.1 writes it. Certificate binary fields are
read in any order (TypeScript writes `localeCompare` order) and written in
byte order.
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
Expand Down
13 changes: 7 additions & 6 deletions Documentation/Compatibility/Rulings.md

Large diffs are not rendered by default.

117 changes: 57 additions & 60 deletions Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md
Original file line number Diff line number Diff line change
@@ -1,70 +1,67 @@
# 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

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.

Safety bounds stay. They reject hostile or malformed input but never
legitimate TypeScript traffic.

## 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.
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`.
- 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: <reason>`.
- 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 <call>
request`, `Invalid <call> result`). The full error goes to the local log:
subsystem `dev.opl.swift-sdk`, category `BSVWallet` (`WalletLog`).

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.
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.

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.
## Divergence from pinned Go v1.3.3

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.
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.

## Consequences
## Tests

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.
`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`).
121 changes: 64 additions & 57 deletions Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,67 @@
# 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. 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.
- **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.
Loading
Loading