From 0b054a1e7b61d62aade542ada964e1ff5fa69b7f Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:22:51 +0000 Subject: [PATCH 1/4] Read and verify Merkle paths the way @bsv/sdk 4.1.1 writes them - A single-level path pairs the right-most node of each height with itself when it has no right neighbour, so full-block paths with an odd node count prove their root (MerklePath.ts:34, :380, :430, :671). - BUMP flags are read as a bitmask: bit 0 is a duplicate, otherwise bit 1 marks a txid. @bsv/sdk writes flags 3 for a marked duplicate. - Nodes above level zero must be siblings of a level-zero hash's ancestors (legalOffsetsOnly); new MerklePathError.illegalOffset. - MerklePath.verify returns false for a coinbase (offset 0) proof until the tracker's current height is 100 blocks above it. - Equal change distribution gives the division remainder to the last change output instead of paying it as fee. - Tests use the @bsv/sdk valid and invalid BUMP vectors and block 125632. --- Documentation/Compatibility/Rulings.md | 4 +- .../COMP-024-Transaction-Fee-Safety.md | 5 +- .../BSVTransaction/Merkle/MerklePath.swift | 83 ++++-- .../Merkle/MerklePathError.swift | 5 + .../Merkle/MerklePathVerification.swift | 15 + Sources/BSVTransaction/TransactionFee.swift | 10 +- Tests/BSVSPVTests/SPVProofVerifierTests.swift | 3 +- .../Merkle/MerklePathTests.swift | 9 +- ...rklePathTypeScriptCompatibilityTests.swift | 259 ++++++++++++++++++ .../Merkle/TypeScriptBUMPVectors.swift | 125 +++++++++ .../SPV/ChainTrackerVerificationTests.swift | 3 +- .../TransactionFeeTests.swift | 34 ++- 12 files changed, 519 insertions(+), 36 deletions(-) create mode 100644 Tests/BSVTransactionTests/Merkle/MerklePathTypeScriptCompatibilityTests.swift create mode 100644 Tests/BSVTransactionTests/Merkle/TypeScriptBUMPVectors.swift diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 267f8b4..906f0dc 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -31,8 +31,8 @@ behind the general rule. | COMP-021 | Go v1.3.3 classifies a one-input transaction with a zero previous hash as coinbase when either the previous-output index or sequence is `0xffffffff`. | Require the consensus null outpoint: one input, zero previous hash, and previous-output index `0xffffffff`; sequence is irrelevant. | Avoids misclassifying an ordinary null-hash input merely because it is finalized. Test non-final coinbase sequence and zero-hash/final-sequence with a non-max index. | | COMP-022 | Go Script ASM normalizes push encodings, returns empty text for malformed programs, and can silently ignore standalone push-opcode append errors. | Treat ASM as a bounded semantic form: canonical BRC-106 names, compact BRC-14 SASM, lowercase pushed-data hex, typed malformed/resource errors, and documented push normalization. | Raw bytes/hex remain the exact serialization. Differential tests cover stable Go output; Swift tests pin intentional safety differences. | | COMP-023 | Go v1.3.3 exports `AnyOneCanPayForkID = 0xc0`, which combines two modifier bits but omits the required ALL/NONE/SINGLE base mode. | Swift signing accepts exactly `0x41`, `0x42`, `0x43`, `0xc1`, `0xc2`, and `0xc3`. The incomplete `0xc0` modifier constant is not a valid signature-hash type. | Prevents a default-to-ALL artifact from becoming an ambiguous public signing API. The oracle and Swift raw parser reject every undefined combination; all six valid combinations are differential-tested. | -| COMP-024 | Go's fee model uses floating-point rounding, estimates compressed P2PKH unlocks at 106 bytes although non-low-R DER can require 107, can underflow paid fees, divides by zero without change, and exposes an unimplemented random mode. | Swift uses checked integer arithmetic and a safe 107-byte P2PKH maximum, reports overspending/overflow, treats no-change excess as intentional fee, and initially exposes only equal change distribution. | Preserves valid Go results for identical explicit projections while preventing rare one-byte underfunding and making hostile/incomplete states typed and nontrapping. Differential tests cover actual and projected sizes; unit tests cover overflow, dust removal, no-change, underfunding, and atomic mutation. | -| COMP-025 | Go's BRC-74 parser truncates oversized block heights, accepts unknown/combined flag bits and trailing bytes, permits zero stored levels, and its implicit root selection uses the first hash rather than a marked transaction ID. | Swift requires a UInt32 block height, nonzero height of at most 64, exact flags 0/1/2, canonical CompactSize by default, full input consumption, and bounded counts. `root()` prefers a level-zero `txid` marker, while `root(for:)` is the unambiguous verification API. Like pinned Go, single-level compound paths derive their effective height from the largest level-zero offset. | Canonical paths remain byte-compatible while malformed or ambiguous inputs fail predictably instead of truncating, ignoring data, or selecting the wrong proof target. Unit tests cover every truncation, invalid flags, limits, offset zero, duplicate markers, explicit targets, and pinned canonical Go differentials, including effective-height root computation. | +| COMP-024 | Go's fee model uses floating-point rounding, estimates compressed P2PKH unlocks at 106 bytes although non-low-R DER can require 107, can underflow paid fees, divides by zero without change, and exposes an unimplemented random mode. | Swift uses checked integer arithmetic and a safe 107-byte P2PKH maximum, reports overspending/overflow, treats no-change excess as intentional fee, and initially exposes only equal change distribution, giving the division remainder to the last change output as @bsv/sdk does. | Preserves valid Go results for identical explicit projections while preventing rare one-byte underfunding and making hostile/incomplete states typed and nontrapping. Differential tests cover actual and projected sizes; unit tests cover overflow, dust removal, no-change, underfunding, and atomic mutation. | +| COMP-025 | Go's BRC-74 parser truncates oversized block heights, accepts unknown/combined flag bits and trailing bytes, permits zero stored levels, and its implicit root selection uses the first hash rather than a marked transaction ID. | Swift requires a UInt32 block height, nonzero height of at most 64 (BRC-74; @bsv/sdk caps at 54 for JavaScript integers, which Swift does not copy), canonical CompactSize by default, full input consumption, and bounded counts. Flags are read as the bitmask Go and @bsv/sdk use: bit 0 is a duplicate, otherwise bit 1 marks a txid, and other bits are ignored. Like @bsv/sdk, nodes above level zero must be siblings of a level-zero hash's ancestors. `root()` prefers a level-zero `txid` marker, while `root(for:)` is the unambiguous verification API. Like pinned Go, single-level compound paths derive their effective height from the largest level-zero offset, and like @bsv/sdk a single-level path pairs the right-most node of each height with itself when it has no right neighbour. `verify` returns false for a coinbase (offset 0) less than 100 blocks below the tracker's current height, as @bsv/sdk does. | Canonical paths remain byte-compatible while malformed or ambiguous inputs fail predictably instead of truncating, ignoring data, or selecting the wrong proof target. Paths @bsv/sdk writes, including flags 3 and full-block single-level paths with an odd node count, parse and prove the same root. Unit tests cover every truncation, flag bits, limits, offset zero, duplicate markers, illegal upper-level offsets, explicit targets, coinbase maturity, the @bsv/sdk valid and invalid BUMP vectors, and pinned canonical Go differentials, including effective-height root computation. | | COMP-026 | Go's BEEF readers accept noncanonical CompactSize values, treat any nonzero v1 BUMP-presence byte as true, can panic on an invalid BUMP index, do not require full input consumption, and the generic parser silently unwraps an Atomic BEEF prefix. Its map-backed representation also does not preserve transaction wire order as a public value contract. Pinned Go v1.3.3 does not propagate validity from an unproved txid-only parent to its raw child even when `allowTxidOnly` is true, and vacuously accepts an unproved zero-input raw transaction. | Swift preserves canonical BEEF v1/v2 and Atomic BEEF bytes, requires canonical CompactSize by default, accepts only defined format bytes, bounds every outer and nested count/size, rejects trailing data and invalid proof references, preserves parent-before-child wire order, and exposes `AtomicBEEF` separately so callers cannot accidentally discard the subject. Permissive CompactSize import is explicit. Per BRC-96, transaction-ID-only records become validation anchors only when the caller opts into that trust policy; unproved zero-input raw transactions do not. Atomic validation rejects unrelated transactions and wholly unrelated BUMPs, but permits combined BUMPs to carry additional same-block leaves when the proof supports at least one relevant ancestor. | Canonical SDK envelopes remain wire-compatible while malformed or ambiguous packages fail with typed errors rather than panicking or losing framing information. The BRC-96 validation semantics take precedence over the pinned Go propagation artifact. Combined BUMPs are normal Go output and must not make an otherwise atomic ancestry graph unreadable. Independently authored exact-byte tests cover both versions and Atomic framing; a pinned persistent Go oracle covers decoding, reverse-direction emission, proof-backed validation, transaction-ID-only policy, and the recorded dependent-child divergence. Script execution and chain-tracker root trust remain separate higher-layer verification steps. | | COMP-027 | Pinned Go `Beef.Verify` asks its chain tracker only about BUMPs containing an explicitly marked txid leaf. A structurally referenced BUMP without the optional marker can therefore make no trust call. Go's synchronous context-aware tracker interface also places concrete trackers beneath `transaction`. | Swift defines a `Sendable`, async `ChainTracker` protocol in `BSVTransaction`, keeps concrete transports in `BSVNetwork`, and computes every level-zero leaf root before verifying every supplied BUMP in deterministic block-height order. Conflicting leaf roots are malformed proof errors; a trusted tracker rejection returns `false`; tracker failures throw. `BSVSPV` exposes the proof-stage façade without claiming script execution. | No supplied inclusion proof can bypass trusted-root validation because of marker metadata or a forged stored internal hash, and network clients can use native Swift concurrency without entering the transaction layer. Pinned Go differentials cover accepted/rejected roots and a conflicting two-marked-leaf BUMP; unit tests cover unmarked paths, deterministic ordering, short-circuiting, and thrown tracker failures. | | COMP-028 | Pinned Go preserves v1 when projecting records to txid-only even though v1 cannot serialize that format. Its merge path also leaves an attached BUMP as format 00, and merging parsed txid-only duplicates can replace them with an empty raw transaction because the parser retains a nonnil placeholder object. | Swift txid-only projection always emits valid BRC-96 v2. Immutable merge promotes to v2 when required, keeps txid-only duplicates as txid-only, lets complete raw data replace placeholders, attaches merged proofs as format 01, cross-checks every BUMP leaf root, and emits stable parent-before-child order. Known-ID trimming removes only placeholders and remaps retained BUMP indexes. | These are intentional safety and validity corrections, not wire-format changes for valid envelopes. Pinned-Go semantic summaries record both merge artifacts; Swift unit and differential tests cover proof arrival, version promotion, topological ordering, projection, trimming, index remapping, and forged combined paths. | diff --git a/Documentation/Compatibility/Rulings/COMP-024-Transaction-Fee-Safety.md b/Documentation/Compatibility/Rulings/COMP-024-Transaction-Fee-Safety.md index ba0f48c..fc99551 100644 --- a/Documentation/Compatibility/Rulings/COMP-024-Transaction-Fee-Safety.md +++ b/Documentation/Compatibility/Rulings/COMP-024-Transaction-Fee-Safety.md @@ -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. diff --git a/Sources/BSVTransaction/Merkle/MerklePath.swift b/Sources/BSVTransaction/Merkle/MerklePath.swift index d41efdf..7b8a209 100644 --- a/Sources/BSVTransaction/Merkle/MerklePath.swift +++ b/Sources/BSVTransaction/Merkle/MerklePath.swift @@ -67,6 +67,7 @@ public struct MerklePath: Hashable, Sendable { ? 1 : UInt64.bitWidth - maximumLevelZeroOffset.leadingZeroBitCount let effectiveHeight = max(sortedLevels.count, offsetHeight) + let legalOffsets = Self.legalOffsets(levels: sortedLevels) for (levelIndex, level) in sortedLevels.enumerated() { var previousOffset: UInt64? @@ -101,6 +102,14 @@ public struct MerklePath: Hashable, Sendable { treeHeight: effectiveHeight ) } + if levelIndex != 0, + !legalOffsets[levelIndex].contains(element.offset) + { + throw MerklePathError.illegalOffset( + level: levelIndex, + offset: element.offset + ) + } } } @@ -200,8 +209,12 @@ public struct MerklePath: Hashable, Sendable { ) { try $0.read(count: 1)[0] } - switch flags { - case 0, 2: + // Flags are a bitmask, as in @bsv/sdk and the Go SDK: bit 0 + // marks a duplicate (no hash follows), and otherwise bit 1 + // marks a transaction ID. Other bits carry no meaning. + if flags & 1 != 0 { + level.append(.duplicate(offset: offset)) + } else { let hashBytes = try Self.read( .hash(level: levelIndex, leaf: leafIndex), from: &cursor @@ -211,16 +224,8 @@ public struct MerklePath: Hashable, Sendable { level.append(.hash( offset: offset, hash: try Hash256(hashBytes), - isTransactionID: flags == 2 + isTransactionID: flags & 2 != 0 )) - case 1: - level.append(.duplicate(offset: offset)) - default: - throw MerklePathError.invalidFlags( - level: levelIndex, - leaf: leafIndex, - flags: flags - ) } } parsedLevels.append(level) @@ -341,11 +346,7 @@ public struct MerklePath: Hashable, Sendable { var index = MerklePathIndex(levels: levels) var workingHash = target let targetOffset = targetElement.offset - let maximumOffset = levels[0].map(\.offset).max() ?? 0 - let offsetHeight = maximumOffset == 0 - ? 1 - : UInt64.bitWidth - maximumOffset.leadingZeroBitCount - let effectiveHeight = max(levels.count, offsetHeight) + let effectiveHeight = max(levels.count, index.offsetHeight) for level in 0..> level) ^ 1 @@ -354,6 +355,10 @@ public struct MerklePath: Hashable, Sendable { continue } guard let siblingHash = index.hash(level: level, offset: siblingOffset) else { + if index.isImplicitDuplicate(level: level, offset: siblingOffset) { + workingHash = MerkleTree.parent(workingHash, workingHash) + continue + } throw MerklePathError.missingSibling( level: level, offset: siblingOffset @@ -463,6 +468,19 @@ public struct MerklePath: Hashable, Sendable { } } + /// The offsets a BRC-74 path may carry above level zero: at each height, + /// the sibling of every ancestor of a level-zero hash. Matches the + /// `legalOffsetsOnly` rule of @bsv/sdk `MerklePath`. + private static func legalOffsets(levels: [[MerklePathElement]]) -> [Set] { + var legal = Array(repeating: Set(), count: levels.count) + for element in levels[0] where !element.isDuplicate { + for height in legal.indices.dropFirst() { + legal[height].insert((element.offset >> height) ^ 1) + } + } + return legal + } + private static func read( _ field: MerklePathField, from cursor: inout ByteCursor, @@ -490,12 +508,36 @@ private struct MerklePathNode: Hashable { private struct MerklePathIndex { let levels: [[UInt64: MerklePathElement]] + let maximumLevelZeroOffset: UInt64 var derived: [MerklePathNode: Hash256] = [:] init(levels: [[MerklePathElement]]) { self.levels = levels.map { level in Dictionary(uniqueKeysWithValues: level.map { ($0.offset, $0) }) } + maximumLevelZeroOffset = levels[0].map(\.offset).max() ?? 0 + } + + /// The tree height implied by the right-most level-zero offset. + var offsetHeight: Int { + maximumLevelZeroOffset == 0 + ? 1 + : UInt64.bitWidth - maximumLevelZeroOffset.leadingZeroBitCount + } + + /// Whether a missing node is the absent right sibling of the last node + /// at its height in a single-level (full block) path. + /// + /// A single-level path lists every transaction of the block, so the + /// right-most node at each height with no right neighbour is paired with + /// itself, as Bitcoin's Merkle tree does. @bsv/sdk serializes such paths + /// without explicit duplicate markers. Multi-level paths must mark + /// duplicates explicitly. + func isImplicitDuplicate(level: Int, offset: UInt64) -> Bool { + guard levels.count == 1, offset & 1 == 1, level < UInt64.bitWidth else { + return false + } + return offset ^ 1 == maximumLevelZeroOffset >> UInt64(level) } func element(level: Int, offset: UInt64) -> MerklePathElement? { @@ -519,11 +561,12 @@ private struct MerklePathIndex { let parent: Hash256 if element(level: level - 1, offset: rightOffset)?.isDuplicate == true { parent = MerkleTree.parent(left, left) - } else { - guard let right = hash(level: level - 1, offset: rightOffset) else { - return nil - } + } else if let right = hash(level: level - 1, offset: rightOffset) { parent = MerkleTree.parent(left, right) + } else if isImplicitDuplicate(level: level - 1, offset: rightOffset) { + parent = MerkleTree.parent(left, left) + } else { + return nil } derived[node] = parent return parent diff --git a/Sources/BSVTransaction/Merkle/MerklePathError.swift b/Sources/BSVTransaction/Merkle/MerklePathError.swift index 930b12b..5d9bdb0 100644 --- a/Sources/BSVTransaction/Merkle/MerklePathError.swift +++ b/Sources/BSVTransaction/Merkle/MerklePathError.swift @@ -22,11 +22,16 @@ public enum MerklePathError: Error, Equatable, Sendable { case leafCountExceedsLimit(level: Int, actual: UInt64, maximum: UInt64) case totalLeafCountExceedsLimit(actual: UInt64, maximum: UInt64) case countNotRepresentable(UInt64) + /// Not produced by the parser, which reads flags as a bitmask like + /// @bsv/sdk and the Go SDK. Retained for source compatibility. case invalidFlags(level: Int, leaf: Int, flags: UInt8) case duplicateLeafOffset(level: Int, offset: UInt64) case duplicateMarkerRequiresOddOffset(level: Int, offset: UInt64) case transactionIDMarkerOutsideLevelZero(level: Int, offset: UInt64) case offsetOutOfRange(level: Int, offset: UInt64, treeHeight: Int) + /// A node above level zero that no level-zero hash needs: it is not the + /// sibling of any level-zero hash's ancestor at that height. + case illegalOffset(level: Int, offset: UInt64) case missingLevelZeroHash case malformed(field: MerklePathField, offset: Int, cause: BinaryDecodingError) case invalidHex(TextEncodingError) diff --git a/Sources/BSVTransaction/Merkle/MerklePathVerification.swift b/Sources/BSVTransaction/Merkle/MerklePathVerification.swift index 1bf2c14..afda982 100644 --- a/Sources/BSVTransaction/Merkle/MerklePathVerification.swift +++ b/Sources/BSVTransaction/Merkle/MerklePathVerification.swift @@ -1,12 +1,27 @@ import BSVCore extension MerklePath { + /// Blocks a coinbase must be buried under before its outputs can be spent. + static let coinbaseMaturity: UInt64 = 100 + /// Verifies this path's computed root against a trusted chain tracker. + /// + /// A transaction at offset zero is its block's coinbase. Matching + /// @bsv/sdk `MerklePath.verify`, its proof verifies only once the + /// tracker's current height is at least `blockHeight + 100`; before then + /// this returns `false` without asking the tracker about the root. public func verify( transactionID: TransactionID, using chainTracker: any ChainTracker ) async throws -> Bool { let computedRoot = try root(for: transactionID) + let target = try Hash256(transactionID.wireBytes) + if levels[0].first(where: { $0.hash == target })?.offset == 0 { + let currentHeight = try await chainTracker.currentHeight() + guard UInt64(blockHeight) + Self.coinbaseMaturity <= UInt64(currentHeight) else { + return false + } + } return try await chainTracker.isValidRoot( computedRoot, atBlockHeight: blockHeight diff --git a/Sources/BSVTransaction/TransactionFee.swift b/Sources/BSVTransaction/TransactionFee.swift index d7daa27..0fe4efa 100644 --- a/Sources/BSVTransaction/TransactionFee.swift +++ b/Sources/BSVTransaction/TransactionFee.swift @@ -88,8 +88,10 @@ public extension Transaction { /// /// If the remainder cannot give every change output at least one satoshi, /// all change outputs are removed and the remainder becomes additional - /// miner fee. Division remainders likewise become additional fee. The - /// mutation is atomic: any failure leaves the receiver unchanged. + /// miner fee. Otherwise each change output gets an equal share and the + /// last one also gets the division remainder, as @bsv/sdk does, so no + /// change is paid as extra fee. The mutation is atomic: any failure + /// leaves the receiver unchanged. mutating func applyFee( using model: any TransactionFeeModel, limits: TransactionLimits @@ -121,9 +123,13 @@ public extension Transaction { candidate.outputs.removeAll(where: \.isChange) } else { let satoshisPerChangeOutput = change / UInt64(changeOutputCount) + let remainder = change % UInt64(changeOutputCount) + var lastChangeIndex = candidate.outputs.startIndex for index in candidate.outputs.indices where candidate.outputs[index].isChange { candidate.outputs[index].satoshis = satoshisPerChangeOutput + lastChangeIndex = index } + candidate.outputs[lastChangeIndex].satoshis += remainder } _ = try candidate.serializedByteCount(limits: limits) self = candidate diff --git a/Tests/BSVSPVTests/SPVProofVerifierTests.swift b/Tests/BSVSPVTests/SPVProofVerifierTests.swift index b3abf00..f28d90d 100644 --- a/Tests/BSVSPVTests/SPVProofVerifierTests.swift +++ b/Tests/BSVSPVTests/SPVProofVerifierTests.swift @@ -442,6 +442,7 @@ private struct FixedChainTracker: ChainTracker { } func currentHeight() async throws -> UInt32 { - blockHeight + // Deep enough that a coinbase proof (offset 0) is mature. + blockHeight + 100 } } diff --git a/Tests/BSVTransactionTests/Merkle/MerklePathTests.swift b/Tests/BSVTransactionTests/Merkle/MerklePathTests.swift index cad7c39..53de1c9 100644 --- a/Tests/BSVTransactionTests/Merkle/MerklePathTests.swift +++ b/Tests/BSVTransactionTests/Merkle/MerklePathTests.swift @@ -218,12 +218,11 @@ struct MerklePathTests { try MerklePath(bytes: bytes + [0], limits: limits) } - var badFlags = bytes + // Flags are a bitmask; bits other than 0 and 1 are ignored. + var extraFlagBits = bytes let firstFlagsIndex = 4 - badFlags[firstFlagsIndex] = 3 - #expect(throws: MerklePathError.invalidFlags(level: 0, leaf: 0, flags: 3)) { - try MerklePath(bytes: badFlags, limits: limits) - } + extraFlagBits[firstFlagsIndex] = 0xfe + #expect(try MerklePath(bytes: extraFlagBits, limits: limits) == fixture.pathA) let oversizedHeight = CompactSize.encode(UInt64(UInt32.max) + 1) + [1] #expect(throws: MerklePathError.blockHeightOutOfRange( diff --git a/Tests/BSVTransactionTests/Merkle/MerklePathTypeScriptCompatibilityTests.swift b/Tests/BSVTransactionTests/Merkle/MerklePathTypeScriptCompatibilityTests.swift new file mode 100644 index 0000000..e6603d8 --- /dev/null +++ b/Tests/BSVTransactionTests/Merkle/MerklePathTypeScriptCompatibilityTests.swift @@ -0,0 +1,259 @@ +import BSVCore +import BSVCrypto +import BSVTransaction +import Testing + +/// Interop with @bsv/sdk 4.1.1 `src/transaction/MerklePath.ts`. +@Suite("BRC-74 Merkle paths interoperate with @bsv/sdk") +struct MerklePathTypeScriptCompatibilityTests { + @Test("a single-level path pairs the last odd node with itself at every height") + func singleLevelOddNode() throws { + // MerklePath.ts:34, :380, :430, :671. A one-level path lists the block's + // transactions, so the right-most node with no neighbour is duplicated. + let h0 = BSVHashing.sha256d([0x10]) + let h1 = BSVHashing.sha256d([0x11]) + let h2 = BSVHashing.sha256d([0x12]) + let path = try MerklePath(blockHeight: 1, levels: [[ + .hash(offset: 0, hash: h0, isTransactionID: true), + .hash(offset: 1, hash: h1, isTransactionID: false), + .hash(offset: 2, hash: h2, isTransactionID: true), + ]]) + let expected = MerkleTree.parent( + MerkleTree.parent(h0, h1), + MerkleTree.parent(h2, h2) + ) + #expect(try path.root(for: transactionID(h0)) == expected) + #expect(try path.root(for: transactionID(h2)) == expected) + + let limits = try merkleLimits() + let reparsed = try MerklePath(hex: try path.hex(limits: limits), limits: limits) + #expect(try reparsed.root(for: transactionID(h2)) == expected) + } + + @Test("every transaction of block 125632 proves the header root from level zero alone") + func block125632() throws { + // MerklePath.test.ts:439 (BLOCK_125632 at :172). Eleven transactions: + // level 2 has three nodes, so its last node is duplicated implicitly. + let hashes = try block125632Transactions.map { try TransactionID(displayHex: $0) } + let root = try TransactionID(displayHex: block125632Root).wireBytes + let leaves = try hashes.enumerated().map { offset, id in + MerklePathElement.hash( + offset: UInt64(offset), + hash: try Hash256(id.wireBytes), + isTransactionID: true + ) + } + + let implicit = try MerklePath(blockHeight: 125_632, levels: [leaves]) + let explicit = try MerklePath( + blockHeight: 125_632, + levels: [leaves + [.duplicate(offset: 11)]] + ) + for id in hashes { + #expect(try implicit.root(for: id).bytes == root) + #expect(try explicit.root(for: id).bytes == root) + } + } + + @Test("implicit duplication never replaces a missing left sibling or an upper level") + func implicitDuplicationIsBounded() throws { + let a = BSVHashing.sha256d([0x20]) + let c = BSVHashing.sha256d([0x22]) + let d = BSVHashing.sha256d([0x23]) + + // MerklePath.test.ts:358: a lone leaf is a proof only at offset 0. + let loneRight = try MerklePath(blockHeight: 1, levels: [[ + .hash(offset: 1, hash: a, isTransactionID: true), + ]]) + #expect(throws: MerklePathError.missingSibling(level: 0, offset: 0)) { + try loneRight.root(for: transactionID(a)) + } + + // MerklePath.test.ts:623: empty upper levels do not imply duplicates. + let twoLevels = try MerklePath(blockHeight: 1, levels: [ + [ + .hash(offset: 0, hash: a, isTransactionID: false), + .hash(offset: 1, hash: a, isTransactionID: false), + .hash(offset: 2, hash: c, isTransactionID: true), + ], + [], + ]) + #expect(throws: MerklePathError.missingSibling(level: 0, offset: 3)) { + try twoLevels.root(for: transactionID(c)) + } + + // Offsets 0 and 1 are missing: the right-most pair has no left + // neighbour to stand in for. + let missingLeft = try MerklePath(blockHeight: 1, levels: [[ + .hash(offset: 2, hash: c, isTransactionID: true), + .hash(offset: 3, hash: d, isTransactionID: false), + ]]) + #expect(throws: MerklePathError.missingSibling(level: 1, offset: 0)) { + try missingLeft.root(for: transactionID(c)) + } + } + + @Test("@bsv/sdk valid BUMP vectors parse and every level-zero hash agrees on the root") + func typeScriptValidVectors() throws { + let limits = try merkleLimits() + for hex in typeScriptValidBUMPs { + let path = try MerklePath(hex: hex, limits: limits) + _ = try path.consistentRoot() + #expect(try path.hex(limits: limits) == hex) + } + } + + @Test("@bsv/sdk invalid BUMP vectors are rejected") + func typeScriptInvalidVectors() throws { + let limits = try merkleLimits() + for vector in typeScriptInvalidBUMPs { + // @bsv/sdk checks roots in its constructor; Swift checks them when + // a path is merged, put in a BEEF, or used for a root. + #expect(throws: MerklePathError.self, "\(vector.error)") { + let path = try MerklePath(hex: vector.hex, limits: limits) + _ = try path.consistentRoot() + } + } + + // bump.invalid.vectors.ts entry 1: an upper-level node no level-zero + // hash needs ("Invalid offset: 12, at height: 1"). + #expect(throws: MerklePathError.illegalOffset(level: 1, offset: 12)) { + try MerklePath(hex: typeScriptInvalidBUMPs[0].hex, limits: limits) + } + } + + @Test("upper-level nodes must be siblings of a level-zero hash's ancestors") + func legalOffsets() throws { + // MerklePath.ts:218-244 (legalOffsetsOnly). + let a = BSVHashing.sha256d([0x30]) + let b = BSVHashing.sha256d([0x31]) + let ab = MerkleTree.parent(a, b) + let cd = MerkleTree.parent(BSVHashing.sha256d([0x32]), BSVHashing.sha256d([0x33])) + + #expect(throws: MerklePathError.illegalOffset(level: 1, offset: 0)) { + try MerklePath(blockHeight: 1, levels: [ + [ + .hash(offset: 0, hash: a, isTransactionID: true), + .hash(offset: 1, hash: b, isTransactionID: false), + ], + [ + .hash(offset: 0, hash: ab, isTransactionID: false), + .hash(offset: 1, hash: cd, isTransactionID: false), + ], + ]) + } + // A duplicate marker at level zero does not make its ancestors' siblings legal. + #expect(throws: MerklePathError.illegalOffset(level: 1, offset: 3)) { + try MerklePath(blockHeight: 1, levels: [ + [ + .hash(offset: 0, hash: a, isTransactionID: true), + .hash(offset: 1, hash: b, isTransactionID: false), + .duplicate(offset: 5), + ], + [ + .hash(offset: 1, hash: cd, isTransactionID: false), + .hash(offset: 3, hash: ab, isTransactionID: false), + ], + ]) + } + } + + @Test("BUMP flags are a bitmask: bit 0 duplicates, otherwise bit 1 marks a txid") + func flagBitmask() throws { + // MerklePath.ts:142-148. @bsv/sdk writes flags 3 for a duplicate leaf + // that also carries a txid marker (MerklePath.ts:296-301). + let a = BSVHashing.sha256d([0x40]) + let limits = try merkleLimits() + func bump(secondFlags: UInt8, firstFlags: UInt8 = 2) -> [UInt8] { + [100, 1, 2, 0, firstFlags] + a.bytes + [1, secondFlags] + } + + let duplicate = try MerklePath(blockHeight: 100, levels: [[ + .hash(offset: 0, hash: a, isTransactionID: true), + .duplicate(offset: 1), + ]]) + #expect(try MerklePath(bytes: bump(secondFlags: 3), limits: limits) == duplicate) + #expect(try MerklePath(bytes: bump(secondFlags: 0xff), limits: limits) == duplicate) + + let unmarked = try MerklePath(bytes: bump(secondFlags: 1, firstFlags: 4), limits: limits) + #expect(unmarked.levels[0][0] == .hash(offset: 0, hash: a, isTransactionID: false)) + let marked = try MerklePath(bytes: bump(secondFlags: 1, firstFlags: 6), limits: limits) + #expect(marked == duplicate) + #expect(try marked.serialized(limits: limits) == bump(secondFlags: 1)) + } + + @Test("a coinbase proof verifies only 100 blocks deep") + func coinbaseMaturity() async throws { + // MerklePath.ts:510-519; MerklePath.test.ts:417 and :428. + let coinbase = BSVHashing.sha256d([0x50]) + let sibling = BSVHashing.sha256d([0x51]) + let path = try MerklePath(blockHeight: 800_000, levels: [[ + .hash(offset: 0, hash: coinbase, isTransactionID: true), + .hash(offset: 1, hash: sibling, isTransactionID: true), + ]]) + let root = MerkleTree.parent(coinbase, sibling) + + let shallow = HeightChainTracker(root: root, blockHeight: 800_000, currentHeight: 800_099) + #expect(!(try await path.verify(transactionID: transactionID(coinbase), using: shallow))) + #expect(await shallow.rootRequests() == 0) + + let deep = HeightChainTracker(root: root, blockHeight: 800_000, currentHeight: 800_100) + #expect(try await path.verify(transactionID: transactionID(coinbase), using: deep)) + + // Only offset zero is a coinbase. + #expect(try await path.verify(transactionID: transactionID(sibling), using: shallow)) + + let maximumHeight = try MerklePath(blockHeight: .max, levels: path.levels) + let top = HeightChainTracker(root: root, blockHeight: .max, currentHeight: .max) + #expect(!(try await maximumHeight.verify(transactionID: transactionID(coinbase), using: top))) + } +} + +private actor HeightChainTracker: ChainTracker { + let root: Hash256 + let blockHeight: UInt32 + let height: UInt32 + private var requests = 0 + + init(root: Hash256, blockHeight: UInt32, currentHeight: UInt32) { + self.root = root + self.blockHeight = blockHeight + height = currentHeight + } + + func isValidRoot(_ candidate: Hash256, atBlockHeight candidateHeight: UInt32) -> Bool { + requests += 1 + return candidate == root && candidateHeight == blockHeight + } + + func currentHeight() -> UInt32 { height } + + func rootRequests() -> Int { requests } +} + +private func transactionID(_ hash: Hash256) -> TransactionID { + TransactionID(exactDigestBytesGuaranteed: hash.bytes) +} + +private func merkleLimits() throws -> MerklePathLimits { + try MerklePathLimits( + maximumByteCount: 100_000, + maximumLeavesPerLevel: 1_000, + maximumTotalLeaves: 10_000 + ) +} + +private let block125632Root = "205b2e27c58601fc1a8de04c83b6b0c46f89c16b2161c93441b7e9269cf6bc4a" +private let block125632Transactions = [ + "17cba98da71fe75862aac894392f2ff604356db386767fec364877a5a9ff200c", + "14ce64bd223ec9bb42662b74fdcf94f96a209a1aee72b7ba7639db503150ec2e", + "90a2de85351cfadd2326b9b0098e9c453af09b2980835f57a1429bbb44beb872", + "a31f2ddfea7ddd4581dca3007ee99e58ea6baa97a8ac3b32bb4610baac9f7206", + "c36eeed6fbc0259d30804f59f804dfcda35a54461157d6ac9c094f0ea378f35c", + "17752483868c52a98407a0e226d73b42e214e0fad548541619d858e1fd4a9549", + "3b8c4460412cfc55be0d50308ba704a859bd6f83bfed01b0828c9b067cd69246", + "a3f1b9d4b3ef3b061af352fdc2d02048417030fef9282c36da689cd899437cdb", + "66e2b022da877621ef197e02c3ef7d3f820d33a86ead2e72bf966432ea6776f1", + "e988b5d7a2cec8e0759ade2e151737d1cdfdde68accff42938583ad12eb98b99", + "5e7a8a8ec3f912ac1c4e90279c04263f170ed055c0411c8d490b846f01e6a99e", +] diff --git a/Tests/BSVTransactionTests/Merkle/TypeScriptBUMPVectors.swift b/Tests/BSVTransactionTests/Merkle/TypeScriptBUMPVectors.swift new file mode 100644 index 0000000..8d05865 --- /dev/null +++ b/Tests/BSVTransactionTests/Merkle/TypeScriptBUMPVectors.swift @@ -0,0 +1,125 @@ +/// `@bsv/sdk` 4.1.1 `src/transaction/__tests/bump.valid.vectors.ts`. +let typeScriptValidBUMPs: [String] = [ + "fed79f0c000c02fd3803029b490d9c8358ff11afaf45628417c9eb52c1a1fd404078a101b4f71dbb" + + "a06aa9fd390300fe82f2768edc3d0cfe4d06b7f390dcb0b7e61cca7f70117d83be0f023204d8ef01" + + "fd9d010060893ac65c8a8e6b9ef7ed5e05dc3bd25aa904812c09853c5dbf423b58a75d0e01cf0012" + + "c3c76d9c332e4701b27bfe7013e7963b92d1851d59c56955b35aecabbc8bae0166000894384f86a5" + + "c4d0d294f9b9441c3ee3d13afa094cca4515d32813b3fa4fdf3601320002aac507f74c9ff2676705" + + "eee1e70897a8baeecaf30c5f49bb22a0c5ce5fda9a01180021f7e27a08d61245be893a238853d723" + + "40881cbd47e0a390895231fa1cc44db9010d004d7a12738a1654777867182ee6f6efc4d692209bad" + + "fa5ba9bb126d08da18ed880107004f8e96b4ee6154bd44b7709f3fb4041bf4426d5f5a5944083456" + + "05e254af7cdd010200ec7d8b185bc7c096b9b88de6f63ab22baf738d5fc4cbc328f2e00644749acf" + + "520100007fd48b1d2b678907ba045b07132003db8116468cd6a3d4764e0df4a644ea0a220101009b" + + "b8ffc1a6ed2ba80ea1b09ff797387115a7129d19e93c003a74e3a20ed6ce590101001106e6ece3f7" + + "0a16de42d0f87b459c71a2440201728bd8541334933726807921", + "feb39d0c000c02fd340700ed4cb1fdd81916dabb69b63bcd378559cf40916205cd004e7f5381cc2b" + + "1ea6acfd350702957998e38434782b1c40c63a4aca0ffaf4d5d9bc3385f0e9e396f4dd3238f0df01" + + "fd9b030012f77e65627c341a3aaea3a0ed645c0082ef53995f446ab9901a27e4622fd1cc01fdcc01" + + "0074026299a4ba40fbcf33cc0c64b384f0bb2fb17c61125609a666b546539c221c01e700730f99f8" + + "cf10fccd30730474449172c5f97cde6a6cf65163359e778463e9f2b9017200a202c78dee487cf96e" + + "1a6a04d51faec4debfad09eea28cc624483f2d6fa53d54013800b51ecabaa590b6bd1805baf4f19f" + + "c0eae0dedb533302603579d124059b374b1e011d00a0f36640f32a43d790bb4c3e7877011aa8ae25" + + "e433b2b83c952a16f8452b6b79010f005d68efab62c6c457ce0bb526194cc16b27f93f8a4899f6d5" + + "9ffffdddc06e345c01060099f66a0ef693d151bbe9aeb10392ac5a7712243406f9e821219fd13d18" + + "65f569010200201fa17c98478675a96703ded42629a3c7bf32b45d0bff25f8be6849d02889ae0100" + + "00367765c2d68e0c926d81ecdf9e3c86991ccf5a52e97c49ad5cf584c8ab030427010100237b58d3" + + "217709b6ebc3bdc093413ba788739f052a0b5b3a413e65444b146bc1", +] + +/// `@bsv/sdk` 4.1.1 `src/transaction/__tests/bump.invalid.vectors.ts`, +/// with the TypeScript error each one raises. +let typeScriptInvalidBUMPs: [(error: String, hex: String)] = [ + ( + error: "Invalid offset: 12, at height: 1, with legal offsets: 413", + hex: "fed79f0c000c02fd3803029b490d9c8358ff11afaf45628417c9eb52c1a1fd404078a101b4f71dbb" + + "a06aa9fd390300fe82f2768edc3d0cfe4d06b7f390dcb0b7e61cca7f70117d83be0f023204d8ef02" + + "fd9d010060893ac65c8a8e6b9ef7ed5e05dc3bd25aa904812c09853c5dbf423b58a75d0e0c009208" + + "390a7786e1626eff4ed1923b96e71370fe7bb201472e339c6dc7c31200cf01cf0012c3c76d9c332e" + + "4701b27bfe7013e7963b92d1851d59c56955b35aecabbc8bae0166000894384f86a5c4d0d294f9b9" + + "441c3ee3d13afa094cca4515d32813b3fa4fdf3601320002aac507f74c9ff2676705eee1e70897a8" + + "baeecaf30c5f49bb22a0c5ce5fda9a01180021f7e27a08d61245be893a238853d72340881cbd47e0" + + "a390895231fa1cc44db9010d004d7a12738a1654777867182ee6f6efc4d692209badfa5ba9bb126d" + + "08da18ed880107004f8e96b4ee6154bd44b7709f3fb4041bf4426d5f5a594408345605e254af7cdd" + + "010200ec7d8b185bc7c096b9b88de6f63ab22baf738d5fc4cbc328f2e00644749acf520100007fd4" + + "8b1d2b678907ba045b07132003db8116468cd6a3d4764e0df4a644ea0a220101009bb8ffc1a6ed2b" + + "a80ea1b09ff797387115a7129d19e93c003a74e3a20ed6ce590101001106e6ece3f70a16de42d0f8" + + "7b459c71a2440201728bd8541334933726807921" + ), + ( + error: "Duplicate offset: 413, at height: 1", + hex: "fed79f0c000c02fd3803029b490d9c8358ff11afaf45628417c9eb52c1a1fd404078a101b4f71dbb" + + "a06aa9fd390300fe82f2768edc3d0cfe4d06b7f390dcb0b7e61cca7f70117d83be0f023204d8ef02" + + "fd9d010060893ac65c8a8e6b9ef7ed5e05dc3bd25aa904812c09853c5dbf423b58a75d0efd9d0100" + + "9208390a7786e1626eff4ed1923b96e71370fe7bb201472e339c6dc7c31200cf01cf0012c3c76d9c" + + "332e4701b27bfe7013e7963b92d1851d59c56955b35aecabbc8bae0166000894384f86a5c4d0d294" + + "f9b9441c3ee3d13afa094cca4515d32813b3fa4fdf3601320002aac507f74c9ff2676705eee1e708" + + "97a8baeecaf30c5f49bb22a0c5ce5fda9a01180021f7e27a08d61245be893a238853d72340881cbd" + + "47e0a390895231fa1cc44db9010d004d7a12738a1654777867182ee6f6efc4d692209badfa5ba9bb" + + "126d08da18ed880107004f8e96b4ee6154bd44b7709f3fb4041bf4426d5f5a594408345605e254af" + + "7cdd010200ec7d8b185bc7c096b9b88de6f63ab22baf738d5fc4cbc328f2e00644749acf52010000" + + "7fd48b1d2b678907ba045b07132003db8116468cd6a3d4764e0df4a644ea0a220101009bb8ffc1a6" + + "ed2ba80ea1b09ff797387115a7129d19e93c003a74e3a20ed6ce590101001106e6ece3f70a16de42" + + "d0f87b459c71a2440201728bd8541334933726807921" + ), + ( + error: "Duplicate offset: 231, at height: 3", + hex: "feb39d0c000c02fd340700ed4cb1fdd81916dabb69b63bcd378559cf40916205cd004e7f5381cc2b" + + "1ea6acfd350702957998e38434782b1c40c63a4aca0ffaf4d5d9bc3385f0e9e396f4dd3238f0df01" + + "fd9b030012f77e65627c341a3aaea3a0ed645c0082ef53995f446ab9901a27e4622fd1cc01fdcc01" + + "0074026299a4ba40fbcf33cc0c64b384f0bb2fb17c61125609a666b546539c221c02e700730f99f8" + + "cf10fccd30730474449172c5f97cde6a6cf65163359e778463e9f2b9e700d9763c2c01f03c0a7786" + + "e1626eff4ed1923b96e71370fe7b9208492e332c1b70017200a202c78dee487cf96e1a6a04d51fae" + + "c4debfad09eea28cc624483f2d6fa53d54013800b51ecabaa590b6bd1805baf4f19fc0eae0dedb53" + + "3302603579d124059b374b1e011d00a0f36640f32a43d790bb4c3e7877011aa8ae25e433b2b83c95" + + "2a16f8452b6b79010f005d68efab62c6c457ce0bb526194cc16b27f93f8a4899f6d59ffffdddc06e" + + "345c01060099f66a0ef693d151bbe9aeb10392ac5a7712243406f9e821219fd13d1865f569010200" + + "201fa17c98478675a96703ded42629a3c7bf32b45d0bff25f8be6849d02889ae010000367765c2d6" + + "8e0c926d81ecdf9e3c86991ccf5a52e97c49ad5cf584c8ab030427010100237b58d3217709b6ebc3" + + "bdc093413ba788739f052a0b5b3a413e65444b146bc1" + ), + ( + error: "ReaderUint8Array read exceeds available data", + hex: "feb39d0c000c01fd9b030012f77e65627c341a3aaea3a0ed645c0082ef53995f446ab9901a27e462" + + "2fd1cc01fdcc010074026299a4ba40fbcf33cc0c64b384f0bb2fb17c61125609a666b546539c221c" + + "01e700730f99f8cf10fccd30730474449172c5f97cde6a6cf65163359e778463e9f2b9017200a202" + + "c78dee487cf96e1a6a04d51faec4debfad09eea28cc624483f2d6fa53d54013800b51ecabaa590b6" + + "bd1805baf4f19fc0eae0dedb533302603579d124059b374b1e011d00a0f36640f32a43d790bb4c3e" + + "7877011aa8ae25e433b2b83c952a16f8452b6b79010f005d68efab62c6c457ce0bb526194cc16b27" + + "f93f8a4899f6d59ffffdddc06e345c01060099f66a0ef693d151bbe9aeb10392ac5a7712243406f9" + + "e821219fd13d1865f569010200201fa17c98478675a96703ded42629a3c7bf32b45d0bff25f8be68" + + "49d02889ae010000367765c2d68e0c926d81ecdf9e3c86991ccf5a52e97c49ad5cf584c8ab030427" + + "010100237b58d3217709b6ebc3bdc093413ba788739f052a0b5b3a413e65444b146bc1" + ), + ( + error: "Missing hash for index 1844 at height 6", + hex: "feb39d0c000c02fd340700ed4cb1fdd81916dabb69b63bcd378559cf40916205cd004e7f5381cc2b" + + "1ea6acfd350702957998e38434782b1c40c63a4aca0ffaf4d5d9bc3385f0e9e396f4dd3238f0df01" + + "fd9b030012f77e65627c341a3aaea3a0ed645c0082ef53995f446ab9901a27e4622fd1cc01fdcc01" + + "0074026299a4ba40fbcf33cc0c64b384f0bb2fb17c61125609a666b546539c221c01e700730f99f8" + + "cf10fccd30730474449172c5f97cde6a6cf65163359e778463e9f2b9017200a202c78dee487cf96e" + + "1a6a04d51faec4debfad09eea28cc624483f2d6fa53d54013800b51ecabaa590b6bd1805baf4f19f" + + "c0eae0dedb533302603579d124059b374b1e00010f005d68efab62c6c457ce0bb526194cc16b27f9" + + "3f8a4899f6d59ffffdddc06e345c01060099f66a0ef693d151bbe9aeb10392ac5a7712243406f9e8" + + "21219fd13d1865f569010200201fa17c98478675a96703ded42629a3c7bf32b45d0bff25f8be6849" + + "d02889ae010000367765c2d68e0c926d81ecdf9e3c86991ccf5a52e97c49ad5cf584c8ab03042701" + + "0100237b58d3217709b6ebc3bdc093413ba788739f052a0b5b3a413e65444b146bc1" + ), + ( + error: "Mismatched roots", + hex: "fed79f0c000c04fd3803029b490d9c8358ff11afaf45628417c9eb52c1a1fd404078a101b4f71dbb" + + "a06aa9fd390300fe82f2768edc3d0cfe4d06b7f390dcb0b7e61cca7f70117d83be0f023204d8effd" + + "3a03007fd48b1d2b678907ba045b07132003db8116468cd6a3d4764e0df4a644ea0a22fd3b03009b" + + "b8ffc1a6ed2ba80ea1b09ff797387115a7129d19e93c003a74e3a20ed6ce5902fd9d010060893ac6" + + "5c8a8e6b9ef7ed5e05dc3bd25aa904812c09853c5dbf423b58a75d0efd9c01002eea60ed9ca5ed2b" + + "a80ea1b09ff797387115a79bb8ffc176fe4337129d393e0101cf0012c3c76d9c332e4701b27bfe70" + + "13e7963b92d1851d59c56955b35aecabbc8bae0166000894384f86a5c4d0d294f9b9441c3ee3d13a" + + "fa094cca4515d32813b3fa4fdf3601320002aac507f74c9ff2676705eee1e70897a8baeecaf30c5f" + + "49bb22a0c5ce5fda9a01180021f7e27a08d61245be893a238853d72340881cbd47e0a390895231fa" + + "1cc44db9010d004d7a12738a1654777867182ee6f6efc4d692209badfa5ba9bb126d08da18ed8801" + + "07004f8e96b4ee6154bd44b7709f3fb4041bf4426d5f5a594408345605e254af7cdd010200ec7d8b" + + "185bc7c096b9b88de6f63ab22baf738d5fc4cbc328f2e00644749acf520100007fd48b1d2b678907" + + "ba045b07132003db8116468cd6a3d4764e0df4a644ea0a220101009bb8ffc1a6ed2ba80ea1b09ff7" + + "97387115a7129d19e93c003a74e3a20ed6ce590101001106e6ece3f70a16de42d0f87b459c71a244" + + "0201728bd8541334933726807921" + ), +] diff --git a/Tests/BSVTransactionTests/SPV/ChainTrackerVerificationTests.swift b/Tests/BSVTransactionTests/SPV/ChainTrackerVerificationTests.swift index a818d5f..94aa449 100644 --- a/Tests/BSVTransactionTests/SPV/ChainTrackerVerificationTests.swift +++ b/Tests/BSVTransactionTests/SPV/ChainTrackerVerificationTests.swift @@ -303,7 +303,8 @@ private actor RecordingChainTracker: ChainTracker { } func currentHeight() -> UInt32 { - acceptedRoots.keys.max() ?? 0 + // Deep enough that a coinbase proof (offset 0) is mature. + (acceptedRoots.keys.max() ?? 0) + 100 } func requests() -> [RootRequest] { diff --git a/Tests/BSVTransactionTests/TransactionFeeTests.swift b/Tests/BSVTransactionTests/TransactionFeeTests.swift index 3043af6..23da39b 100644 --- a/Tests/BSVTransactionTests/TransactionFeeTests.swift +++ b/Tests/BSVTransactionTests/TransactionFeeTests.swift @@ -89,7 +89,7 @@ struct TransactionFeeTests { } } - @Test("equal change distribution is atomic and leaves only rounding dust") + @Test("equal change distribution is atomic and gives the remainder to the last change output") func applyFee() throws { let limits = try feeLimits() let empty = try Script(bytes: [], maximumByteCount: 0) @@ -111,9 +111,8 @@ struct TransactionFeeTests { let requiredFee = try model.fee(for: transaction, limits: limits) try transaction.applyFee(using: model, limits: limits) - #expect(transaction.outputs[1].satoshis == transaction.outputs[2].satoshis) - #expect(try transaction.fee() >= requiredFee) - #expect(try transaction.fee() - requiredFee < 2) + #expect(transaction.outputs[2].satoshis - transaction.outputs[1].satoshis < 2) + #expect(try transaction.fee() == requiredFee) let beforeFailure = transaction transaction.outputs[0].satoshis = 10_000 @@ -125,6 +124,33 @@ struct TransactionFeeTests { transaction = beforeFailure } + @Test("the change remainder goes to the last change output, as @bsv/sdk does") + func changeRemainder() throws { + // @bsv/sdk Transaction.ts #distributeEqualChange. + let limits = try feeLimits() + let empty = try Script(bytes: [], maximumByteCount: 0) + var transaction = Transaction( + inputs: [TransactionInput( + previousOutput: try testOutpoint(fill: 4), + unlockingScript: empty, + sourceOutput: TransactionOutput(satoshis: 10_002, lockingScript: empty), + estimatedUnlockingScriptByteCount: 0 + )], + outputs: [ + TransactionOutput(satoshis: 0, lockingScript: empty, isChange: true), + TransactionOutput(satoshis: 1_000, lockingScript: empty), + TransactionOutput(satoshis: 0, lockingScript: empty, isChange: true), + TransactionOutput(satoshis: 0, lockingScript: empty, isChange: true), + ] + ) + try transaction.applyFee( + using: SatoshisPerKilobyteFeeModel(satoshisPerKilobyte: 0), + limits: limits + ) + #expect(transaction.outputs.map(\.satoshis) == [3_000, 1_000, 3_000, 3_002]) + #expect(try transaction.fee() == 0) + } + @Test("dust change is removed and no-change transactions preserve excess fee") func dustAndNoChange() throws { let limits = try feeLimits() From b0ad82d846da4a6ebcf7391e8ed27099447f90f6 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:22:51 +0000 Subject: [PATCH 2/4] Read and write ASM the way @bsv/sdk 4.1.1 does, by default - New ScriptASMDialect.typeScript and ScriptASMStyle.typeScript, now the defaults. They use the OP.ts names (OP_0, OP_1, OP_SUBSTR..OP_RSHIFTNUM, OP_NOP9..OP_NOP77, OP_SMALLDATA), so ASM crossing between the SDKs keeps its bytes. BRC-106 and Go output stay available. - The TypeScript dialect reads -1, odd-length hex and OP_PUSHDATA1/2/4 , which keeps its push opcode. - The TypeScript style prints zero-length pushes as OP_0 and names a top-level OP_RETURN, reading the bytes after it leniently. - New Opcode.typeScriptName and ScriptError.invalidASMPushDataLength. - COMP-022 records the decision. --- Documentation/Compatibility/Rulings.md | 2 +- .../COMP-022-Script-ASM-Normalization.md | 63 +++++- README.md | 2 +- Sources/BSVScript/Opcode.swift | 56 ++++- Sources/BSVScript/Script.swift | 204 +++++++++++------ Sources/BSVScript/ScriptASM.swift | 121 +++++++--- Sources/BSVScript/ScriptError.swift | 3 + Tests/BSVScriptTests/ScriptASMTests.swift | 8 + .../ScriptASMTypeScriptTests.swift | 206 ++++++++++++++++++ .../TypeScriptOpcodeTable.swift | 194 +++++++++++++++++ 10 files changed, 751 insertions(+), 108 deletions(-) create mode 100644 Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift create mode 100644 Tests/BSVScriptTests/TypeScriptOpcodeTable.swift diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 906f0dc..9e9f84f 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -29,7 +29,7 @@ behind the general rule. | COMP-017 | The initial oracle Base58Check operation composes Go SDK Base58 and SHA256d primitives rather than calling a single checked-encoding façade. | Treat the oracle operation as the Bitcoin one-byte-version Base58Check composition only. It does not establish multi-byte version policy or the public error behavior of WIF/address/extended-key Go APIs; the Phase 3 packet must compare those façades directly. | Prevents a composed test adapter from silently defining higher-level compatibility. Pin one known Base58Check value now and use format-specific Go/static vectors before public key-format APIs freeze. | | COMP-018 | Pinned Go SDK call sites use ordinary standard Base64 decoding, which tolerates CR/LF and non-zero discarded bits; Go Base58 rejects forbidden characters but reports a non-indexed error. | Swift Hex accepts ASCII case but otherwise rejects malformed input. Swift Base64 requires canonical encoding, rejects all whitespace including CR/LF, and rejects non-zero discarded bits. Swift Base58 rejects every non-alphabet character with its zero-based UTF-8 byte offset. Every Swift text decoder requires an explicit output maximum. | Deterministic cross-platform parsing and bounded hostile-input handling outweigh permissive decoder parity. Canonical encoders remain interoperable. Test the strict Swift results against the SDK-like non-strict Base64 oracle policy, and verify that both Base58 decoders reject forbidden input while preserving their documented error-detail difference. | | COMP-021 | Go v1.3.3 classifies a one-input transaction with a zero previous hash as coinbase when either the previous-output index or sequence is `0xffffffff`. | Require the consensus null outpoint: one input, zero previous hash, and previous-output index `0xffffffff`; sequence is irrelevant. | Avoids misclassifying an ordinary null-hash input merely because it is finalized. Test non-final coinbase sequence and zero-hash/final-sequence with a non-max index. | -| COMP-022 | Go Script ASM normalizes push encodings, returns empty text for malformed programs, and can silently ignore standalone push-opcode append errors. | Treat ASM as a bounded semantic form: canonical BRC-106 names, compact BRC-14 SASM, lowercase pushed-data hex, typed malformed/resource errors, and documented push normalization. | Raw bytes/hex remain the exact serialization. Differential tests cover stable Go output; Swift tests pin intentional safety differences. | +| COMP-022 | Go Script ASM normalizes push encodings, returns empty text for malformed programs, and can silently ignore standalone push-opcode append errors. BRC-106, Go and @bsv/sdk 4.x give conflicting names to the Chronicle and high NOP bytes, so the same text can mean different bytes. | Treat ASM as a bounded semantic form in a named dialect. The default `.typeScript` dialect reads and writes @bsv/sdk 4.1.1 text (its opcode names, `0`/`-1`, odd-length hex, `OP_PUSHDATA* `, `OP_0` for empty pushes, a lenient tail after a top-level OP_RETURN). BRC-106 names with compact BRC-14 SASM, and the Go map, remain selectable. Lowercase pushed-data hex, typed malformed/resource errors, and documented push normalization. | Raw bytes/hex remain the exact serialization. ASM crossing to @bsv/sdk keeps its bytes. Differential tests cover stable Go output; the TypeScript table is pinned against every `OP.ts` name and `Script.test.ts` vectors; Swift tests pin intentional safety differences. | | COMP-023 | Go v1.3.3 exports `AnyOneCanPayForkID = 0xc0`, which combines two modifier bits but omits the required ALL/NONE/SINGLE base mode. | Swift signing accepts exactly `0x41`, `0x42`, `0x43`, `0xc1`, `0xc2`, and `0xc3`. The incomplete `0xc0` modifier constant is not a valid signature-hash type. | Prevents a default-to-ALL artifact from becoming an ambiguous public signing API. The oracle and Swift raw parser reject every undefined combination; all six valid combinations are differential-tested. | | COMP-024 | Go's fee model uses floating-point rounding, estimates compressed P2PKH unlocks at 106 bytes although non-low-R DER can require 107, can underflow paid fees, divides by zero without change, and exposes an unimplemented random mode. | Swift uses checked integer arithmetic and a safe 107-byte P2PKH maximum, reports overspending/overflow, treats no-change excess as intentional fee, and initially exposes only equal change distribution, giving the division remainder to the last change output as @bsv/sdk does. | Preserves valid Go results for identical explicit projections while preventing rare one-byte underfunding and making hostile/incomplete states typed and nontrapping. Differential tests cover actual and projected sizes; unit tests cover overflow, dust removal, no-change, underfunding, and atomic mutation. | | COMP-025 | Go's BRC-74 parser truncates oversized block heights, accepts unknown/combined flag bits and trailing bytes, permits zero stored levels, and its implicit root selection uses the first hash rather than a marked transaction ID. | Swift requires a UInt32 block height, nonzero height of at most 64 (BRC-74; @bsv/sdk caps at 54 for JavaScript integers, which Swift does not copy), canonical CompactSize by default, full input consumption, and bounded counts. Flags are read as the bitmask Go and @bsv/sdk use: bit 0 is a duplicate, otherwise bit 1 marks a txid, and other bits are ignored. Like @bsv/sdk, nodes above level zero must be siblings of a level-zero hash's ancestors. `root()` prefers a level-zero `txid` marker, while `root(for:)` is the unambiguous verification API. Like pinned Go, single-level compound paths derive their effective height from the largest level-zero offset, and like @bsv/sdk a single-level path pairs the right-most node of each height with itself when it has no right neighbour. `verify` returns false for a coinbase (offset 0) less than 100 blocks below the tracker's current height, as @bsv/sdk does. | Canonical paths remain byte-compatible while malformed or ambiguous inputs fail predictably instead of truncating, ignoring data, or selecting the wrong proof target. Paths @bsv/sdk writes, including flags 3 and full-block single-level paths with an odd node count, parse and prove the same root. Unit tests cover every truncation, flag bits, limits, offset zero, duplicate markers, illegal upper-level offsets, explicit targets, coinbase maturity, the @bsv/sdk valid and invalid BUMP vectors, and pinned canonical Go differentials, including effective-height root computation. | diff --git a/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md b/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md index 8bf85f1..8e50447 100644 --- a/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md +++ b/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md @@ -8,25 +8,66 @@ 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 and writes + exactly what @bsv/sdk 4.1.1 `Script.fromASM`/`toASM` read and write: 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`, + odd-length hexadecimal padded with a leading zero (`3` is the byte 0x03, + and `1` is data, not OP_1), and `OP_PUSHDATA1/2/4 `, which + keeps the named push opcode. Swift requires that length to be the decimal + byte count of the data; @bsv/sdk ignores it. Formatting 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`, + 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. + +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 crosses to +@bsv/sdk without changing 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. 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. diff --git a/README.md b/README.md index ffdc57f..082350a 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/Sources/BSVScript/Opcode.swift b/Sources/BSVScript/Opcode.swift index 13bd4cc..c045a17 100644 --- a/Sources/BSVScript/Opcode.swift +++ b/Sources/BSVScript/Opcode.swift @@ -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) { diff --git a/Sources/BSVScript/Script.swift b/Sources/BSVScript/Script.swift index 4965265..403dc2a 100644 --- a/Sources/BSVScript/Script.swift +++ b/Sources/BSVScript/Script.swift @@ -52,6 +52,24 @@ public struct Script: Hashable, Sendable { /// Parses every operation and enforces a separate ceiling for each pushed value. public func operations(maximumPushDataByteCount: Int) throws -> [ScriptOperation] { + try operations( + maximumPushDataByteCount: maximumPushDataByteCount, + lenientAfterTopLevelReturn: false + ) + } + + /// Parses operations, optionally reading the bytes after a top-level + /// OP_RETURN the way @bsv/sdk does. + /// + /// @bsv/sdk folds everything after an OP_RETURN that is not inside an + /// OP_IF/OP_NOTIF/OP_VERIF/OP_VERNOTIF block into one chunk, so those + /// bytes need not be well-formed pushes. When `lenientAfterTopLevelReturn` + /// is set, a truncated push there yields the bytes that remain instead + /// of an error. Everything before that OP_RETURN is parsed strictly. + func operations( + maximumPushDataByteCount: Int, + lenientAfterTopLevelReturn: Bool + ) throws -> [ScriptOperation] { guard maximumPushDataByteCount >= 0 else { throw ScriptError.invalidMaximumPushDataByteCount(maximumPushDataByteCount) } @@ -59,78 +77,98 @@ public struct Script: Hashable, Sendable { var result: [ScriptOperation] = [] result.reserveCapacity(storage.count) var offset = 0 + var conditionalDepth = 0 + var lenient = false while offset < storage.count { - let opcodeOffset = offset - let opcode = Opcode(rawValue: storage[offset]) - offset += 1 - - let length: Int - switch opcode.rawValue { - case 0x01...0x4b: - length = Int(opcode.rawValue) - case 0x4c: - guard storage.count - offset >= 1 else { - throw ScriptError.truncatedPushDataLength( - offset: opcodeOffset, - expected: 1, - remaining: storage.count - offset - ) - } - length = Int(storage[offset]) - offset += 1 - case 0x4d: - guard storage.count - offset >= 2 else { - throw ScriptError.truncatedPushDataLength( - offset: opcodeOffset, - expected: 2, - remaining: storage.count - offset - ) - } - length = Int(storage[offset]) | (Int(storage[offset + 1]) << 8) - offset += 2 - case 0x4e: - guard storage.count - offset >= 4 else { - throw ScriptError.truncatedPushDataLength( - offset: opcodeOffset, - expected: 4, - remaining: storage.count - offset - ) - } - let declared = UInt32(storage[offset]) - | (UInt32(storage[offset + 1]) << 8) - | (UInt32(storage[offset + 2]) << 16) - | (UInt32(storage[offset + 3]) << 24) - guard UInt64(declared) <= UInt64(Int.max) else { - throw ScriptError.pushDataLengthNotRepresentable(declared) - } - length = Int(declared) - offset += 4 + let operation = try readOperation( + at: &offset, + maximumPushDataByteCount: maximumPushDataByteCount, + lenient: lenient + ) + result.append(operation) + guard lenientAfterTopLevelReturn, !lenient else { continue } + switch operation.opcode { + case .if, .notIf, .verIf, .verNotIf: + conditionalDepth += 1 + case .endIf: + conditionalDepth -= 1 + case .return where conditionalDepth == 0: + lenient = true default: - result.append(.opcode(opcode)) - continue + break } + } + return result + } - guard length <= maximumPushDataByteCount else { - throw ScriptError.pushDataTooLarge( - actual: length, - maximum: maximumPushDataByteCount - ) + private func readOperation( + at offset: inout Int, + maximumPushDataByteCount: Int, + lenient: Bool + ) throws -> ScriptOperation { + let opcodeOffset = offset + let opcode = Opcode(rawValue: storage[offset]) + offset += 1 + + let length: Int + let lengthByteCount: Int + switch opcode.rawValue { + case 0x01...0x4b: + length = Int(opcode.rawValue) + lengthByteCount = 0 + case 0x4c: + lengthByteCount = 1 + length = Int(storage[offset..> 8), + ] + case .pushData4 where UInt64(count) <= UInt64(UInt32.max): + prefix = [ + opcode.rawValue, + UInt8(truncatingIfNeeded: count), + UInt8(truncatingIfNeeded: count >> 8), + UInt8(truncatingIfNeeded: count >> 16), + UInt8(truncatingIfNeeded: count >> 24), + ] + case _ where opcode.directPushByteCount == count: + prefix = [opcode.rawValue] + default: + throw ScriptError.dataTooLargeForPush(actual: count) + } + let (additional, overflow) = prefix.count.addingReportingOverflow(count) + guard !overflow else { + throw ScriptError.scriptTooLarge(actual: Int.max, maximum: maximumScriptByteCount) + } + try requireAppendCapacity(additional, maximum: maximumScriptByteCount) + storage.append(contentsOf: prefix) + storage.append(contentsOf: data) + } + /// Appends the policy-minimal representation, using OP_1...OP_16 and /// OP_1NEGATE for their single-byte Script-number encodings. public mutating func appendMinimalPush( diff --git a/Sources/BSVScript/ScriptASM.swift b/Sources/BSVScript/ScriptASM.swift index fa24093..0cc90ac 100644 --- a/Sources/BSVScript/ScriptASM.swift +++ b/Sources/BSVScript/ScriptASM.swift @@ -8,26 +8,38 @@ public enum ScriptASMStyle: Equatable, Sendable { case compact /// Canonical opcode names emitted by the pinned Go SDK v1.3.3. case goSDK + /// Text emitted by @bsv/sdk 4.x `Script.toASM`: its opcode names + /// (`OP_0`, `OP_1`, Chronicle names), zero-length pushes as `OP_0`, and + /// the bytes after a top-level OP_RETURN read leniently. + case typeScript } -/// Opcode-name interpretation for the BRC-106/Go Chronicle naming conflict. +/// Opcode-name interpretation for the BRC-106/Go/TypeScript naming conflicts. public enum ScriptASMDialect: Equatable, Sendable { case brc106 case goSDK + /// The token rules of @bsv/sdk 4.x `Script.fromASM`: its opcode table, + /// `0` and `-1`, odd-length hexadecimal padded with a leading zero, and + /// `OP_PUSHDATA1/2/4 ` with the push opcode kept. + case typeScript } extension Script { - /// Parses bounded BRC ASM or compact SASM in an explicitly selected dialect. + /// Parses bounded ASM in the selected dialect. /// - /// Requiring `dialect` prevents conflicting NOP names from silently changing - /// bytes between BRC-106 and Go SDK text. Tokens must be separated by exactly - /// one ASCII space. Opcode aliases are - /// accepted, while hexadecimal tokens are encoded with the shortest push - /// length prefix used by the Go SDK. Consequently, ASM preserves program - /// meaning but does not preserve a non-minimal push opcode choice. + /// The default `.typeScript` dialect reads the text @bsv/sdk 4.x writes, + /// so ASM crossing between the SDKs keeps its bytes. `.brc106` reads + /// BRC-106 ASM and compact SASM; `.goSDK` reads the pinned Go SDK's + /// names. The dialects disagree on some NOP names, so pick the one that + /// wrote the text. Tokens must be separated by exactly one ASCII space. + /// Hexadecimal tokens are encoded with the shortest push length prefix. + /// Consequently, ASM preserves program meaning but does not preserve a + /// non-minimal push opcode choice, except for the `.typeScript` form + /// `OP_PUSHDATA1 ` (and its PUSHDATA2/4 forms), whose + /// decimal length must equal the data's byte count. public init( asm: String, - dialect: ScriptASMDialect, + dialect: ScriptASMDialect = .typeScript, maximumScriptByteCount: Int, maximumASMByteCount: Int ) throws { @@ -73,46 +85,93 @@ extension Script { } var result = try Script(bytes: [], maximumByteCount: maximumScriptByteCount) - for (tokenIndex, tokenBytes) in utf8.split(separator: 0x20).enumerated() { - let token = String(decoding: tokenBytes, as: UTF8.self) + let tokens = utf8.split(separator: 0x20).map { String(decoding: $0, as: UTF8.self) } + let padsOddHex = dialect == .typeScript + var tokenIndex = 0 + while tokenIndex < tokens.count { + let token = tokens[tokenIndex] if let opcode = Opcode(asmName: token, dialect: dialect) { - guard !opcode.isDataPush else { + guard opcode.isDataPush else { + try result.append(opcode, maximumScriptByteCount: maximumScriptByteCount) + tokenIndex += 1 + continue + } + // Only the TypeScript table names push opcodes, and only + // OP_PUSHDATA1/2/4: those take a length and a data token. + guard dialect == .typeScript, tokenIndex + 2 < tokens.count else { throw ScriptError.pushOpcodeRequiresData(opcode) } - try result.append(opcode, maximumScriptByteCount: maximumScriptByteCount) - continue - } - - let data: [UInt8] - do { - data = try Hex.decode( - token, - maximumDecodedByteCount: maximumScriptByteCount + let data = try Self.asmData( + tokens[tokenIndex + 2], + index: tokenIndex + 2, + padsOddLength: true, + maximumByteCount: maximumScriptByteCount ) - } catch let error as TextEncodingError { - if case .invalidCharacter = error { - throw ScriptError.invalidASMToken(index: tokenIndex) + let lengthToken = tokens[tokenIndex + 1] + guard lengthToken.utf8.allSatisfy({ (0x30...0x39).contains($0) }), + Int(lengthToken) == data.count + else { + throw ScriptError.invalidASMPushDataLength(index: tokenIndex + 1) } - throw ScriptError.invalidASMData(index: tokenIndex, error) + try result.appendPushData( + data, + using: opcode, + maximumScriptByteCount: maximumScriptByteCount + ) + tokenIndex += 3 + continue } + + let data = try Self.asmData( + token, + index: tokenIndex, + padsOddLength: padsOddHex, + maximumByteCount: maximumScriptByteCount + ) try result.appendPushData(data, maximumScriptByteCount: maximumScriptByteCount) + tokenIndex += 1 } self = result } - /// Formats bounded BRC ASM or compact SASM. + private static func asmData( + _ token: String, + index: Int, + padsOddLength: Bool, + maximumByteCount: Int + ) throws -> [UInt8] { + let hex = padsOddLength && token.utf8.count % 2 == 1 ? "0" + token : token + do { + return try Hex.decode(hex, maximumDecodedByteCount: maximumByteCount) + } catch let error as TextEncodingError { + if case .invalidCharacter = error { + throw ScriptError.invalidASMToken(index: index) + } + throw ScriptError.invalidASMData(index: index, error) + } + } + + /// Formats bounded ASM in the selected style. /// - /// Pushed values are lowercase hexadecimal. Empty non-minimal pushes are - /// normalized to `OP_FALSE`/`false`, matching their stack semantics. + /// The default `.typeScript` style writes what @bsv/sdk 4.x `toASM` + /// writes. Pushed values are lowercase hexadecimal. Empty non-minimal + /// pushes are normalized to the style's name for OP_0, matching their + /// stack semantics. Malformed pushes are errors, except in the + /// `.typeScript` style after an OP_RETURN outside any conditional, where + /// @bsv/sdk keeps the remaining bytes as data: a truncated push there is + /// written as the bytes that remain. public func asm( - style: ScriptASMStyle = .canonical, + style: ScriptASMStyle = .typeScript, maximumPushDataByteCount: Int, maximumASMByteCount: Int ) throws -> String { guard maximumASMByteCount >= 0 else { throw ScriptError.invalidMaximumASMByteCount(maximumASMByteCount) } - let operations = try operations(maximumPushDataByteCount: maximumPushDataByteCount) + let operations = try operations( + maximumPushDataByteCount: maximumPushDataByteCount, + lenientAfterTopLevelReturn: style == .typeScript + ) var tokens: [String] = [] tokens.reserveCapacity(operations.count) var outputByteCount = 0 @@ -125,6 +184,7 @@ extension Script { case .canonical: token = opcode.name case .compact: token = opcode.compactName case .goSDK: token = opcode.goSDKName + case .typeScript: token = opcode.typeScriptName } case .push(_, let data): if data.isEmpty { @@ -132,6 +192,7 @@ extension Script { case .canonical: token = Opcode.zero.name case .compact: token = Opcode.zero.compactName case .goSDK: token = Opcode.zero.goSDKName + case .typeScript: token = Opcode.zero.typeScriptName } } else { token = Hex.encode(data) diff --git a/Sources/BSVScript/ScriptError.swift b/Sources/BSVScript/ScriptError.swift index 9ea462a..125a4fa 100644 --- a/Sources/BSVScript/ScriptError.swift +++ b/Sources/BSVScript/ScriptError.swift @@ -24,6 +24,9 @@ public enum ScriptError: Error, Equatable, Sendable { case invalidASMToken(index: Int) /// Invalid hexadecimal data at a zero-based, space-delimited token index. case invalidASMData(index: Int, TextEncodingError) + /// An `OP_PUSHDATA1/2/4 ` length token, at a zero-based + /// token index, that is not the decimal byte count of its data. + case invalidASMPushDataLength(index: Int) case asmOutputTooLarge(actual: Int, maximum: Int) case nonDataOperationInFalseReturn(index: Int, Opcode) } diff --git a/Tests/BSVScriptTests/ScriptASMTests.swift b/Tests/BSVScriptTests/ScriptASMTests.swift index 32104d0..d336468 100644 --- a/Tests/BSVScriptTests/ScriptASMTests.swift +++ b/Tests/BSVScriptTests/ScriptASMTests.swift @@ -16,6 +16,7 @@ struct ScriptASMTests { ) #expect(script.hex == "76a914000000000000000000000000000000000000000088ac") #expect(try script.asm( + style: .canonical, maximumPushDataByteCount: 20, maximumASMByteCount: 128 ) == p2pkhASM) @@ -44,6 +45,7 @@ struct ScriptASMTests { ) #expect(script.bytes == [0x00, 0x51, 0xb6, 0xff]) #expect(try script.asm( + style: .canonical, maximumPushDataByteCount: 0, maximumASMByteCount: 64 ) == "OP_FALSE OP_TRUE OP_NOP4 OP_INVALIDOPCODE") @@ -66,6 +68,7 @@ struct ScriptASMTests { func pushNormalization() throws { let nonMinimal = try Script(bytes: [0x4c, 0x01, 0xaa], maximumByteCount: 3) let text = try nonMinimal.asm( + style: .canonical, maximumPushDataByteCount: 1, maximumASMByteCount: 2 ) @@ -80,9 +83,14 @@ struct ScriptASMTests { let emptyNonMinimal = try Script(bytes: [0x4c, 0x00], maximumByteCount: 2) #expect(try emptyNonMinimal.asm( + style: .canonical, maximumPushDataByteCount: 0, maximumASMByteCount: 8 ) == "OP_FALSE") + #expect(try emptyNonMinimal.asm( + maximumPushDataByteCount: 0, + maximumASMByteCount: 8 + ) == "OP_0") } @Test("bare 10 through 16 are data, never compact opcode names") diff --git a/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift b/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift new file mode 100644 index 0000000..122fea8 --- /dev/null +++ b/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift @@ -0,0 +1,206 @@ +import BSVCore +import BSVScript +import Testing + +/// ASM interop with @bsv/sdk 4.1.1 `src/script/Script.ts` and `src/script/OP.ts`, +/// plus the unmerged branches `cursor/script-op-return-asm-954d` and +/// `cursor/script-fromasm-empty-09e9`. +@Suite("Script ASM interoperates with @bsv/sdk") +struct ScriptASMTypeScriptTests { + @Test("every byte prints the first name @bsv/sdk lists and parses back") + func opcodeTable() throws { + var firstNames: [UInt8: String] = [:] + for (name, byte) in typeScriptOpcodeNames { + if firstNames[byte] == nil { firstNames[byte] = name } + #expect(Opcode(asmName: name, dialect: .typeScript)?.rawValue == byte, "\(name)") + } + for raw in UInt16(0)...UInt16(0xff) { + let opcode = Opcode(rawValue: UInt8(raw)) + guard !opcode.isDirectPush else { continue } + #expect(opcode.typeScriptName == firstNames[opcode.rawValue], "0x\(Hex.encode([opcode.rawValue]))") + } + #expect(Opcode(asmName: "0", dialect: .typeScript) == .zero) + #expect(Opcode(asmName: "-1", dialect: .typeScript) == .oneNegate) + #expect(Opcode(asmName: "OP_DATA_20", dialect: .typeScript) == nil) + #expect(Opcode(asmName: "dup", dialect: .typeScript) == nil) + #expect(Opcode(asmName: "OP_UNKNOWN186", dialect: .typeScript) == nil) + } + + @Test("every non-push byte round trips through the default dialect") + func defaultRoundTrip() throws { + for raw in UInt16(0)...UInt16(0xff) where !(0x01...0x4e).contains(raw) { + let script = try Script(bytes: [UInt8(raw)], maximumByteCount: 1) + let text = try script.asm(maximumPushDataByteCount: 0, maximumASMByteCount: 64) + let parsed = try Script(asm: text, maximumScriptByteCount: 1, maximumASMByteCount: 64) + #expect(parsed == script, "\(text)") + } + } + + @Test("Chronicle and high NOP names keep their bytes across the SDKs") + func chronicleNames() throws { + // tx-script review T13: BRC-106 prints 0xb6 as OP_NOP4, which @bsv/sdk + // reads as 0xb3; @bsv/sdk prints 0xb8 as OP_NOP9, which BRC-106 reads as 0xbb. + let bytes: [UInt8] = [0x50, 0xb3, 0xb6, 0xb8, 0xb9, 0xba, 0xf8, 0xf9, 0xfc] + let script = try Script(bytes: bytes, maximumByteCount: 9) + let text = try script.asm(maximumPushDataByteCount: 0, maximumASMByteCount: 256) + #expect(text == "OP_RESERVED OP_SUBSTR OP_LSHIFTNUM OP_NOP9 OP_NOP10 OP_NOP11 OP_NOP73 OP_SMALLDATA OP_NOP77") + #expect(try Script(asm: text, maximumScriptByteCount: 9, maximumASMByteCount: 256) == script) + #expect(try Script( + asm: "OP_NOP4 OP_NOP5 OP_NOP6 OP_NOP7 OP_NOP8 OP_NOP2 OP_NOP3", + maximumScriptByteCount: 7, + maximumASMByteCount: 64 + ).bytes == [0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb1, 0xb2]) + #expect(try Script( + asm: "OP_NOP9", + dialect: .brc106, + maximumScriptByteCount: 1, + maximumASMByteCount: 8 + ).bytes == [0xbb]) + } + + @Test("Script.test.ts fromASM and toASM vectors") + func scriptTestVectors() throws { + // Script.test.ts:228 and :245 + #expect(try roundTrip("OP_0 010203 OP_0") == "OP_0 010203 OP_0") + #expect(try roundTrip("OP_0 3 010203 OP_0") == "OP_0 03 010203 OP_0") + #expect(try parse("OP_0 3 010203 OP_0").hex == "0001030301020300") + // Script.test.ts:246 + #expect(try roundTrip("") == "") + // Script.test.ts:248 + let p2pkh = "OP_DUP OP_HASH160 f4c03610e60ad15100929cc23da2f3a799af1725 OP_EQUALVERIFY OP_CHECKSIG" + #expect(try parse(p2pkh).hex == "76a914f4c03610e60ad15100929cc23da2f3a799af172588ac") + #expect(try roundTrip(p2pkh) == p2pkh) + // Script.test.ts:264 + #expect(try roundTrip("OP_RETURN 026d02 0568656c6c6f") == "OP_RETURN 026d02 0568656c6c6f") + // Script.test.ts:271 + #expect(throws: ScriptError.invalidASMToken(index: 2)) { + try parse("OP_RETURN 026d02 0568656c6c6fzz") + } + // Script.test.ts:282, :290 and :298 + for (count, opcode) in [(220, Opcode.pushData1), (1_024, .pushData2), (1 << 17, .pushData4)] { + let text = "OP_RETURN " + String(repeating: "00", count: count) + let script = try parse(text) + #expect(script.bytes[1] == opcode.rawValue) + #expect(try format(script) == text) + } + // Script.test.ts:307 and :316 + for alias in ["OP_FALSE", "OP_0", "0"] { + #expect(try roundTrip(alias) == "OP_0") + } + for alias in ["OP_1NEGATE", "-1"] { + #expect(try roundTrip(alias) == "OP_1NEGATE") + } + #expect(try roundTrip("OP_TRUE") == "OP_1") + // Script.test.ts:211: OP_PUSHDATA4 with a three-byte payload. + let pushData4 = try Script(hex: "004e0300000001020300", maximumByteCount: 10) + #expect(try format(pushData4) == "OP_0 010203 OP_0") + } + + @Test("OP_PUSHDATA1/2/4 keeps its push opcode") + func explicitPushData() throws { + // Script.test.ts:335 + let script = try parse("OP_PUSHDATA1 5 1010101010") + #expect(script.hex == "4c051010101010") + #expect(try script.isPushOnly(maximumPushDataByteCount: 5)) + #expect(try format(script) == "1010101010") + #expect(try parse("OP_PUSHDATA2 2 abcd").hex == "4d0200abcd") + #expect(try parse("OP_PUSHDATA4 1 a OP_1").hex == "4e010000000a51") + + #expect(throws: ScriptError.invalidASMPushDataLength(index: 1)) { + try parse("OP_PUSHDATA1 4 1010101010") + } + #expect(throws: ScriptError.invalidASMPushDataLength(index: 2)) { + try parse("OP_1 OP_PUSHDATA1 0x05 1010101010") + } + #expect(throws: ScriptError.pushOpcodeRequiresData(.pushData1)) { + try parse("OP_PUSHDATA1 5") + } + #expect(throws: ScriptError.dataTooLargeForPush(actual: 256)) { + try parse("OP_PUSHDATA1 256 " + String(repeating: "00", count: 256)) + } + #expect(throws: ScriptError.invalidASMToken(index: 2)) { + try parse("OP_PUSHDATA1 1 zz") + } + } + + @Test("odd-length hexadecimal is left-padded and compact names are data or errors") + func oddHexAndCompactNames() throws { + #expect(try parse("3").hex == "0103") + #expect(try parse("abc").hex == "020abc") + // @bsv/sdk reads `1` as the byte 0x01, not OP_1. + #expect(try parse("1").hex == "0101") + // ...and `add` as the bytes 0x0add. + #expect(try parse("add").hex == "020add") + #expect(throws: ScriptError.invalidASMToken(index: 0)) { try parse("dup") } + #expect(throws: ScriptError.invalidASMToken(index: 0)) { try parse("OP_UNKNOWN186") } + // BRC-106 keeps rejecting odd-length data. + #expect(throws: ScriptError.invalidASMData(index: 0, .oddLength)) { + try Script(asm: "abc", dialect: .brc106, maximumScriptByteCount: 2, maximumASMByteCount: 3) + } + } + + @Test("a top-level OP_RETURN is named and the bytes after it are read leniently") + func opReturn() throws { + // cursor/script-op-return-asm-954d, Script.test.ts + let cases = [ + ("6a0568656c6c6f", "OP_RETURN 68656c6c6f"), + ("006a0568656c6c6f", "OP_0 OP_RETURN 68656c6c6f"), + ("6a", "OP_RETURN"), + ("006a", "OP_0 OP_RETURN"), + ] + for (hex, text) in cases { + let script = try Script(hex: hex, maximumByteCount: 16) + #expect(try format(script) == text) + #expect(try parse(text).hex == hex) + } + #expect(try parse("OP_FALSE OP_RETURN 68656c6c6f").hex == "006a0568656c6c6f") + + // A truncated push after a top-level OP_RETURN prints the bytes left. + let truncated = try Script(hex: "6a056869", maximumByteCount: 4) + #expect(try format(truncated) == "OP_RETURN 6869") + let missingLength = try Script(hex: "6a4d01", maximumByteCount: 3) + #expect(try format(missingLength) == "OP_RETURN OP_0") + let afterEndIf = try Script(hex: "6368" + "6a0268", maximumByteCount: 5) + #expect(try format(afterEndIf) == "OP_IF OP_ENDIF OP_RETURN 68") + + // Inside a conditional, and in the other styles, malformed pushes stay errors. + let inBranch = try Script(hex: "636a0568", maximumByteCount: 4) + #expect(throws: ScriptError.truncatedPushData(offset: 2, expected: 5, remaining: 1)) { + try format(inBranch) + } + #expect(throws: ScriptError.truncatedPushData(offset: 1, expected: 5, remaining: 2)) { + try truncated.asm(style: .canonical, maximumPushDataByteCount: 8, maximumASMByteCount: 64) + } + #expect(throws: ScriptError.truncatedPushData(offset: 0, expected: 5, remaining: 2)) { + try Script(hex: "056869", maximumByteCount: 3).asm(maximumPushDataByteCount: 8, maximumASMByteCount: 64) + } + #expect(throws: ScriptError.pushDataTooLarge(actual: 2, maximum: 1)) { + try truncated.asm(maximumPushDataByteCount: 1, maximumASMByteCount: 64) + } + } + + @Test("empty text, blank tokens, and zero-length pushes") + func emptyForms() throws { + // cursor/script-fromasm-empty-09e9, Script.test.ts + #expect(try parse("").bytes.isEmpty) + for text in ["OP_DUP OP_HASH160", " OP_1", "OP_1 ", " ", "OP_1 OP_2", "OP_PUSHDATA1 01", "OP_PUSHDATA1 1 "] { + #expect(throws: ScriptError.self, "\(text)") { try parse(text) } + } + #expect(try format(Script(hex: "4c00", maximumByteCount: 2)) == "OP_0") + let insideBranch = try Script(hex: "00634c006851", maximumByteCount: 6) + #expect(try format(insideBranch) == "OP_0 OP_IF OP_0 OP_ENDIF OP_1") + #expect(try roundTrip("OP_0 OP_IF OP_0 OP_ENDIF OP_1") == "OP_0 OP_IF OP_0 OP_ENDIF OP_1") + } +} + +private func parse(_ text: String) throws -> Script { + try Script(asm: text, maximumScriptByteCount: 1 << 20, maximumASMByteCount: 1 << 20) +} + +private func format(_ script: Script) throws -> String { + try script.asm(maximumPushDataByteCount: 1 << 20, maximumASMByteCount: 1 << 20) +} + +private func roundTrip(_ text: String) throws -> String { + try format(parse(text)) +} diff --git a/Tests/BSVScriptTests/TypeScriptOpcodeTable.swift b/Tests/BSVScriptTests/TypeScriptOpcodeTable.swift new file mode 100644 index 0000000..7a0322d --- /dev/null +++ b/Tests/BSVScriptTests/TypeScriptOpcodeTable.swift @@ -0,0 +1,194 @@ +/// Every name in @bsv/sdk 4.1.1 `src/script/OP.ts` `namedOP`, in source order. +/// `Script.toASM` writes the first name listed for a byte (OP.ts:222-226). +let typeScriptOpcodeNames: [(name: String, byte: UInt8)] = [ + ("OP_0", 0x00), + ("OP_FALSE", 0x00), + ("OP_PUSHDATA1", 0x4c), + ("OP_PUSHDATA2", 0x4d), + ("OP_PUSHDATA4", 0x4e), + ("OP_1NEGATE", 0x4f), + ("OP_RESERVED", 0x50), + ("OP_1", 0x51), + ("OP_TRUE", 0x51), + ("OP_2", 0x52), + ("OP_3", 0x53), + ("OP_4", 0x54), + ("OP_5", 0x55), + ("OP_6", 0x56), + ("OP_7", 0x57), + ("OP_8", 0x58), + ("OP_9", 0x59), + ("OP_10", 0x5a), + ("OP_11", 0x5b), + ("OP_12", 0x5c), + ("OP_13", 0x5d), + ("OP_14", 0x5e), + ("OP_15", 0x5f), + ("OP_16", 0x60), + ("OP_NOP", 0x61), + ("OP_VER", 0x62), + ("OP_IF", 0x63), + ("OP_NOTIF", 0x64), + ("OP_VERIF", 0x65), + ("OP_VERNOTIF", 0x66), + ("OP_ELSE", 0x67), + ("OP_ENDIF", 0x68), + ("OP_VERIFY", 0x69), + ("OP_RETURN", 0x6a), + ("OP_TOALTSTACK", 0x6b), + ("OP_FROMALTSTACK", 0x6c), + ("OP_2DROP", 0x6d), + ("OP_2DUP", 0x6e), + ("OP_3DUP", 0x6f), + ("OP_2OVER", 0x70), + ("OP_2ROT", 0x71), + ("OP_2SWAP", 0x72), + ("OP_IFDUP", 0x73), + ("OP_DEPTH", 0x74), + ("OP_DROP", 0x75), + ("OP_DUP", 0x76), + ("OP_NIP", 0x77), + ("OP_OVER", 0x78), + ("OP_PICK", 0x79), + ("OP_ROLL", 0x7a), + ("OP_ROT", 0x7b), + ("OP_SWAP", 0x7c), + ("OP_TUCK", 0x7d), + ("OP_CAT", 0x7e), + ("OP_SPLIT", 0x7f), + ("OP_NUM2BIN", 0x80), + ("OP_BIN2NUM", 0x81), + ("OP_SIZE", 0x82), + ("OP_INVERT", 0x83), + ("OP_AND", 0x84), + ("OP_OR", 0x85), + ("OP_XOR", 0x86), + ("OP_EQUAL", 0x87), + ("OP_EQUALVERIFY", 0x88), + ("OP_RESERVED1", 0x89), + ("OP_RESERVED2", 0x8a), + ("OP_1ADD", 0x8b), + ("OP_1SUB", 0x8c), + ("OP_2MUL", 0x8d), + ("OP_2DIV", 0x8e), + ("OP_NEGATE", 0x8f), + ("OP_ABS", 0x90), + ("OP_NOT", 0x91), + ("OP_0NOTEQUAL", 0x92), + ("OP_ADD", 0x93), + ("OP_SUB", 0x94), + ("OP_MUL", 0x95), + ("OP_DIV", 0x96), + ("OP_MOD", 0x97), + ("OP_LSHIFT", 0x98), + ("OP_RSHIFT", 0x99), + ("OP_BOOLAND", 0x9a), + ("OP_BOOLOR", 0x9b), + ("OP_NUMEQUAL", 0x9c), + ("OP_NUMEQUALVERIFY", 0x9d), + ("OP_NUMNOTEQUAL", 0x9e), + ("OP_LESSTHAN", 0x9f), + ("OP_GREATERTHAN", 0xa0), + ("OP_LESSTHANOREQUAL", 0xa1), + ("OP_GREATERTHANOREQUAL", 0xa2), + ("OP_MIN", 0xa3), + ("OP_MAX", 0xa4), + ("OP_WITHIN", 0xa5), + ("OP_RIPEMD160", 0xa6), + ("OP_SHA1", 0xa7), + ("OP_SHA256", 0xa8), + ("OP_HASH160", 0xa9), + ("OP_HASH256", 0xaa), + ("OP_CODESEPARATOR", 0xab), + ("OP_CHECKSIG", 0xac), + ("OP_CHECKSIGVERIFY", 0xad), + ("OP_CHECKMULTISIG", 0xae), + ("OP_CHECKMULTISIGVERIFY", 0xaf), + ("OP_NOP1", 0xb0), + ("OP_CHECKLOCKTIMEVERIFY", 0xb1), + ("OP_NOP2", 0xb1), + ("OP_CHECKSEQUENCEVERIFY", 0xb2), + ("OP_NOP3", 0xb2), + ("OP_SUBSTR", 0xb3), + ("OP_NOP4", 0xb3), + ("OP_LEFT", 0xb4), + ("OP_NOP5", 0xb4), + ("OP_RIGHT", 0xb5), + ("OP_NOP6", 0xb5), + ("OP_LSHIFTNUM", 0xb6), + ("OP_NOP7", 0xb6), + ("OP_RSHIFTNUM", 0xb7), + ("OP_NOP8", 0xb7), + ("OP_NOP9", 0xb8), + ("OP_NOP10", 0xb9), + ("OP_NOP11", 0xba), + ("OP_NOP12", 0xbb), + ("OP_NOP13", 0xbc), + ("OP_NOP14", 0xbd), + ("OP_NOP15", 0xbe), + ("OP_NOP16", 0xbf), + ("OP_NOP17", 0xc0), + ("OP_NOP18", 0xc1), + ("OP_NOP19", 0xc2), + ("OP_NOP20", 0xc3), + ("OP_NOP21", 0xc4), + ("OP_NOP22", 0xc5), + ("OP_NOP23", 0xc6), + ("OP_NOP24", 0xc7), + ("OP_NOP25", 0xc8), + ("OP_NOP26", 0xc9), + ("OP_NOP27", 0xca), + ("OP_NOP28", 0xcb), + ("OP_NOP29", 0xcc), + ("OP_NOP30", 0xcd), + ("OP_NOP31", 0xce), + ("OP_NOP32", 0xcf), + ("OP_NOP33", 0xd0), + ("OP_NOP34", 0xd1), + ("OP_NOP35", 0xd2), + ("OP_NOP36", 0xd3), + ("OP_NOP37", 0xd4), + ("OP_NOP38", 0xd5), + ("OP_NOP39", 0xd6), + ("OP_NOP40", 0xd7), + ("OP_NOP41", 0xd8), + ("OP_NOP42", 0xd9), + ("OP_NOP43", 0xda), + ("OP_NOP44", 0xdb), + ("OP_NOP45", 0xdc), + ("OP_NOP46", 0xdd), + ("OP_NOP47", 0xde), + ("OP_NOP48", 0xdf), + ("OP_NOP49", 0xe0), + ("OP_NOP50", 0xe1), + ("OP_NOP51", 0xe2), + ("OP_NOP52", 0xe3), + ("OP_NOP53", 0xe4), + ("OP_NOP54", 0xe5), + ("OP_NOP55", 0xe6), + ("OP_NOP56", 0xe7), + ("OP_NOP57", 0xe8), + ("OP_NOP58", 0xe9), + ("OP_NOP59", 0xea), + ("OP_NOP60", 0xeb), + ("OP_NOP61", 0xec), + ("OP_NOP62", 0xed), + ("OP_NOP63", 0xee), + ("OP_NOP64", 0xef), + ("OP_NOP65", 0xf0), + ("OP_NOP66", 0xf1), + ("OP_NOP67", 0xf2), + ("OP_NOP68", 0xf3), + ("OP_NOP69", 0xf4), + ("OP_NOP70", 0xf5), + ("OP_NOP71", 0xf6), + ("OP_NOP72", 0xf7), + ("OP_NOP73", 0xf8), + ("OP_NOP77", 0xfc), + ("OP_SMALLDATA", 0xf9), + ("OP_SMALLINTEGER", 0xfa), + ("OP_PUBKEYS", 0xfb), + ("OP_PUBKEYHASH", 0xfd), + ("OP_PUBKEY", 0xfe), + ("OP_INVALIDOPCODE", 0xff), +] From fdd6975148a23f26f43ce9d209e2d52f30a5e6a0 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:41:18 +0000 Subject: [PATCH 3/4] Check coinbase maturity in full SPV and state where ASM differs from 4.1.1 SPVProofVerifier.verify(_:rootTransactionID:...) now returns false when the walk reaches a proven coinbase (offset 0) less than 100 blocks below the tracker's currentHeight(), as @bsv/sdk Transaction.verify does through MerklePath.verify. The tip is fetched once, only when such a proof is reached. BEEF.verify still checks roots only, like Beef.verify. ChainTracker.currentHeight() now says it must be the real chain tip. ASM in the default TypeScript dialect: - raw data tokens must be lowercase, as @bsv/sdk rejects uppercase; the data token of OP_PUSHDATA* still accepts either case, as @bsv/sdk does - a trailing OP_PUSHDATA1/2/4 (or "OP_PUSHDATA1 0") is an empty push - the OP_PUSHDATA* length must be plain decimal, without leading zeros - docs and COMP-022 no longer say Swift writes exactly what 4.1.1 writes, list where it follows the unmerged @bsv/sdk fixes, and state that the lenient OP_RETURN tail is lossy for malformed pushes Also: the 32-bit push-length guard runs after the truncated-length check, invalidFlags is marked deprecated, legal offsets are only built for levels that hold nodes, and COMP-025 notes that a duplicate's txid bit is not kept. The previous Merkle commit also made applyFee give the change remainder to the last change output. --- Documentation/Compatibility/BRC-Matrix.md | 2 +- Documentation/Compatibility/Rulings.md | 6 +- .../COMP-022-Script-ASM-Normalization.md | 67 +++++++++++--- Sources/BSVSPV/SPVProofVerifier.swift | 52 ++++++++++- Sources/BSVScript/Script.swift | 40 ++++----- Sources/BSVScript/ScriptASM.swift | 89 +++++++++++++------ .../ChainTracking/ChainTracker.swift | 6 ++ .../BSVTransaction/Merkle/MerklePath.swift | 5 +- .../Merkle/MerklePathError.swift | 1 + .../SPVProofConformanceTests.swift | 3 +- Tests/BSVSPVTests/SPVProofVerifierTests.swift | 41 ++++++++- .../ScriptASMTypeScriptTests.swift | 40 ++++++++- 12 files changed, 276 insertions(+), 76 deletions(-) diff --git a/Documentation/Compatibility/BRC-Matrix.md b/Documentation/Compatibility/BRC-Matrix.md index b2d852f..e3a4833 100644 --- a/Documentation/Compatibility/BRC-Matrix.md +++ b/Documentation/Compatibility/BRC-Matrix.md @@ -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. diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 9e9f84f..1340c7e 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -29,12 +29,12 @@ behind the general rule. | COMP-017 | The initial oracle Base58Check operation composes Go SDK Base58 and SHA256d primitives rather than calling a single checked-encoding façade. | Treat the oracle operation as the Bitcoin one-byte-version Base58Check composition only. It does not establish multi-byte version policy or the public error behavior of WIF/address/extended-key Go APIs; the Phase 3 packet must compare those façades directly. | Prevents a composed test adapter from silently defining higher-level compatibility. Pin one known Base58Check value now and use format-specific Go/static vectors before public key-format APIs freeze. | | COMP-018 | Pinned Go SDK call sites use ordinary standard Base64 decoding, which tolerates CR/LF and non-zero discarded bits; Go Base58 rejects forbidden characters but reports a non-indexed error. | Swift Hex accepts ASCII case but otherwise rejects malformed input. Swift Base64 requires canonical encoding, rejects all whitespace including CR/LF, and rejects non-zero discarded bits. Swift Base58 rejects every non-alphabet character with its zero-based UTF-8 byte offset. Every Swift text decoder requires an explicit output maximum. | Deterministic cross-platform parsing and bounded hostile-input handling outweigh permissive decoder parity. Canonical encoders remain interoperable. Test the strict Swift results against the SDK-like non-strict Base64 oracle policy, and verify that both Base58 decoders reject forbidden input while preserving their documented error-detail difference. | | COMP-021 | Go v1.3.3 classifies a one-input transaction with a zero previous hash as coinbase when either the previous-output index or sequence is `0xffffffff`. | Require the consensus null outpoint: one input, zero previous hash, and previous-output index `0xffffffff`; sequence is irrelevant. | Avoids misclassifying an ordinary null-hash input merely because it is finalized. Test non-final coinbase sequence and zero-hash/final-sequence with a non-max index. | -| COMP-022 | Go Script ASM normalizes push encodings, returns empty text for malformed programs, and can silently ignore standalone push-opcode append errors. BRC-106, Go and @bsv/sdk 4.x give conflicting names to the Chronicle and high NOP bytes, so the same text can mean different bytes. | Treat ASM as a bounded semantic form in a named dialect. The default `.typeScript` dialect reads and writes @bsv/sdk 4.1.1 text (its opcode names, `0`/`-1`, odd-length hex, `OP_PUSHDATA* `, `OP_0` for empty pushes, a lenient tail after a top-level OP_RETURN). BRC-106 names with compact BRC-14 SASM, and the Go map, remain selectable. Lowercase pushed-data hex, typed malformed/resource errors, and documented push normalization. | Raw bytes/hex remain the exact serialization. ASM crossing to @bsv/sdk keeps its bytes. Differential tests cover stable Go output; the TypeScript table is pinned against every `OP.ts` name and `Script.test.ts` vectors; Swift tests pin intentional safety differences. | +| COMP-022 | Go Script ASM normalizes push encodings, returns empty text for malformed programs, and can silently ignore standalone push-opcode append errors. BRC-106, Go and @bsv/sdk 4.x give conflicting names to the Chronicle and high NOP bytes, so the same text can mean different bytes. | Treat ASM as a bounded semantic form in a named dialect. The default `.typeScript` dialect reads what @bsv/sdk 4.1.1 `fromASM` reads (its opcode names, `0`/`-1`, lowercase odd-length hex, `OP_PUSHDATA* `) and writes its opcode names; where 4.1.1 `toASM` is not reversible (top-level OP_RETURN, zero-length pushes, empty input) it follows the two unmerged @bsv/sdk fixes (`OP_0` for empty pushes, a named OP_RETURN with a lenient, lossy tail, empty text as the empty script). BRC-106 names with compact BRC-14 SASM, and the Go map, remain selectable. Lowercase pushed-data hex, typed malformed/resource errors, and documented push normalization. | Raw bytes/hex remain the exact serialization. ASM written by Swift keeps its bytes in @bsv/sdk. Default ASM of a malformed OP_RETURN tail is lossy; `style: .canonical` is the strict form. Differential tests cover stable Go output; the TypeScript table is pinned against every `OP.ts` name and `Script.test.ts` vectors; Swift tests pin intentional safety differences. | | COMP-023 | Go v1.3.3 exports `AnyOneCanPayForkID = 0xc0`, which combines two modifier bits but omits the required ALL/NONE/SINGLE base mode. | Swift signing accepts exactly `0x41`, `0x42`, `0x43`, `0xc1`, `0xc2`, and `0xc3`. The incomplete `0xc0` modifier constant is not a valid signature-hash type. | Prevents a default-to-ALL artifact from becoming an ambiguous public signing API. The oracle and Swift raw parser reject every undefined combination; all six valid combinations are differential-tested. | | COMP-024 | Go's fee model uses floating-point rounding, estimates compressed P2PKH unlocks at 106 bytes although non-low-R DER can require 107, can underflow paid fees, divides by zero without change, and exposes an unimplemented random mode. | Swift uses checked integer arithmetic and a safe 107-byte P2PKH maximum, reports overspending/overflow, treats no-change excess as intentional fee, and initially exposes only equal change distribution, giving the division remainder to the last change output as @bsv/sdk does. | Preserves valid Go results for identical explicit projections while preventing rare one-byte underfunding and making hostile/incomplete states typed and nontrapping. Differential tests cover actual and projected sizes; unit tests cover overflow, dust removal, no-change, underfunding, and atomic mutation. | -| COMP-025 | Go's BRC-74 parser truncates oversized block heights, accepts unknown/combined flag bits and trailing bytes, permits zero stored levels, and its implicit root selection uses the first hash rather than a marked transaction ID. | Swift requires a UInt32 block height, nonzero height of at most 64 (BRC-74; @bsv/sdk caps at 54 for JavaScript integers, which Swift does not copy), canonical CompactSize by default, full input consumption, and bounded counts. Flags are read as the bitmask Go and @bsv/sdk use: bit 0 is a duplicate, otherwise bit 1 marks a txid, and other bits are ignored. Like @bsv/sdk, nodes above level zero must be siblings of a level-zero hash's ancestors. `root()` prefers a level-zero `txid` marker, while `root(for:)` is the unambiguous verification API. Like pinned Go, single-level compound paths derive their effective height from the largest level-zero offset, and like @bsv/sdk a single-level path pairs the right-most node of each height with itself when it has no right neighbour. `verify` returns false for a coinbase (offset 0) less than 100 blocks below the tracker's current height, as @bsv/sdk does. | Canonical paths remain byte-compatible while malformed or ambiguous inputs fail predictably instead of truncating, ignoring data, or selecting the wrong proof target. Paths @bsv/sdk writes, including flags 3 and full-block single-level paths with an odd node count, parse and prove the same root. Unit tests cover every truncation, flag bits, limits, offset zero, duplicate markers, illegal upper-level offsets, explicit targets, coinbase maturity, the @bsv/sdk valid and invalid BUMP vectors, and pinned canonical Go differentials, including effective-height root computation. | +| COMP-025 | Go's BRC-74 parser truncates oversized block heights, accepts unknown/combined flag bits and trailing bytes, permits zero stored levels, and its implicit root selection uses the first hash rather than a marked transaction ID. | Swift requires a UInt32 block height, nonzero height of at most 64 (BRC-74; @bsv/sdk caps at 54 for JavaScript integers, which Swift does not copy), canonical CompactSize by default, full input consumption, and bounded counts. Flags are read as the bitmask Go and @bsv/sdk use: bit 0 is a duplicate, otherwise bit 1 marks a txid, and other bits are ignored. Like @bsv/sdk, nodes above level zero must be siblings of a level-zero hash's ancestors. `root()` prefers a level-zero `txid` marker, while `root(for:)` is the unambiguous verification API. Like pinned Go, single-level compound paths derive their effective height from the largest level-zero offset, and like @bsv/sdk a single-level path pairs the right-most node of each height with itself when it has no right neighbour. `verify` returns false for a coinbase (offset 0) less than 100 blocks below the tracker's current height, as @bsv/sdk does. | Canonical paths remain byte-compatible (a duplicate's txid bit is not kept: @bsv/sdk flags 3 is written back as 1) while malformed or ambiguous inputs fail predictably instead of truncating, ignoring data, or selecting the wrong proof target. Paths @bsv/sdk writes, including flags 3 and full-block single-level paths with an odd node count, parse and prove the same root. Unit tests cover every truncation, flag bits, limits, offset zero, duplicate markers, illegal upper-level offsets, explicit targets, coinbase maturity, the @bsv/sdk valid and invalid BUMP vectors, and pinned canonical Go differentials, including effective-height root computation. | | COMP-026 | Go's BEEF readers accept noncanonical CompactSize values, treat any nonzero v1 BUMP-presence byte as true, can panic on an invalid BUMP index, do not require full input consumption, and the generic parser silently unwraps an Atomic BEEF prefix. Its map-backed representation also does not preserve transaction wire order as a public value contract. Pinned Go v1.3.3 does not propagate validity from an unproved txid-only parent to its raw child even when `allowTxidOnly` is true, and vacuously accepts an unproved zero-input raw transaction. | Swift preserves canonical BEEF v1/v2 and Atomic BEEF bytes, requires canonical CompactSize by default, accepts only defined format bytes, bounds every outer and nested count/size, rejects trailing data and invalid proof references, preserves parent-before-child wire order, and exposes `AtomicBEEF` separately so callers cannot accidentally discard the subject. Permissive CompactSize import is explicit. Per BRC-96, transaction-ID-only records become validation anchors only when the caller opts into that trust policy; unproved zero-input raw transactions do not. Atomic validation rejects unrelated transactions and wholly unrelated BUMPs, but permits combined BUMPs to carry additional same-block leaves when the proof supports at least one relevant ancestor. | Canonical SDK envelopes remain wire-compatible while malformed or ambiguous packages fail with typed errors rather than panicking or losing framing information. The BRC-96 validation semantics take precedence over the pinned Go propagation artifact. Combined BUMPs are normal Go output and must not make an otherwise atomic ancestry graph unreadable. Independently authored exact-byte tests cover both versions and Atomic framing; a pinned persistent Go oracle covers decoding, reverse-direction emission, proof-backed validation, transaction-ID-only policy, and the recorded dependent-child divergence. Script execution and chain-tracker root trust remain separate higher-layer verification steps. | -| COMP-027 | Pinned Go `Beef.Verify` asks its chain tracker only about BUMPs containing an explicitly marked txid leaf. A structurally referenced BUMP without the optional marker can therefore make no trust call. Go's synchronous context-aware tracker interface also places concrete trackers beneath `transaction`. | Swift defines a `Sendable`, async `ChainTracker` protocol in `BSVTransaction`, keeps concrete transports in `BSVNetwork`, and computes every level-zero leaf root before verifying every supplied BUMP in deterministic block-height order. Conflicting leaf roots are malformed proof errors; a trusted tracker rejection returns `false`; tracker failures throw. `BSVSPV` exposes the proof-stage façade without claiming script execution. | No supplied inclusion proof can bypass trusted-root validation because of marker metadata or a forged stored internal hash, and network clients can use native Swift concurrency without entering the transaction layer. Pinned Go differentials cover accepted/rejected roots and a conflicting two-marked-leaf BUMP; unit tests cover unmarked paths, deterministic ordering, short-circuiting, and thrown tracker failures. | +| COMP-027 | Pinned Go `Beef.Verify` asks its chain tracker only about BUMPs containing an explicitly marked txid leaf. A structurally referenced BUMP without the optional marker can therefore make no trust call. Go's synchronous context-aware tracker interface also places concrete trackers beneath `transaction`. | Swift defines a `Sendable`, async `ChainTracker` protocol in `BSVTransaction`, keeps concrete transports in `BSVNetwork`, and computes every level-zero leaf root before verifying every supplied BUMP in deterministic block-height order. Conflicting leaf roots are malformed proof errors; a trusted tracker rejection returns `false`; tracker failures throw. `BSVSPV` exposes the proof-stage façade without claiming script execution. Like @bsv/sdk `Beef.verify`, `BEEF.verify` checks roots only and applies no coinbase maturity rule; `MerklePath.verify` and the full `SPVProofVerifier.verify(_:rootTransactionID:...)` (the counterpart of @bsv/sdk `Transaction.verify`) return `false` for a proof at offset zero until the tracker's `currentHeight()` is 100 above its block. | No supplied inclusion proof can bypass trusted-root validation because of marker metadata or a forged stored internal hash, and network clients can use native Swift concurrency without entering the transaction layer. Pinned Go differentials cover accepted/rejected roots and a conflicting two-marked-leaf BUMP; unit tests cover unmarked paths, deterministic ordering, short-circuiting, and thrown tracker failures. | | COMP-028 | Pinned Go preserves v1 when projecting records to txid-only even though v1 cannot serialize that format. Its merge path also leaves an attached BUMP as format 00, and merging parsed txid-only duplicates can replace them with an empty raw transaction because the parser retains a nonnil placeholder object. | Swift txid-only projection always emits valid BRC-96 v2. Immutable merge promotes to v2 when required, keeps txid-only duplicates as txid-only, lets complete raw data replace placeholders, attaches merged proofs as format 01, cross-checks every BUMP leaf root, and emits stable parent-before-child order. Known-ID trimming removes only placeholders and remaps retained BUMP indexes. | These are intentional safety and validity corrections, not wire-format changes for valid envelopes. Pinned-Go semantic summaries record both merge artifacts; Swift unit and differential tests cover proof arrival, version promotion, topological ordering, projection, trimming, index remapping, and forged combined paths. | | COMP-029 | Pinned Go `spv.Verify` accumulates each unproven transaction's input satoshis but never compares the total with its outputs; when no root fee model is supplied, an inflationary or zero-fee transaction can therefore pass the verifier. | Swift resolves every source output and requires input satoshis to be strictly greater than output satoshis for every unproven transaction, as BRC-67 specifies. An optional caller fee model can impose a stronger size-based minimum on the root transaction. Proven transactions remain chain-tracker trust anchors and are not recursively re-executed. | BRC-67 and monetary safety take precedence over the unused-variable artifact. Unit tests cover positive fee, zero fee, inflation, overflow, insufficient root policy, bad source indexes, script failure, and untrusted roots. Pinned-Go differentials cover the shared canonical path and explicitly record Go accepting the inflationary artifact that Swift rejects. | | COMP-030 | Go BRC-42 private derivation discards the error from constructing the child scalar, and Go BRC-94 generation accepts caller-supplied `A` and `S` points without checking that they correspond to private key `a` and counterparty point `B`. Its proof value also permits an arbitrary `big.Int` response until verification. | Swift BRC-42 throws a typed error if the derived scalar is zero. Swift BRC-94 generation accepts only the prover private key and counterparty public key, derives `A` and `S` internally, generates its nonce through P256K/libsecp256k1, and admits only exact 32-byte nonzero responses below the curve order. Verification is nontrapping and returns `false` for failed equations. | Valid wire proofs and child keys remain exactly compatible while structurally inconsistent statements and scalar artifacts are unrepresentable. Unit tests cover role agreement, exact UTF-8 invoice distinctions, malformed responses, nonce freshness, statement/proof tampering, and both proof equations. Persistent pinned-Go tests compare BRC-42 in both directions, verify a deterministic Swift proof in Go, and verify a fresh Go proof in Swift. | diff --git a/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md b/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md index 8e50447..c2bb9a7 100644 --- a/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md +++ b/Documentation/Compatibility/Rulings/COMP-022-Script-ASM-Normalization.md @@ -22,28 +22,63 @@ different SDKs: BRC-106 `OP_NOP4` (0xb6) is 0xb3 in @bsv/sdk, and @bsv/sdk 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 and writes - exactly what @bsv/sdk 4.1.1 `Script.fromASM`/`toASM` read and write: its +- `.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`, - odd-length hexadecimal padded with a leading zero (`3` is the byte 0x03, - and `1` is data, not OP_1), and `OP_PUSHDATA1/2/4 `, which - keeps the named push opcode. Swift requires that length to be the decimal - byte count of the data; @bsv/sdk ignores it. Formatting follows the two - unmerged @bsv/sdk fixes (`cursor/script-op-return-asm-954d`, + 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 + `, 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`, - 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). + 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 crosses to -@bsv/sdk without changing bytes. BRC-106 and Go output remain available by +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 @@ -56,6 +91,12 @@ 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 diff --git a/Sources/BSVSPV/SPVProofVerifier.swift b/Sources/BSVSPV/SPVProofVerifier.swift index b3f72eb..86ec067 100644 --- a/Sources/BSVSPV/SPVProofVerifier.swift +++ b/Sources/BSVSPV/SPVProofVerifier.swift @@ -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. @@ -97,9 +100,31 @@ public enum SPVProofVerifier { var pending = [rootTransactionID] var visited: Set = [] + 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) } @@ -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] diff --git a/Sources/BSVScript/Script.swift b/Sources/BSVScript/Script.swift index 403dc2a..def6802 100644 --- a/Sources/BSVScript/Script.swift +++ b/Sources/BSVScript/Script.swift @@ -110,31 +110,13 @@ public struct Script: Hashable, Sendable { let opcode = Opcode(rawValue: storage[offset]) offset += 1 - let length: Int let lengthByteCount: Int switch opcode.rawValue { - case 0x01...0x4b: - length = Int(opcode.rawValue) - lengthByteCount = 0 - case 0x4c: - lengthByteCount = 1 - length = Int(storage[offset.. ` with the push opcode kept. + /// The token rules of @bsv/sdk 4.1.1 `Script.fromASM`: its opcode table, + /// `0` and `-1`, lowercase hexadecimal with odd lengths padded with a + /// leading zero, and `OP_PUSHDATA1/2/4 ` with the push + /// opcode kept. Swift also requires that length to be the data's byte + /// count, written in plain decimal. case typeScript } extension Script { /// Parses bounded ASM in the selected dialect. /// - /// The default `.typeScript` dialect reads the text @bsv/sdk 4.x writes, - /// so ASM crossing between the SDKs keeps its bytes. `.brc106` reads + /// The default `.typeScript` dialect reads what @bsv/sdk 4.1.1 `fromASM` + /// reads, so ASM written by Swift keeps its bytes in @bsv/sdk. Empty text + /// is an empty script (4.1.1 reads it as `00`). `.brc106` reads /// BRC-106 ASM and compact SASM; `.goSDK` reads the pinned Go SDK's /// names. The dialects disagree on some NOP names, so pick the one that /// wrote the text. Tokens must be separated by exactly one ASCII space. @@ -36,7 +41,9 @@ extension Script { /// Consequently, ASM preserves program meaning but does not preserve a /// non-minimal push opcode choice, except for the `.typeScript` form /// `OP_PUSHDATA1 ` (and its PUSHDATA2/4 forms), whose - /// decimal length must equal the data's byte count. + /// decimal length must equal the data's byte count. A trailing + /// `OP_PUSHDATA1` (or `OP_PUSHDATA1 0`) with no data token is an empty + /// push, as in @bsv/sdk. public init( asm: String, dialect: ScriptASMDialect = .typeScript, @@ -98,27 +105,37 @@ extension Script { } // Only the TypeScript table names push opcodes, and only // OP_PUSHDATA1/2/4: those take a length and a data token. - guard dialect == .typeScript, tokenIndex + 2 < tokens.count else { + guard dialect == .typeScript else { throw ScriptError.pushOpcodeRequiresData(opcode) } - let data = try Self.asmData( - tokens[tokenIndex + 2], - index: tokenIndex + 2, - padsOddLength: true, - maximumByteCount: maximumScriptByteCount - ) - let lengthToken = tokens[tokenIndex + 1] - guard lengthToken.utf8.allSatisfy({ (0x30...0x39).contains($0) }), - Int(lengthToken) == data.count - else { - throw ScriptError.invalidASMPushDataLength(index: tokenIndex + 1) + let data: [UInt8] + if tokenIndex + 2 < tokens.count { + // @bsv/sdk decodes this token without its raw-token + // check, so uppercase hexadecimal is accepted here. + data = try Self.asmData( + tokens[tokenIndex + 2], + index: tokenIndex + 2, + padsOddLength: true, + requiresLowercase: false, + maximumByteCount: maximumScriptByteCount + ) + } else { + // @bsv/sdk reads a missing data token as no data, so a + // trailing `OP_PUSHDATA1` or `OP_PUSHDATA1 0` is `4c00`. + data = [] + } + if tokenIndex + 1 < tokens.count { + let lengthToken = tokens[tokenIndex + 1] + guard lengthToken == String(data.count) else { + throw ScriptError.invalidASMPushDataLength(index: tokenIndex + 1) + } } try result.appendPushData( data, using: opcode, maximumScriptByteCount: maximumScriptByteCount ) - tokenIndex += 3 + tokenIndex += min(3, tokens.count - tokenIndex) continue } @@ -126,6 +143,7 @@ extension Script { token, index: tokenIndex, padsOddLength: padsOddHex, + requiresLowercase: dialect == .typeScript, maximumByteCount: maximumScriptByteCount ) try result.appendPushData(data, maximumScriptByteCount: maximumScriptByteCount) @@ -138,8 +156,14 @@ extension Script { _ token: String, index: Int, padsOddLength: Bool, + requiresLowercase: Bool, maximumByteCount: Int ) throws -> [UInt8] { + // @bsv/sdk re-encodes a raw data token and rejects it unless the + // text is unchanged, so it refuses uppercase hexadecimal. + if requiresLowercase, token.utf8.contains(where: { (0x41...0x46).contains($0) }) { + throw ScriptError.invalidASMToken(index: index) + } let hex = padsOddLength && token.utf8.count % 2 == 1 ? "0" + token : token do { return try Hex.decode(hex, maximumDecodedByteCount: maximumByteCount) @@ -153,13 +177,20 @@ extension Script { /// Formats bounded ASM in the selected style. /// - /// The default `.typeScript` style writes what @bsv/sdk 4.x `toASM` - /// writes. Pushed values are lowercase hexadecimal. Empty non-minimal - /// pushes are normalized to the style's name for OP_0, matching their - /// stack semantics. Malformed pushes are errors, except in the - /// `.typeScript` style after an OP_RETURN outside any conditional, where - /// @bsv/sdk keeps the remaining bytes as data: a truncated push there is - /// written as the bytes that remain. + /// The default `.typeScript` style writes @bsv/sdk 4.1.1 opcode names and + /// follows the unmerged @bsv/sdk fixes where 4.1.1 text cannot be read + /// back (see `ScriptASMStyle.typeScript`). Pushed values are lowercase + /// hexadecimal. Empty non-minimal pushes are normalized to the style's + /// name for OP_0, matching their stack semantics. + /// + /// Malformed pushes are errors, except in the `.typeScript` style after + /// an OP_RETURN outside any conditional, where @bsv/sdk keeps the + /// remaining bytes as data: a truncated push there is written as the + /// bytes that remain, or `OP_0` when none remain. That text is lossy: it + /// reads back as a different, well-formed script (`6a056869` is written + /// `OP_RETURN 6869`, which reads as `6a026869`). Do not use it as a + /// script's identity or as a well-formedness check; `style: .canonical` + /// or `operations(maximumPushDataByteCount:)` reject malformed pushes. public func asm( style: ScriptASMStyle = .typeScript, maximumPushDataByteCount: Int, diff --git a/Sources/BSVTransaction/ChainTracking/ChainTracker.swift b/Sources/BSVTransaction/ChainTracking/ChainTracker.swift index 4a9f2bc..b0919ad 100644 --- a/Sources/BSVTransaction/ChainTracking/ChainTracker.swift +++ b/Sources/BSVTransaction/ChainTracking/ChainTracker.swift @@ -6,5 +6,11 @@ public protocol ChainTracker: Sendable { func isValidRoot(_ root: Hash256, atBlockHeight blockHeight: UInt32) async throws -> Bool /// Returns the tracker's current best-chain height. + /// + /// This must be the real chain tip. `MerklePath.verify` and the full + /// `SPVProofVerifier.verify(_:rootTransactionID:...)` use it for coinbase + /// maturity: a proof at offset zero verifies only when this height is at + /// least 100 above the proof's block. A placeholder height makes every + /// coinbase proof fail (too low) or lets immature ones pass (too high). func currentHeight() async throws -> UInt32 } diff --git a/Sources/BSVTransaction/Merkle/MerklePath.swift b/Sources/BSVTransaction/Merkle/MerklePath.swift index 7b8a209..65c2ab8 100644 --- a/Sources/BSVTransaction/Merkle/MerklePath.swift +++ b/Sources/BSVTransaction/Merkle/MerklePath.swift @@ -473,8 +473,11 @@ public struct MerklePath: Hashable, Sendable { /// `legalOffsetsOnly` rule of @bsv/sdk `MerklePath`. private static func legalOffsets(levels: [[MerklePathElement]]) -> [Set] { var legal = Array(repeating: Set(), count: levels.count) + // Only levels that hold nodes are looked up, so only fill those. + let heights = levels.indices.dropFirst().filter { !levels[$0].isEmpty } + guard !heights.isEmpty else { return legal } for element in levels[0] where !element.isDuplicate { - for height in legal.indices.dropFirst() { + for height in heights { legal[height].insert((element.offset >> height) ^ 1) } } diff --git a/Sources/BSVTransaction/Merkle/MerklePathError.swift b/Sources/BSVTransaction/Merkle/MerklePathError.swift index 5d9bdb0..4387264 100644 --- a/Sources/BSVTransaction/Merkle/MerklePathError.swift +++ b/Sources/BSVTransaction/Merkle/MerklePathError.swift @@ -24,6 +24,7 @@ public enum MerklePathError: Error, Equatable, Sendable { case countNotRepresentable(UInt64) /// Not produced by the parser, which reads flags as a bitmask like /// @bsv/sdk and the Go SDK. Retained for source compatibility. + @available(*, deprecated, message: "No longer thrown; flags are a bitmask") case invalidFlags(level: Int, leaf: Int, flags: UInt8) case duplicateLeafOffset(level: Int, offset: UInt64) case duplicateMarkerRequiresOddOffset(level: Int, offset: UInt64) diff --git a/Tests/BSVConformanceTests/SPVProofConformanceTests.swift b/Tests/BSVConformanceTests/SPVProofConformanceTests.swift index 5df78dd..2dae5e9 100644 --- a/Tests/BSVConformanceTests/SPVProofConformanceTests.swift +++ b/Tests/BSVConformanceTests/SPVProofConformanceTests.swift @@ -355,7 +355,8 @@ private struct ConformanceChainTracker: ChainTracker { } func currentHeight() async throws -> UInt32 { - blockHeight + // Deep enough that a coinbase proof (offset 0) is mature. + blockHeight + 100 } } diff --git a/Tests/BSVSPVTests/SPVProofVerifierTests.swift b/Tests/BSVSPVTests/SPVProofVerifierTests.swift index f28d90d..5fd4547 100644 --- a/Tests/BSVSPVTests/SPVProofVerifierTests.swift +++ b/Tests/BSVSPVTests/SPVProofVerifierTests.swift @@ -51,6 +51,42 @@ struct SPVProofVerifierTests { )) } + @Test("a transaction spending a coinbase verifies only once the coinbase is 100 blocks deep") + func coinbaseMaturity() async throws { + // @bsv/sdk Transaction.ts:1311 verifies every proven ancestor with + // MerklePath.verify, which applies the 100-block rule (MerklePath.ts:510-519). + let fixture = try FullSPVFixture() + #expect(fixture.path.levels[0][0].offset == 0) + let root = try fixture.path.root(for: fixture.parentID) + let height = fixture.path.blockHeight + + let shallow = FixedChainTracker(root: root, blockHeight: height, tipHeight: height + 99) + #expect(!(try await SPVProofVerifier.verify( + fixture.beef, + rootTransactionID: fixture.childID, + using: shallow, + scriptConfiguration: fixture.scriptConfiguration, + limits: fixture.beefLimits + ))) + + let deep = FixedChainTracker(root: root, blockHeight: height, tipHeight: height + 100) + #expect(try await SPVProofVerifier.verify( + fixture.beef, + rootTransactionID: fixture.childID, + using: deep, + scriptConfiguration: fixture.scriptConfiguration, + limits: fixture.beefLimits + )) + + // The proof-stage BEEF check, like @bsv/sdk Beef.verify, has no maturity rule. + #expect(try await SPVProofVerifier.verify( + fixture.beef, + using: shallow, + allowTransactionIDOnly: false, + limits: fixture.transactionLimits + )) + } + @Test("untrusted roots return false before transaction execution") func rejectedRoot() async throws { let fixture = try FullSPVFixture() @@ -433,6 +469,7 @@ private struct FixedFeeModel: TransactionFeeModel { private struct FixedChainTracker: ChainTracker { let root: Hash256 let blockHeight: UInt32 + var tipHeight: UInt32? func isValidRoot( _ candidate: Hash256, @@ -442,7 +479,7 @@ private struct FixedChainTracker: ChainTracker { } func currentHeight() async throws -> UInt32 { - // Deep enough that a coinbase proof (offset 0) is mature. - blockHeight + 100 + // By default deep enough that a coinbase proof (offset 0) is mature. + tipHeight ?? blockHeight + 100 } } diff --git a/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift b/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift index 122fea8..730af40 100644 --- a/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift +++ b/Tests/BSVScriptTests/ScriptASMTypeScriptTests.swift @@ -112,9 +112,23 @@ struct ScriptASMTypeScriptTests { #expect(throws: ScriptError.invalidASMPushDataLength(index: 2)) { try parse("OP_1 OP_PUSHDATA1 0x05 1010101010") } - #expect(throws: ScriptError.pushOpcodeRequiresData(.pushData1)) { + // The length token is the plain decimal byte count: no leading zeros. + #expect(throws: ScriptError.invalidASMPushDataLength(index: 1)) { + try parse("OP_PUSHDATA1 05 1010101010") + } + // @bsv/sdk reads a missing data token as no data (Script.ts:108). + #expect(try parse("OP_PUSHDATA1").hex == "4c00") + #expect(try parse("OP_PUSHDATA1 0").hex == "4c00") + #expect(try parse("OP_1 OP_PUSHDATA2").hex == "514d0000") + // @bsv/sdk returns 4c00 here too; Swift keeps the length-token rule. + #expect(throws: ScriptError.invalidASMPushDataLength(index: 1)) { try parse("OP_PUSHDATA1 5") } + // The data token skips @bsv/sdk's raw-token check, so uppercase is read. + #expect(try parse("OP_PUSHDATA1 2 ABCD").hex == "4c02abcd") + #expect(throws: ScriptError.pushOpcodeRequiresData(.pushData1)) { + try Script(asm: "OP_PUSHDATA1", dialect: .brc106, maximumScriptByteCount: 2, maximumASMByteCount: 12) + } #expect(throws: ScriptError.dataTooLargeForPush(actual: 256)) { try parse("OP_PUSHDATA1 256 " + String(repeating: "00", count: 256)) } @@ -132,6 +146,10 @@ struct ScriptASMTypeScriptTests { // ...and `add` as the bytes 0x0add. #expect(try parse("add").hex == "020add") #expect(throws: ScriptError.invalidASMToken(index: 0)) { try parse("dup") } + // @bsv/sdk re-encodes raw data and rejects uppercase (Script.ts:116). + #expect(throws: ScriptError.invalidASMToken(index: 1)) { try parse("OP_1 ABCD") } + #expect(throws: ScriptError.invalidASMToken(index: 0)) { try parse("abCd") } + #expect(try Script(asm: "ABCD", dialect: .brc106, maximumScriptByteCount: 3, maximumASMByteCount: 4).hex == "02abcd") #expect(throws: ScriptError.invalidASMToken(index: 0)) { try parse("OP_UNKNOWN186") } // BRC-106 keeps rejecting odd-length data. #expect(throws: ScriptError.invalidASMData(index: 0, .oddLength)) { @@ -163,6 +181,11 @@ struct ScriptASMTypeScriptTests { let afterEndIf = try Script(hex: "6368" + "6a0268", maximumByteCount: 5) #expect(try format(afterEndIf) == "OP_IF OP_ENDIF OP_RETURN 68") + // That text is lossy: it reads back as a well-formed push of the + // bytes that remained. `style: .canonical` is the strict check. + #expect(try parse(format(truncated)).hex == "6a026869") + #expect(try parse(format(missingLength)).hex == "6a00") + // Inside a conditional, and in the other styles, malformed pushes stay errors. let inBranch = try Script(hex: "636a0568", maximumByteCount: 4) #expect(throws: ScriptError.truncatedPushData(offset: 2, expected: 5, remaining: 1)) { @@ -179,6 +202,21 @@ struct ScriptASMTypeScriptTests { } } + @Test("where @bsv/sdk 4.1.1 toASM cannot be read back, Swift writes the unmerged fixes' text") + func differencesFromTypeScript411() throws { + // @bsv/sdk 4.1.1 toASM: "OP_0 0568656c6c6f" (drops OP_RETURN; reads back as 00060568656c6c6f). + let opReturn = try Script(hex: "006a0568656c6c6f", maximumByteCount: 8) + #expect(try format(opReturn) == "OP_0 OP_RETURN 68656c6c6f") + // @bsv/sdk 4.1.1 toASM: "" (empty string). + #expect(try format(Script(hex: "6a", maximumByteCount: 1)) == "OP_RETURN") + // @bsv/sdk 4.1.1 toASM: "" (a blank token). + #expect(try format(Script(hex: "4c00", maximumByteCount: 2)) == "OP_0") + // @bsv/sdk 4.1.1 toASM: "OP_0 OP_IF OP_ENDIF OP_1" (two spaces). + #expect(try format(Script(hex: "00634c006851", maximumByteCount: 6)) == "OP_0 OP_IF OP_0 OP_ENDIF OP_1") + // @bsv/sdk 4.1.1 fromASM(""): script 00. + #expect(try parse("").hex == "") + } + @Test("empty text, blank tokens, and zero-length pushes") func emptyForms() throws { // cursor/script-fromasm-empty-09e9, Script.test.ts From 28c9fe0ae8e2f6ece20206e6b1596f3ccc70a2f5 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:44:14 +0000 Subject: [PATCH 4/4] Describe illegalOffset in the Merkle proof error text --- Sources/BSVTransaction/TransactionError+LocalizedError.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/BSVTransaction/TransactionError+LocalizedError.swift b/Sources/BSVTransaction/TransactionError+LocalizedError.swift index d513c39..d177066 100644 --- a/Sources/BSVTransaction/TransactionError+LocalizedError.swift +++ b/Sources/BSVTransaction/TransactionError+LocalizedError.swift @@ -49,7 +49,7 @@ extension MerklePathError: LocalizedError { "The Merkle proof is larger than the wallet can handle." case .blockHeightOutOfRange, .invalidTreeHeight, .invalidFlags, .duplicateLeafOffset, .duplicateMarkerRequiresOddOffset, .transactionIDMarkerOutsideLevelZero, - .offsetOutOfRange, .missingLevelZeroHash, .malformed, .invalidHex, .invalidJSON, + .offsetOutOfRange, .illegalOffset, .missingLevelZeroHash, .malformed, .invalidHex, .invalidJSON, .missingSibling, .conflictingElement: "The Merkle proof could not be read." case .transactionNotInPath: