Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Documentation/Compatibility/BRC-Matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
|---|---|---|---|---|---|---|
| BRC-12 `transactions/0012.md` | Bitcoin raw transaction: version u32 LE; CompactSize input/output counts; input prev-tx hash in internal byte order, vout u32 LE, script length+bytes, sequence; output satoshis u64 LE and script; locktime u32 LE; txid=SHA256d. New local “wire frame” is a 44-byte big-endian header (magic `E3E1F3E8`, protocol `02BF`, frame `1`, reserved `0`, internal txid, payload length) followed by raw tx. | **Partial**: `transaction.Transaction`, `TransactionInput`, `TransactionOutput`, `NewTransactionFromBytes`, `NewTransactionFromHex`, `ReadFrom`, `Bytes`, `Hex`, `TxID`; `util.VarInt`; `chainhash`. No BRC-12 wire-frame API found. | `BSVCore` byte cursor/CompactSize; `BSVTransaction` raw transaction and optional frame codec. | SHA256d, strict bounds/overflow checks, byte-order types. | Document has a frame example; no single comprehensive raw-tx golden vector. Use Go transaction fixtures plus Bitcoin consensus vectors. | Decide whether the newly added frame is Phase 1 or later network framing. It overlaps the multicast framing family and is not present in pinned Go.
| BRC-14 `scripts/0014.md` | Script binary/hex formats and ASM/SASM tokenization; preserve pushed bytes and distinguish opcode versus data encoding. | **Partial/full core**: `script.Script`, `NewFromBytes`, `NewFromHex`, `NewFromASM`, `ToASM`, `Chunks`, opcode maps. | `BSVScript` | Byte cursor, opcode enum, ScriptNum/pushdata rules. | Inline hex/ASM examples. | Go’s ASM parser is deliberately smaller than the BRC-15 assembler; do not claim BRC-15 from BRC-14 support.
| BRC-106 `scripts/0106.md` | Canonical ASM presentation and accepted aliases; output `OP_FALSE`/`OP_TRUE` rather than `OP_0`/`OP_1`; stable opcode/data rendering. | **Partial**: opcode alias maps and `Script.ToASM`; requires explicit conformance tests for canonical names. | `BSVScript` | BRC-14. | Inline equivalence examples. | Freeze canonical output separately from permissive input aliases.
| BRC-106 `scripts/0106.md` | Canonical ASM presentation and accepted aliases; output `OP_FALSE`/`OP_TRUE` rather than `OP_0`/`OP_1`; stable opcode/data rendering. | **Partial**: opcode alias maps and `Script.ToASM`; requires explicit conformance tests for canonical names. Swift: BRC-106 output is `asm(style: .canonical)` and input `Script(asm:dialect: .brc106)`; the default is the @bsv/sdk dialect, which prints `OP_0`/`OP_1` (COMP-022). | `BSVScript` | BRC-14. | Inline equivalence examples. | Freeze canonical output separately from permissive input aliases.
| BRC-15 `scripts/0015.md` | Full `.basm` language: comments, quoted strings/escapes, numbers/opcodes, template variables, `.unlock`/`.lock`, assembly pipeline. | **None/partial parser only**: `script.NewFromASM` does not implement the complete language. | `BSVScriptAssembler` (later target or optional product) | BRC-14/106; lexer/parser; diagnostics. | Numerous source snippets, not a machine-readable suite. | Not a primitive-parity gate unless the public roadmap promises BASM.
| BRC-16 `scripts/0016.md` | Standard P2PKH lock/unlock templates and Base58Check address conversion/network prefixes. | **Full**: `transaction/template/p2pkh.Lock`, `Unlock`, `Decode`; `script.Address`. | `BSVScript` templates + `BSVKeys` address | HASH160, Base58Check, DER ECDSA, sighash. | Locking/unlocking/address examples in document and Go tests. | Ensure decoding rejects malformed/noncanonical variants without preventing generic script parsing.
| BRC-17 `scripts/0017.md` | R-puzzle output and redemption, including custom version prefixes/address form. | **None** as a named template. | `BSVScript` optional templates | Hashes, ECDSA signature/R extraction. | Inline examples. | Clarify whether custom address prefixes belong in the core address type.
Expand Down
8 changes: 4 additions & 4 deletions Documentation/Compatibility/Rulings.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,107 @@ parsing that text emits the SDK's shortest push-length form. Its formatter also
returns an empty string for malformed push programs, and its parser silently
ignores an error when a standalone push opcode name is supplied.

The SDKs also disagree on opcode names. BRC-106 prints 0xb6...0xbc as
`OP_NOP4`...`OP_NOP10`. @bsv/sdk 4.x prints the restored Chronicle names at
0xb3...0xb7 and reads `OP_NOP4`...`OP_NOP8` as their aliases, prints 0xb8 and
0xb9 as `OP_NOP9`/`OP_NOP10`, and names 0xba...0xf8 `OP_NOP11`...`OP_NOP73`,
0xf9 `OP_SMALLDATA` and 0xfc `OP_NOP77`. Go names 0x50 `OP_BASE` and the high
bytes `OP_UNKNOWNn`. The same text can therefore mean different bytes in
different SDKs: BRC-106 `OP_NOP4` (0xb6) is 0xb3 in @bsv/sdk, and @bsv/sdk
`OP_NOP9` (0xb8) is 0xbb in BRC-106.

## Ruling

Swift ASM parsing and formatting are explicitly byte-bounded. Default
formatting uses BRC-106 names (`OP_FALSE` and `OP_TRUE`); compact output follows
BRC-14 SASM. Parsing always requires the caller to select a dialect. A named
Go-SDK dialect preserves the pinned SDK's conflicting
Chronicle/NOP map for exact interop. Common unambiguous aliases remain accepted.
Pushed data is lowercase hexadecimal
and non-minimal push forms normalize on reassembly. Standalone push opcodes,
malformed/truncated programs, ambiguous spacing, and exhausted resource limits
return typed errors instead of an empty result or partial script.
Swift ASM parsing and formatting are explicitly byte-bounded and take a named
dialect. Three dialects exist:

- `.typeScript` (the default for both parsing and formatting) reads what
@bsv/sdk 4.1.1 `Script.fromASM` reads and writes its opcode names: its
opcode table and first-listed output names (`OP_0`, `OP_1`, Chronicle names,
`OP_NOP9`...`OP_NOP77`, `OP_SMALLDATA`), the bare tokens `0` and `-1`,
lowercase hexadecimal with odd lengths padded with a leading zero (`3` is
the byte 0x03, and `1` is data, not OP_1), and `OP_PUSHDATA1/2/4 <length>
<hex>`, which keeps the named push opcode. Where 4.1.1 `toASM` is not
reversible (a top-level OP_RETURN, zero-length pushes, empty input) Swift
follows the two unmerged @bsv/sdk fixes (`cursor/script-op-return-asm-954d`,
`cursor/script-fromasm-empty-09e9`): a zero-length push prints as `OP_0`,
empty text is the empty script, and an OP_RETURN outside any
OP_IF/OP_NOTIF/OP_VERIF/OP_VERNOTIF block is printed by name, followed by
the remaining bytes read leniently, as @bsv/sdk keeps them as one data
chunk. A truncated push there prints as the bytes that remain (`OP_0` when
none remain).
- `.brc106` formats BRC-106 names (`OP_FALSE` and `OP_TRUE`); compact output
follows BRC-14 SASM. It accepts common unambiguous aliases.
- `.goSDK` preserves the pinned Go SDK's conflicting Chronicle/NOP map for
exact interop.

Text Swift writes reads back to the same bytes in @bsv/sdk 4.1.1. The reverse
does not hold where 4.1.1 output cannot be read back by 4.1.1 either:

| Script bytes | @bsv/sdk 4.1.1 | Swift default (and the unmerged fixes) |
|---|---|---|
| `006a0568656c6c6f` | `toASM`: `OP_0 0568656c6c6f` (reads back as `00060568656c6c6f`) | `OP_0 OP_RETURN 68656c6c6f` |
| `6a` | `toASM`: empty string | `OP_RETURN` |
| `4c00` | `toASM`: a blank token | `OP_0` |
| `00634c006851` | `toASM`: `OP_0 OP_IF OP_ENDIF OP_1` (two spaces) | `OP_0 OP_IF OP_0 OP_ENDIF OP_1` |
| empty | `fromASM("")`: script `00` | empty script |

Swift rejects 4.1.1's blank tokens with `invalidASMSpacing`.

The lenient OP_RETURN tail is lossy for malformed pushes: `6a056869` (a push
of five bytes with two present) prints as `OP_RETURN 6869`, which reads back
as `6a026869`; `6a4d01` prints as `OP_RETURN OP_0`, which reads back as
`6a00`. The unmerged @bsv/sdk fix behaves the same way. Do not use default ASM
as a script's identity or as a well-formedness check: `style: .canonical` and
`operations(maximumPushDataByteCount:)` reject malformed pushes.

Differences from 4.1.1 `fromASM` kept on purpose:

- The `OP_PUSHDATA*` length must be the data's byte count in plain decimal
(`5`, not `05`). @bsv/sdk ignores it, and silently writes a wrong length
byte when the data does not fit the named opcode; Swift throws
`invalidASMPushDataLength` or `dataTooLargeForPush`.
- A trailing `OP_PUSHDATA1` (or `OP_PUSHDATA1 0`) with no data token is an
empty push (`4c00`), as in @bsv/sdk. `OP_PUSHDATA1 5` with no data token is
`4c00` in @bsv/sdk; Swift throws `invalidASMPushDataLength`, because the
length does not match.
- Like @bsv/sdk, raw data tokens must be lowercase (`ABCD` throws
`invalidASMToken`), while the data token of `OP_PUSHDATA*` accepts either
case. The other dialects accept uppercase data.

The TypeScript dialect is the default because the package has no callers that
depend on BRC-106 or Go output, and it is the one whose text @bsv/sdk reads
back to the same bytes. BRC-106 and Go output remain available by
passing `style: .canonical` or `.goSDK`, and their parsers by passing
`dialect: .brc106` or `.goSDK`. The default output therefore spells OP_0 and
OP_1 as `OP_0`/`OP_1`, not the BRC-106 `OP_FALSE`/`OP_TRUE`; both parse in
every dialect.

Pushed data is lowercase hexadecimal and non-minimal push forms normalize on
reassembly, except the TypeScript `OP_PUSHDATA*` form above. Standalone push
opcodes, malformed or truncated programs (outside the TypeScript OP_RETURN
tail), ambiguous spacing, a wrong `OP_PUSHDATA*` length, and exhausted
resource limits return typed errors instead of an empty result or partial
script. An empty string is the empty script in every dialect.

Changing the default from `.canonical`/`.brc106` to `.typeScript` changes the
output of `asm()` and the reading of `Script(asm:)` without a compile error:
`OP_FALSE`/`OP_TRUE` print as `OP_0`/`OP_1`, 0xb6 prints as `OP_LSHIFTNUM`
(was `OP_NOP4`), 0xb8 as `OP_NOP9` (was `OP_NOP6`), malformed pushes after a
top-level OP_RETURN print instead of throwing, and `1` reads as data.

BRC-14's compact spelling is ambiguous for `OP_10` through `OP_16`, because
bare `10` through `16` are also valid pushed-data hex. Swift always interprets
the bare forms as data, matching Go ASM, and retains `OP_10`...`OP_16` in
compact output so formatting and parsing cannot silently change the program.
The TypeScript dialect accepts no compact names at all: like @bsv/sdk, it reads
any token outside its `OP_*` table, `0` and `-1` as hexadecimal.

## Consequences

Use raw script bytes or hexadecimal when exact push-opcode preservation matters.
Use ASM for readable semantic interchange. Differential tests cover the stable
Go behavior, while focused Swift tests pin the deliberate error-policy changes.
Use ASM for readable semantic interchange, and parse text with the dialect of
the SDK that wrote it. Differential tests cover the stable Go behavior; the
TypeScript dialect is pinned against every name in @bsv/sdk `OP.ts` and the
`Script.test.ts` vectors, and focused Swift tests pin the deliberate
error-policy changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ Change markers and unsigned-script estimates are construction metadata. They
do not alter transaction wire bytes, equality, hashing, or the transaction ID.
Equal distribution is atomic. If the available remainder cannot give every
change output one satoshi, change outputs are removed and the remainder is
paid as additional miner fee. Division dust is also additional fee. A
paid as additional miner fee. Otherwise the division remainder goes to the
last change output, as @bsv/sdk 4.x does, rather than becoming fee as in Go.
@bsv/sdk keeps zero-valued change outputs when change is smaller than their
count; Swift does not create them. A
transaction with no marked change output is left unchanged once it is proven
to pay at least the required fee.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ print(script.isPayToPublicKeyHash)

- Parses raw opcodes and PUSHDATA operations.
- Reads and writes bounded BIP-276 text.
- Reads and writes BRC-106 ASM and compact SASM.
- Reads and writes @bsv/sdk-compatible ASM by default, plus BRC-106 ASM, compact SASM and Go SDK ASM.
- Builds P2PK, P2PKH, P2SH, and BRC-18 scripts.
- Runs Script with explicit limits and network-era rules.
- Supports CHECKSIG, CHECKMULTISIG, CLTV, CSV, and Chronicle rules.
Expand Down
52 changes: 50 additions & 2 deletions Sources/BSVSPV/SPVProofVerifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ public enum SPVProofVerifier {
///
/// The envelope must prove every reachable source transaction either through
/// a trusted Merkle root or through a complete chain of raw transactions.
/// Transactions below a trusted Merkle anchor are not re-executed. Every
/// Transactions below a trusted Merkle anchor are not re-executed. An
/// anchor proven at offset zero is its block's coinbase: as in @bsv/sdk
/// `Transaction.verify`, this returns `false` unless the tracker's
/// `currentHeight()` is at least 100 above that block. Every
/// unproven transaction has its source outputs resolved, value conservation
/// checked, and input scripts evaluated. When supplied, `feeModel` applies to
/// the root transaction only, matching the Go SDK's fee-policy boundary.
Expand Down Expand Up @@ -97,9 +100,31 @@ public enum SPVProofVerifier {

var pending = [rootTransactionID]
var visited: Set<TransactionID> = []
var currentHeight: UInt32?
while let transactionID = pending.popLast() {
guard visited.insert(transactionID).inserted else { continue }
guard !provenTransactionIDs.contains(transactionID) else { continue }
if provenTransactionIDs.contains(transactionID) {
// A proven coinbase anchors the walk only once it is mature,
// as @bsv/sdk `Transaction.verify` checks through
// `MerklePath.verify`.
if let entry = entries[transactionID],
let blockHeight = coinbaseBlockHeight(
transactionID,
entry: entry,
in: beef
)
{
if currentHeight == nil {
currentHeight = try await chainTracker.currentHeight()
}
guard let currentHeight,
UInt64(blockHeight) + 100 <= UInt64(currentHeight)
else {
return false
}
}
continue
}
guard let entry = entries[transactionID] else {
throw SPVValidationError.rootTransactionMissing(transactionID)
}
Expand Down Expand Up @@ -153,6 +178,29 @@ public enum SPVProofVerifier {
return true
}

/// The block height of the proof that anchors `transactionID`, when that
/// proof places it at offset zero (its block's coinbase).
///
/// Uses the entry's own BUMP when it holds the transaction, as
/// `BEEF.isProven` does, and otherwise the first BUMP that does.
private static func coinbaseBlockHeight(
_ transactionID: TransactionID,
entry: BEEFTransaction,
in beef: BEEF
) -> UInt32? {
guard let hash = try? Hash256(transactionID.wireBytes) else { return nil }
var candidates = beef.merklePaths
if let index = entry.merklePathIndex, beef.merklePaths.indices.contains(index) {
candidates.insert(beef.merklePaths[index], at: 0)
}
guard let path = candidates.first(where: { BEEF.path($0, contains: transactionID) }),
path.levels[0].first(where: { $0.hash == hash })?.offset == 0
else {
return nil
}
return path.blockHeight
}

private static func contextualTransaction(
_ transactionID: TransactionID,
entries: [TransactionID: BEEFTransaction]
Expand Down
56 changes: 54 additions & 2 deletions Sources/BSVScript/Opcode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -280,13 +280,65 @@ public struct Opcode: RawRepresentable, Hashable, Sendable {
}
}

/// Parses canonical BRC-106 names, compact SASM names, and common SDK aliases.
/// Name emitted by @bsv/sdk 4.x `Script.toASM`.
///
/// @bsv/sdk keeps the first name it lists for each byte: `OP_0`, `OP_1`,
/// the restored Chronicle names at 0xb3...0xb7, `OP_NOP9`/`OP_NOP10` at
/// 0xb8/0xb9, `OP_NOP11`...`OP_NOP73` at 0xba...0xf8, `OP_SMALLDATA` at
/// 0xf9 and `OP_NOP77` at 0xfc. Direct pushes (0x01...0x4b) have no name
/// there and are printed as their data, so this returns `name` for them.
public var typeScriptName: String {
return switch rawValue {
case 0x00: "OP_0"
case 0x51: "OP_1"
case 0xb1: "OP_CHECKLOCKTIMEVERIFY"
case 0xb2: "OP_CHECKSEQUENCEVERIFY"
case 0xb6: "OP_LSHIFTNUM"
case 0xb7: "OP_RSHIFTNUM"
case 0xb8: "OP_NOP9"
case 0xb9: "OP_NOP10"
case 0xba...0xf8: "OP_NOP\(Int(rawValue) - 0xba + 11)"
case 0xf9: "OP_SMALLDATA"
case 0xfa: "OP_SMALLINTEGER"
case 0xfb: "OP_PUBKEYS"
case 0xfc: "OP_NOP77"
default: name
}
}

/// Parses an opcode name in the selected dialect.
///
/// `.brc106` takes canonical BRC-106 names, compact SASM names, and common
/// SDK aliases. `.goSDK` takes the pinned Go SDK's names. `.typeScript`
/// takes exactly the names @bsv/sdk 4.x `Script.fromASM` knows: its `OP_*`
/// table with aliases, plus the bare tokens `0` and `-1`.
public init?(asmName: String, dialect: ScriptASMDialect) {
let table = dialect == .brc106 ? Self.brcASMNameTable : Self.goSDKASMNameTable
let table = switch dialect {
case .brc106: Self.brcASMNameTable
case .goSDK: Self.goSDKASMNameTable
case .typeScript: Self.typeScriptASMNameTable
}
guard let opcode = table[asmName] else { return nil }
self = opcode
}

private static let typeScriptASMNameTable: [String: Opcode] = {
var names: [String: Opcode] = [:]
for raw in UInt16(UInt8.min)...UInt16(UInt8.max) {
let opcode = Opcode(rawValue: UInt8(raw))
guard !opcode.isDirectPush else { continue }
names[opcode.typeScriptName] = opcode
}
let aliases: [String: Opcode] = [
"0": .zero, "-1": .oneNegate, "OP_FALSE": .zero, "OP_TRUE": .one,
"OP_NOP2": .checkLockTimeVerify, "OP_NOP3": .checkSequenceVerify,
"OP_NOP4": .substring, "OP_NOP5": .left, "OP_NOP6": .right,
"OP_NOP7": .leftShiftNumber, "OP_NOP8": .rightShiftNumber,
]
for (name, opcode) in aliases { names[name] = opcode }
return names
}()

private static let brcASMNameTable: [String: Opcode] = {
var names: [String: Opcode] = [:]
for raw in UInt16(UInt8.min)...UInt16(UInt8.max) {
Expand Down
Loading
Loading