From 7106a2fccc5d64af2e7ee6b84259f6ada9a146e7 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:28:09 +0000 Subject: [PATCH 1/3] Follow SV Node v1.2.3 Chronicle and signature rules in the interpreter Add the chronicle verification flag, implied by the afterChronicle era, and match SV Node v1.2.3 where the interpreter differed from it: - Splice operands use the node int64 decoding: at most 9 bytes, then saturate to Int32. - LSHIFTNUM and RSHIFTNUM reject shifts the node rejects; a negative right shift rounds toward zero. - The post-Chronicle number limit is 32,000,000 bytes. - SIGHASH_CHRONICLE signatures are verified with the original digest; the ForkID digest is used only when ForkID is enabled. - The original digest serializes script code as the node does after a failed final push, and FindAndDelete removes only exact pushes. - Malleability rules are relaxed for version > 1 transactions under Chronicle. - The alt stack is cleared between scripts. - Public keys are checked for empty signatures. - NULLFAIL covers every failed signature. - Multisig counts are 4-byte numbers. Record the change as COMP-064 and update the Go parity notes. --- Documentation/Compatibility/GoSDK-v1.3.3.md | 7 +- Documentation/Compatibility/Rulings.md | 3 +- .../COMP-023-ForkID-Signature-Hash-Types.md | 4 + ...MP-064-Interpreter-Node-Chronicle-Rules.md | 97 ++ .../ScriptExecutionConfiguration.swift | 41 +- .../BSVInterpreter/ScriptExecutionError.swift | 6 + .../BSVInterpreter/ScriptInterpreter.swift | 10 +- Sources/BSVInterpreter/VM/ScriptMachine.swift | 506 ++++++---- .../BSVTransaction/LegacySignatureHash.swift | 57 +- .../InterpreterReferenceCorpusTests.swift | 10 +- .../NodeConformanceRegressionTests.swift | 864 ++++++++++++++++++ ...erpreterReferenceNumberBoundaryTests.swift | 3 +- .../ScriptInterpreterTests.swift | 39 +- 13 files changed, 1455 insertions(+), 192 deletions(-) create mode 100644 Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md create mode 100644 Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift diff --git a/Documentation/Compatibility/GoSDK-v1.3.3.md b/Documentation/Compatibility/GoSDK-v1.3.3.md index e0a0a08..1af5c54 100644 --- a/Documentation/Compatibility/GoSDK-v1.3.3.md +++ b/Documentation/Compatibility/GoSDK-v1.3.3.md @@ -275,7 +275,7 @@ Public: - `Debugger` lifecycle hooks. - `ScriptNumber`: construction, sign-magnitude bytes, arithmetic/comparisons, integer conversions. - `CheckMinimalDataEncoding`, `MinimallyEncode`, external signature-verifier injection. -- Era/limit constants: pre-Genesis op/stack/script/element/number/pubkey limits and 32 MiB Chronicle number limit. +- Era/limit constants: pre-Genesis op/stack/script/element/number/pubkey limits and 32 MiB Chronicle number limit. Swift uses the SV Node limit of 32,000,000 bytes instead (COMP-064). Edges: EC/hash, script, transaction, sighash, `x/crypto/ripemd160`. @@ -891,7 +891,10 @@ License warning: these live under the Open BSV-licensed upstream. Use the Go ora 5. Era boundaries: - pre-Genesis number length 4 and classic script/stack/op limits, - post-Genesis number ceiling 750,000 bytes, - - post-Chronicle number ceiling 32 MiB, + - post-Chronicle number ceiling 32,000,000 bytes (SV Node + `MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE`; Go uses 32 MiB, see COMP-064), + - post-Chronicle `OP_RSHIFTNUM` rounds a negative value toward zero, as + SV Node does; Go floors it (COMP-064), - Chronicle reactivates/version-gates `VER`, `VERIF`, `VERNOTIF`, `2MUL`, `2DIV`, `SUBSTR`, `LEFT`, `RIGHT`, numeric shifts. 6. Minimal-push is checked at numeric evaluation/policy-dependent points, not indiscriminately for every unevaluated push. 7. Legacy `SIGHASH_SINGLE` out-of-range “hash of 1” bug is consensus. diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 267f8b4..1788d54 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -30,7 +30,7 @@ behind the general rule. | 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-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-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. The interpreter validates Chronicle/OTDA signatures (COMP-064); signing stays ForkID-only. | | 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-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. | @@ -71,6 +71,7 @@ behind the general rule. | COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It validates the exact four-field advertisement, binds it to the requested identifier, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the canonical `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | +| COMP-064 | The interpreter was pinned to Go v1.3.3. TypeScript `@bsv/sdk` 4.1.1 and Go disagree with it on Chronicle splice operands, numeric shifts, the Chronicle number limit (32,000,000 bytes, not 32 MiB), `SIGHASH_CHRONICLE`, malleability relaxation for transaction version above 1, alt-stack clearing, and signature and public-key checks. | Swift follows SV Node v1.2.3 for all of them. It adds `ScriptVerificationFlags.chronicle`, implied by the `.afterChronicle` era, and the consensus failures `illegalChronicle` and `scriptNumberOverflow`. | Script validity is consensus, so the node decides. Where Go differs, Swift no longer matches Go. `NodeConformanceRegressionTests` runs all 21 TypeScript node vectors and a test per rule. See [COMP-064](Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md). | ## Scope decisions diff --git a/Documentation/Compatibility/Rulings/COMP-023-ForkID-Signature-Hash-Types.md b/Documentation/Compatibility/Rulings/COMP-023-ForkID-Signature-Hash-Types.md index dbfb6ce..b3a5fe6 100644 --- a/Documentation/Compatibility/Rulings/COMP-023-ForkID-Signature-Hash-Types.md +++ b/Documentation/Compatibility/Rulings/COMP-023-ForkID-Signature-Hash-Types.md @@ -28,3 +28,7 @@ for all six valid combinations are compared with the pinned Go SDK, and the compressed P2PKH unlocking script is compared byte-for-byte. Unsupported future digest flags require a new explicit API/ruling rather than being silently accepted by this ForkID type. + +Verification is separate. Under the Chronicle flag the interpreter accepts +and checks `SIGHASH_CHRONICLE` signatures with the original digest, as SV +Node does (COMP-064). This type still does not create them. diff --git a/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md new file mode 100644 index 0000000..bb060b8 --- /dev/null +++ b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md @@ -0,0 +1,97 @@ +# COMP-064: Interpreter follows SV Node v1.2.3 Chronicle and signature rules + +## Context + +The interpreter was built against pinned Go SDK v1.3.3. A review against +TypeScript `@bsv/sdk` 4.1.1 found ten places (review items T1 to T10) where +Swift, and in several cases Go, disagree with the TypeScript interpreter. +Script validity is consensus, so the deciding source is the SV Node +implementation, not either SDK. Every item was checked against SV Node v1.2.3 +(`bitcoin-sv` tag `v1.2.3`, commit `6504a3aff65ba97c0f6c80962b033e35ecbfed4b`). +Where TypeScript and the node disagree, Swift follows the node. + +## Ruling + +Swift follows SV Node v1.2.3 for the rules below. References are to +`src/script/interpreter.cpp` unless noted. + +1. **Chronicle flag.** `ScriptVerificationFlags.chronicle` (`1 << 15`) mirrors + `SCRIPT_CHRONICLE`. The `.afterChronicle` era always implies it, and + `.enableForkID` implies `.strictEncoding`, as in the node's standard flags. +2. **Malleability relaxation (T10).** `EnforceNonMalleability` (line 40) is + false only when `.chronicle` is set and the spending transaction's version, + read as a signed 32-bit integer, is greater than 1. Without a transaction + the version is 0. When it is false, MINIMALDATA, MINIMALIF, LOW_S, + NULLFAIL, NULLDUMMY, SIGPUSHONLY and CLEANSTACK are not enforced + (lines 285, 433, 801, 1493, 1643, 1666, 2441). P2SH push-only is not + relaxed. +3. **Splice operands (T1).** `OP_SUBSTR`, `OP_LEFT` and `OP_RIGHT` decode + their numeric operands as the node's `CScriptNum` int64 path does + (line 609): era length check, minimal check, at most 9 bytes + (`scriptNumberOverflow` otherwise), then saturation to `Int32`. +4. **Numeric shifts (T2, T7).** `OP_LSHIFTNUM` and `OP_RSHIFTNUM` + (lines 692 and 728) reject a negative shift and, for a right shift, a + shift above `INT32_MAX`. A right shift of a negative value rounds toward + zero (`BN_rshift` on the magnitude in `big_int.cpp`), so `-3 >> 1 == -1`. + A left shift fails when `current_size + shift / 8` exceeds the number + limit, even for the value 0, and the result size is checked again. +5. **Number limit (T3).** The post-Chronicle script-number limit is + `MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE = 32 * ONE_MEGABYTE` + (`src/consensus/consensus.h:66`), which is 32,000,000 bytes, not 32 MiB. + `ScriptResourceLimits.standard` keeps its separate 32 MiB allocation cap. +6. **Chronicle digest (T4).** Under `.chronicle` a signature may carry + `SIGHASH_CHRONICLE` (`0x20`, `src/script/sighashtype.h:19`). The digest is + BIP143 only when ForkID is enabled, the hash type has ForkID, and it does + not have the Chronicle bit (line 2118). Otherwise the original (OTDA) + digest is used. Without `.chronicle` the Chronicle bit fails with + `illegalChronicle` (line 303). +7. **Hash-type order.** Under STRICTENC the checks run in node order: + defined base type, then illegal ForkID, then illegal Chronicle, then + `MUST_USE_FORKID` when ForkID is enabled and the bit is missing + (line 306). +8. **ForkID digest only with ForkID enabled (T8).** A hash type with the ForkID + bit, verified without `.enableForkID`, uses the original digest. +9. **Original-digest script code (T9).** `SerializeScriptCode` (line 1864) + writes the length minus code separators and the bytes up to where a + failed final push stopped the parser. `FindAndDelete` removes only exact + push encodings of the signature, and applies whenever ForkID is not + enabled or the hash type lacks ForkID (`CleanupScriptCode`, line 255). +10. **Chronicle unlocking script code.** A `CHECKSIG` that runs in the + unlocking script under `.chronicle` signs the unlocking script code + followed by the locking script. +11. **Alt stack (T5).** The alt stack is cleared before each script runs, + so items do not leak from the unlocking script into the locking script + after an early `OP_RETURN`. +12. **Public-key check (T6).** `CheckPubKeyEncoding` runs even for an empty + signature, in `CHECKSIG` and on every `CHECKMULTISIG` comparison. +13. **NULLFAIL.** When enforced, NULLFAIL applies to every non-empty + signature that fails, including one rejected before the ECDSA check + (lines 1489 to 1497). +14. **Multisig counts.** `CHECKMULTISIG` key and signature counts are decoded + as 4-byte script numbers in every era. + +New public consensus failures: `ScriptConsensusFailure.illegalChronicle(UInt8)` +and `ScriptConsensusFailure.scriptNumberOverflow`. + +## Not changed + +- Node also bounds arithmetic results (`OP_ADD`, `OP_MUL` and others) by the + script-number length. Swift bounds them by the push limit. This is outside + T1 to T10 and remains open. +- Signing stays ForkID-only (COMP-023). The interpreter now validates + Chronicle/OTDA signatures, but `ForkIDSignatureHashType` does not create + them. + +## Go difference + +Pinned Go v1.3.3 uses a 32 MiB Chronicle number limit, floors a negative +right shift (`-3 >> 1 == -2`), and does not implement the Chronicle hash type +or the malleability relaxation. Swift no longer matches Go in these cases. The +Go differential case for a negative right shift was removed; the node result +is pinned in `NodeConformanceRegressionTests`. + +## Tests + +`Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift` +runs all 21 TypeScript node-conformance vectors and a test for each item +above. Each test fails on the code before this ruling. diff --git a/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift b/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift index 8f8ff7f..5d3cc01 100644 --- a/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift +++ b/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift @@ -30,6 +30,21 @@ public struct ScriptVerificationFlags: OptionSet, Hashable, Sendable { public static let strictEncoding = Self(rawValue: 1 << 12) public static let bip143SignatureHash = Self(rawValue: 1 << 13) public static let minimalIf = Self(rawValue: 1 << 14) + + /// The spending transaction is validated under Chronicle block rules + /// (SV Node `SCRIPT_CHRONICLE`). + /// + /// This is separate from the ``ScriptExecutionEra``, which describes when + /// the spent output was created: an output created before Chronicle can be + /// spent in a Chronicle block. The flag allows `SIGHASH_CHRONICLE` + /// signatures, appends the locking script to the signature script code of + /// a signature check in the unlocking script, and stops enforcing the + /// malleability rules (`minimalData`, `lowS`, `strictMultiSignatureDummy`, + /// `signaturePushOnly`, `cleanStack`, `minimalIf` and `nullFail`) when the + /// spending transaction's version, read as a signed 32-bit value, is + /// greater than one. ``ScriptExecutionEra/afterChronicle`` always implies + /// this flag. + public static let chronicle = Self(rawValue: 1 << 15) } /// Caller-owned work and memory ceilings. @@ -113,11 +128,27 @@ public struct ScriptExecutionConfiguration: Hashable, Sendable { } self.era = era - self.flags = flags.contains(.enableForkID) - ? flags.union(.strictEncoding) - : flags + var effectiveFlags = flags + if flags.contains(.enableForkID) { + effectiveFlags.insert(.strictEncoding) + } + // An output created after Chronicle can only be spent in a Chronicle block. + if era == .afterChronicle { + effectiveFlags.insert(.chronicle) + } + self.flags = effectiveFlags self.resourceLimits = resourceLimits } + + /// SV Node `EnforceNonMalleability`: the malleability rules apply unless + /// Chronicle rules are active and the spending transaction version, as a + /// signed 32-bit value, is greater than one. Without a transaction the + /// node's checker reports version zero. + package func enforcesNonMalleability(transactionVersion: UInt32?) -> Bool { + guard flags.contains(.chronicle) else { return true } + let version = transactionVersion.map { Int32(bitPattern: $0) } ?? 0 + return version <= 1 + } } package struct ScriptConsensusLimits: Sendable { @@ -151,7 +182,9 @@ package struct ScriptConsensusLimits: Sendable { maximumPushDataByteCount: Int(Int32.max), maximumStackItemCount: Int(Int32.max), maximumOperationCountPerScript: Int(Int32.max), - maximumScriptNumberByteCount: 32 * 1_024 * 1_024 + // SV Node MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE is 32 * ONE_MEGABYTE, + // where ONE_MEGABYTE is 1,000,000 bytes. + maximumScriptNumberByteCount: 32_000_000 ) } } diff --git a/Sources/BSVInterpreter/ScriptExecutionError.swift b/Sources/BSVInterpreter/ScriptExecutionError.swift index 2f4cd0b..1eedf7c 100644 --- a/Sources/BSVInterpreter/ScriptExecutionError.swift +++ b/Sources/BSVInterpreter/ScriptExecutionError.swift @@ -22,6 +22,10 @@ public enum ScriptConsensusFailure: Error, Equatable, Sendable { case invalidSplitPosition(position: Int64, byteCount: Int) case numberTooLarge(actual: Int, maximum: Int) case nonMinimalNumber + /// An operand read as a node int64 Script number (the OP_SUBSTR, OP_LEFT + /// and OP_RIGHT operands) is longer than nine bytes or outside the signed + /// 64-bit range. + case scriptNumberOverflow case impossibleNumericEncoding(targetByteCount: Int, minimumByteCount: Int) case divisionByZero case invalidShiftAmount(Int64) @@ -42,6 +46,8 @@ public enum ScriptConsensusFailure: Error, Equatable, Sendable { case invalidPublicKeyEncoding case invalidSignatureHashType(UInt8) case illegalForkID(UInt8) + /// A `SIGHASH_CHRONICLE` signature outside Chronicle rules under strict encoding. + case illegalChronicle(UInt8) case invalidPublicKeyCount(Int64) case invalidSignatureCount(Int64) case nullDummy diff --git a/Sources/BSVInterpreter/ScriptInterpreter.swift b/Sources/BSVInterpreter/ScriptInterpreter.swift index ac962d8..7967289 100644 --- a/Sources/BSVInterpreter/ScriptInterpreter.swift +++ b/Sources/BSVInterpreter/ScriptInterpreter.swift @@ -29,7 +29,12 @@ public enum ScriptInterpreter { let evaluatesPayToScriptHash = configuration.era == .beforeGenesis && configuration.flags.contains(.payToScriptHash) && lockingScript.isPayToScriptHash - if configuration.flags.contains(.signaturePushOnly) || evaluatesPayToScriptHash { + let enforcesNonMalleability = configuration.enforcesNonMalleability( + transactionVersion: context?.transaction.version + ) + let requiresPushOnly = configuration.flags.contains(.signaturePushOnly) + && enforcesNonMalleability + if requiresPushOnly || evaluatesPayToScriptHash { let isPushOnly = try isPushOnly( unlockingScript, configuration: configuration @@ -85,7 +90,8 @@ public enum ScriptInterpreter { guard let top = finalStack.last else { throw ScriptExecutionError.consensus(.emptyFinalStack) } - if configuration.flags.contains(.cleanStack), finalStack.count != 1 { + if configuration.flags.contains(.cleanStack), enforcesNonMalleability, + finalStack.count != 1 { throw ScriptExecutionError.consensus(.cleanStackViolation( actualItemCount: finalStack.count )) diff --git a/Sources/BSVInterpreter/VM/ScriptMachine.swift b/Sources/BSVInterpreter/VM/ScriptMachine.swift index 38b0ba9..273e3cb 100644 --- a/Sources/BSVInterpreter/VM/ScriptMachine.swift +++ b/Sources/BSVInterpreter/VM/ScriptMachine.swift @@ -15,6 +15,10 @@ package struct ScriptMachine { private let configuration: ScriptExecutionConfiguration private let consensusLimits: ScriptConsensusLimits private let context: ScriptExecutionContext? + /// SV Node `EnforceNonMalleability` for this spend. + private let enforcesNonMalleability: Bool + /// MINIMALDATA after the Chronicle malleability relaxation. + private let requiresMinimalData: Bool private(set) var mainStack: ScriptStack private var altStack: ScriptStack private let debugState: ScriptDebugState? @@ -32,6 +36,12 @@ package struct ScriptMachine { self.configuration = configuration self.context = context consensusLimits = .forEra(configuration.era) + let enforcesNonMalleability = configuration.enforcesNonMalleability( + transactionVersion: context?.transaction.version + ) + self.enforcesNonMalleability = enforcesNonMalleability + requiresMinimalData = configuration.flags.contains(.minimalData) + && enforcesNonMalleability let debugState = debugSession.map(ScriptDebugState.init(session:)) self.debugState = debugState mainStack = ScriptStack(debugState: debugState, debugStack: .main) @@ -40,6 +50,12 @@ package struct ScriptMachine { mutating func execute(_ script: Script, phase: ScriptPhase) throws { try checkScriptSize(script.byteCount) + // SV Node evaluates every script with a fresh alternate stack, so + // nothing left there by an early-returning unlocking script reaches + // the locking script. + if altStack.count > 0 { + altStack.removeAll() + } operationsInCurrentScript = 0 conditions.removeAll(keepingCapacity: true) elseSeen.removeAll(keepingCapacity: true) @@ -98,7 +114,7 @@ package struct ScriptMachine { } if let data = instruction.data { - if configuration.flags.contains(.minimalData), + if requiresMinimalData, !isMinimalPush(opcode: opcode, data: data) { throw ScriptExecutionError.consensus(.nonMinimalPush) } @@ -461,26 +477,7 @@ package struct ScriptMachine { } case Opcode.leftShiftNumber.rawValue, Opcode.rightShiftNumber.rawValue: if configuration.era == .afterChronicle { - let shift = try popNativeNumber() - guard shift >= 0 else { - throw ScriptExecutionError.consensus(.invalidShiftAmount(shift)) - } - let value = try popScriptNumber() - let consensusMaximumBits = 32 * 1_024 * 1_024 * 8 - let boundedShift = min(shift, Int64(consensusMaximumBits)) - let shifted = try performBigNumberOperation { budget in - if opcode == .rightShiftNumber { - return try value.value.shiftedRight( - by: Int(boundedShift), - budget: budget - ) - } - return try value.value.shiftedLeft( - by: Int(boundedShift), - budget: budget - ) - } - try pushScriptNumber(shifted) + try executeNumericShift(opcode) break } if configuration.flags.contains(.discourageUpgradeableNops) { @@ -572,7 +569,7 @@ package struct ScriptMachine { let state: ConditionalState if outerExecuting, mayEvaluateCondition { let encoded = try mainStack.pop() - if configuration.flags.contains(.minimalIf), + if configuration.flags.contains(.minimalIf), enforcesNonMalleability, encoded != [] && encoded != [1] { throw ScriptExecutionError.consensus(.minimalIf) } @@ -689,7 +686,7 @@ package struct ScriptMachine { consensusLimits.maximumScriptNumberByteCount, configuration.resourceLimits.maximumScriptNumberByteCount ), - requireMinimal: configuration.flags.contains(.minimalData) + requireMinimal: requiresMinimalData ) } catch ScriptNumberError.nonMinimalEncoding { throw ScriptExecutionError.consensus(.nonMinimalNumber) @@ -698,6 +695,71 @@ package struct ScriptMachine { } } + /// Reads a CHECKMULTISIG key or signature count. SV Node parses both with + /// `CScriptNum::MAXIMUM_ELEMENT_SIZE` (four bytes) in every era. + private mutating func popCountNumber() throws -> Int64 { + let encoded = try mainStack.pop() + let maximum = ScriptNumber.beforeGenesisMaximumByteCount + guard encoded.count <= maximum else { + throw ScriptExecutionError.consensus(.numberTooLarge( + actual: encoded.count, + maximum: maximum + )) + } + do { + return try ScriptNumber( + encoded: encoded, + maximumByteCount: maximum, + requireMinimal: requiresMinimalData + ).int64Clamped() + } catch ScriptNumberError.nonMinimalEncoding { + throw ScriptExecutionError.consensus(.nonMinimalNumber) + } catch let error as ScriptNumberError { + throw ScriptExecutionError.scriptNumber(error) + } + } + + /// Reads an OP_SUBSTR, OP_LEFT or OP_RIGHT operand the way SV Node v1.2.3 + /// does (`CScriptNum` without big-integer mode, `deserialize` + /// and `getint()`): the era length limit, the minimal-encoding check, a + /// nine-byte ceiling, the signed 64-bit range, then saturation to Int32. + private mutating func popSpliceOperand() throws -> Int64 { + let encoded = try mainStack.pop() + try checkNumberSize(encoded.count) + if requiresMinimalData, !ScriptNumber.isMinimallyEncoded(encoded) { + throw ScriptExecutionError.consensus(.nonMinimalNumber) + } + guard let last = encoded.last else { return 0 } + guard encoded.count <= 9 else { + throw ScriptExecutionError.consensus(.scriptNumberOverflow) + } + let isNegative = last & 0x80 != 0 + var magnitude: UInt64 = 0 + if encoded.count == 9 { + // The ninth byte may only carry the sign. + guard last & 0x7f == 0 else { + throw ScriptExecutionError.consensus(.scriptNumberOverflow) + } + for (index, byte) in encoded.prefix(8).enumerated() { + magnitude |= UInt64(byte) << (8 * index) + } + } else { + for (index, byte) in encoded.enumerated() { + let digit = index == encoded.count - 1 ? byte & 0x7f : byte + magnitude |= UInt64(digit) << (8 * index) + } + } + let value: Int64 + if magnitude <= UInt64(Int64.max) { + value = isNegative ? -Int64(magnitude) : Int64(magnitude) + } else if isNegative, magnitude == UInt64(Int64.max) + 1 { + value = .min + } else { + throw ScriptExecutionError.consensus(.scriptNumberOverflow) + } + return min(max(value, Int64(Int32.min)), Int64(Int32.max)) + } + private func checkNumberSize(_ count: Int) throws { if count > consensusLimits.maximumScriptNumberByteCount { throw ScriptExecutionError.consensus(.numberTooLarge( @@ -845,10 +907,54 @@ package struct ScriptMachine { return result } + /// OP_LSHIFTNUM and OP_RSHIFTNUM as SV Node v1.2.3 evaluates them with + /// big Script numbers (`CScriptNum::operator<<=` and `operator>>=`). + private mutating func executeNumericShift(_ opcode: Opcode) throws { + let shift = try popScriptNumber() + guard !shift.isNegative else { + throw ScriptExecutionError.consensus(.invalidShiftAmount(shift.int64Clamped())) + } + let value = try popScriptNumber() + let shiftCount = shift.int64Clamped() + + if opcode == .rightShiftNumber { + // `bsv::bint::operator>>=` rejects a count above INT_MAX. + guard shiftCount <= Int64(Int32.max) else { + throw ScriptExecutionError.consensus(.invalidShiftAmount(shiftCount)) + } + // OpenSSL BN_rshift shifts the magnitude and keeps the sign, so a + // negative value rounds toward zero: -3 >> 1 is -1, -1 >> 1 is 0. + let magnitude = value.value.magnitude + guard shiftCount < Int64(magnitude.bitWidth) else { + mainStack.push([]) + return + } + let shifted = try performBigNumberOperation { budget in + try magnitude.shiftedRight(by: Int(shiftCount), budget: budget) + } + try pushScriptNumber(BigSigned(sign: value.value.sign, magnitude: shifted)) + return + } + + // The node rejects the shift when the operand's minimal size plus the + // whole bytes shifted exceeds the era number limit, whatever the + // value, and again when the shifted result is too large. + let bitWidth = value.value.magnitude.bitWidth + let currentSize = bitWidth == 0 ? 0 : bitWidth / 8 + 1 + let projectedSize = Int64(currentSize) + shiftCount / 8 + try checkNumberSize(Int(clamping: projectedSize)) + let shifted = try performBigNumberOperation { budget in + try value.value.shiftedLeft(by: Int(shiftCount), budget: budget) + } + let shiftedWidth = shifted.magnitude.bitWidth + try checkNumberSize(shiftedWidth == 0 ? 0 : shiftedWidth / 8 + 1) + try pushScriptNumber(shifted) + } + private mutating func executeAfterChronicleSlice(_ opcode: Opcode) throws { - let length = try popNativeNumber() + let length = try popSpliceOperand() if opcode == .substring { - let offset = try popNativeNumber() + let offset = try popSpliceOperand() let data = try mainStack.pop() guard offset >= 0, length >= 0, offset < Int64(data.count), @@ -887,26 +993,24 @@ package struct ScriptMachine { try mainStack.require(2) let publicKeyBytes = try mainStack.pop() let signatureWithHashType = try mainStack.pop() - guard let rawHashType = signatureWithHashType.last else { - return false - } - try checkHashTypeEncoding(rawHashType) - let signatureBytes = Array(signatureWithHashType.dropLast()) - let signature = try parseScriptSignature(signatureBytes) + // SV Node checks the signature encoding (an empty signature passes) + // and then the public-key encoding before it checks the signature. + let signature = try checkSignatureEncoding(signatureWithHashType) try checkPublicKeyEncoding(publicKeyBytes) - guard let signature else { return false } - guard let publicKey = try? PublicKey(publicKeyBytes) else { return false } + guard let rawHashType = signatureWithHashType.last, + let signature, + let publicKey = try? PublicKey(publicKeyBytes) + else { + return try signatureFailure(signatureWithHashType) + } - var transaction = context.transaction - transaction.inputs[context.inputIndex].sourceOutput = context.spentOutput - let cleansLegacyScript = !configuration.flags.contains(.enableForkID) - || rawHashType & ForkIDSignatureHashType.forkIDMask == 0 - let scriptCode = try signatureScriptCode( + let transaction = signingTransaction(context) + let scriptCode = signatureScriptCode( script: script, phase: phase, codeSeparatorOffset: codeSeparatorOffset, - signaturesToRemove: cleansLegacyScript ? [signatureWithHashType] : [] + signatures: [signatureWithHashType] ) let digest = try signatureDigest( transaction: transaction, @@ -914,8 +1018,9 @@ package struct ScriptMachine { rawHashType: rawHashType, scriptCode: scriptCode ) - let valid = signature.verifiesInScript(publicKey: publicKey, digest: digest) - if !valid { return try signatureFailure(signatureBytes) } + guard signature.verifiesInScript(publicKey: publicKey, digest: digest) else { + return try signatureFailure(signatureWithHashType) + } return true } @@ -935,7 +1040,7 @@ package struct ScriptMachine { throw ScriptExecutionError.missingExecutionContext(opcode: opcode) } - let rawPublicKeyCount = try popNativeNumber() + let rawPublicKeyCount = try popCountNumber() let maximumPublicKeys = configuration.era == .beforeGenesis ? 20 : Int64(Int32.max) guard rawPublicKeyCount >= 0, rawPublicKeyCount <= maximumPublicKeys else { throw ScriptExecutionError.consensus(.invalidPublicKeyCount(rawPublicKeyCount)) @@ -947,7 +1052,7 @@ package struct ScriptMachine { publicKeys.reserveCapacity(publicKeyCount) for _ in 0..= 0, rawSignatureCount <= rawPublicKeyCount else { throw ScriptExecutionError.consensus(.invalidSignatureCount(rawSignatureCount)) } @@ -959,26 +1064,18 @@ package struct ScriptMachine { signatures.append(MultiSignatureInfo(bytes: try mainStack.pop())) } let dummy = try mainStack.pop() - if configuration.flags.contains(.strictMultiSignatureDummy), !dummy.isEmpty { + if configuration.flags.contains(.strictMultiSignatureDummy), enforcesNonMalleability, + !dummy.isEmpty { throw ScriptExecutionError.consensus(.nullDummy) } - let signaturesToRemove = signatures.compactMap { info -> [UInt8]? in - let hasForkID = info.bytes.last.map { - $0 & ForkIDSignatureHashType.forkIDMask != 0 - } ?? false - return !configuration.flags.contains(.enableForkID) || !hasForkID - ? info.bytes - : nil - } - let scriptCode = try signatureScriptCode( + let scriptCode = signatureScriptCode( script: script, phase: phase, codeSeparatorOffset: codeSeparatorOffset, - signaturesToRemove: signaturesToRemove + signatures: signatures.map(\.bytes) ) - var transaction = context.transaction - transaction.inputs[context.inputIndex].sourceOutput = context.spentOutput + let transaction = signingTransaction(context) var remainingSignatures = signatureCount // The early-impossibility check counts the key selected in the current @@ -999,18 +1096,18 @@ package struct ScriptMachine { let rawSignature = signatures[signatureIndex].bytes let publicKeyBytes = publicKeys[publicKeyIndex] publicKeyIndex += 1 - guard let rawHashType = rawSignature.last else { continue } + // The node checks both encodings on every comparison, including + // for an empty signature. if !signatures[signatureIndex].didParse { - try checkHashTypeEncoding(rawHashType) - signatures[signatureIndex].parsed = try parseScriptSignature( - Array(rawSignature.dropLast()) - ) + signatures[signatureIndex].parsed = try checkSignatureEncoding(rawSignature) signatures[signatureIndex].didParse = true } - guard let signature = signatures[signatureIndex].parsed else { continue } try checkPublicKeyEncoding(publicKeyBytes) - guard let publicKey = try? PublicKey(publicKeyBytes) else { continue } + guard let rawHashType = rawSignature.last, + let signature = signatures[signatureIndex].parsed, + let publicKey = try? PublicKey(publicKeyBytes) + else { continue } let digest: Hash256 if let cached = cachedDigests[rawHashType] { @@ -1030,59 +1127,65 @@ package struct ScriptMachine { } } - if !success, configuration.flags.contains(.nullFail), + if !success, configuration.flags.contains(.nullFail), enforcesNonMalleability, signatures.contains(where: { !$0.bytes.isEmpty }) { throw ScriptExecutionError.consensus(.nullFail) } return success } - private func checkHashTypeEncoding(_ rawHashType: UInt8) throws { - guard configuration.flags.contains(.strictEncoding) else { return } - var normalized = rawHashType & ~ForkIDSignatureHashType.anyoneCanPayMask - if configuration.flags.contains(.bip143SignatureHash) { - normalized ^= ForkIDSignatureHashType.forkIDMask - guard rawHashType & ForkIDSignatureHashType.forkIDMask != 0 else { - throw ScriptExecutionError.consensus(.invalidSignatureHashType(rawHashType)) - } - } - if normalized & ForkIDSignatureHashType.forkIDMask == 0 { - guard (1...3).contains(normalized) else { - throw ScriptExecutionError.consensus(.invalidSignatureHashType(rawHashType)) - } - return - } - guard (0x41...0x43).contains(normalized) else { - throw ScriptExecutionError.consensus(.invalidSignatureHashType(rawHashType)) - } - let hasForkID = rawHashType & ForkIDSignatureHashType.forkIDMask != 0 - guard configuration.flags.contains(.enableForkID) == hasForkID else { - throw ScriptExecutionError.consensus(.illegalForkID(rawHashType)) - } - } - - private func parseScriptSignature(_ bytes: [UInt8]) throws -> ECDSASignature? { + /// SV Node `CheckSignatureEncoding`: DER, then low S, then the hash type. + /// Returns the parsed signature, or `nil` for an empty signature or one + /// that does not parse when no DER rule applies. + private func checkSignatureEncoding(_ signatureWithHashType: [UInt8]) throws -> ECDSASignature? { + guard let rawHashType = signatureWithHashType.last else { return nil } let requiresStrictDER = configuration.flags.contains(.strictEncoding) || configuration.flags.contains(.derSignatures) || configuration.flags.contains(.lowS) - let signature: ECDSASignature + var signature: ECDSASignature? do { signature = try ECDSASignature( - scriptBytes: bytes, + scriptBytes: Array(signatureWithHashType.dropLast()), strict: requiresStrictDER ) } catch { if requiresStrictDER { throw ScriptExecutionError.consensus(.invalidSignatureEncoding) } - return nil + signature = nil } - if configuration.flags.contains(.lowS), !signature.isLowS { + if configuration.flags.contains(.lowS), enforcesNonMalleability, + let signature, !signature.isLowS { throw ScriptExecutionError.consensus(.invalidSignatureEncoding) } + try checkHashTypeEncoding(rawHashType) return signature } + /// SV Node `CheckSignatureEncoding` hash-type rules under STRICTENC. + private func checkHashTypeEncoding(_ rawHashType: UInt8) throws { + guard configuration.flags.contains(.strictEncoding) else { return } + let hasForkID = rawHashType & Self.forkIDBit != 0 + let hasChronicle = rawHashType & Self.chronicleBit != 0 + if configuration.flags.contains(.bip143SignatureHash), !hasForkID { + throw ScriptExecutionError.consensus(.invalidSignatureHashType(rawHashType)) + } + let baseType = rawHashType & ~(Self.chronicleBit | Self.forkIDBit | Self.anyoneCanPayBit) + guard (1...3).contains(baseType) else { + throw ScriptExecutionError.consensus(.invalidSignatureHashType(rawHashType)) + } + let forkIDEnabled = configuration.flags.contains(.enableForkID) + if !forkIDEnabled, hasForkID { + throw ScriptExecutionError.consensus(.illegalForkID(rawHashType)) + } + if !configuration.flags.contains(.chronicle), hasChronicle { + throw ScriptExecutionError.consensus(.illegalChronicle(rawHashType)) + } + if forkIDEnabled, !hasForkID { + throw ScriptExecutionError.consensus(.illegalForkID(rawHashType)) + } + } + private func checkPublicKeyEncoding(_ bytes: [UInt8]) throws { guard configuration.flags.contains(.strictEncoding) else { return } let compressed = bytes.count == 33 && (bytes[0] == 0x02 || bytes[0] == 0x03) @@ -1092,25 +1195,46 @@ package struct ScriptMachine { } } + private static let chronicleBit: UInt8 = 0x20 + private static let forkIDBit: UInt8 = ForkIDSignatureHashType.forkIDMask + private static let anyoneCanPayBit: UInt8 = ForkIDSignatureHashType.anyoneCanPayMask + + private func signingTransaction(_ context: ScriptExecutionContext) -> Transaction { + var transaction = context.transaction + transaction.inputs[context.inputIndex].sourceOutput = context.spentOutput + return transaction + } + + /// SV Node `SignatureHash`: the BIP143 digest only when ForkID is enabled + /// and the hash type has FORKID without CHRONICLE; otherwise the original + /// transaction digest (OTDA) over the node's script-code walk. private func signatureDigest( transaction: Transaction, context: ScriptExecutionContext, rawHashType: UInt8, - scriptCode: Script + scriptCode: [UInt8] ) throws -> Hash256 { + let usesBIP143 = configuration.flags.contains(.enableForkID) + && rawHashType & Self.forkIDBit != 0 + && rawHashType & Self.chronicleBit == 0 do { - if rawHashType & ForkIDSignatureHashType.forkIDMask != 0 { + if usesBIP143 { return try transaction.forkIDSignatureHash( inputIndex: context.inputIndex, rawHashType: rawHashType, - scriptCode: scriptCode, + scriptCode: try Script( + bytes: scriptCode, + maximumByteCount: configuration.resourceLimits.maximumScriptByteCount + ), limits: context.transactionLimits ) } + let original = Self.originalDigestScriptCode(scriptCode) return try transaction.legacySignatureHash( inputIndex: context.inputIndex, rawHashType: rawHashType, - scriptCode: scriptCode, + scriptCodeBytes: original.bytes, + encodedScriptCodeLength: original.encodedLength, limits: context.transactionLimits ) } catch let error as TransactionError { @@ -1118,58 +1242,138 @@ package struct ScriptMachine { } } + /// The script code a signature commits to, before digest-specific + /// serialization: the current script from the last OP_CODESEPARATOR, + /// followed under Chronicle rules by the locking script when the check + /// runs in the unlocking script, with each signature removed by + /// `FindAndDelete` unless ForkID is enabled and that signature uses it + /// (SV Node `CleanupScriptCode`). private func signatureScriptCode( script: Script, phase: ScriptPhase, codeSeparatorOffset: Int, - signaturesToRemove: [[UInt8]] - ) throws -> Script { - let bytes = Array(script.bytes[codeSeparatorOffset...]) - guard !signaturesToRemove.isEmpty else { - return try Script( - bytes: bytes, - maximumByteCount: configuration.resourceLimits.maximumScriptByteCount - ) + signatures: [[UInt8]] + ) -> [UInt8] { + var bytes = Array(script.bytes[codeSeparatorOffset...]) + if phase == .unlocking, configuration.flags.contains(.chronicle), let context { + bytes += context.spentOutput.lockingScript.bytes } + let forkIDEnabled = configuration.flags.contains(.enableForkID) + for signature in signatures { + let hasForkID = (signature.last ?? 0) & Self.forkIDBit != 0 + guard !forkIDEnabled || !hasForkID else { continue } + bytes = Self.findAndDelete(bytes, pattern: Self.pushEncoding(signature)) + } + return bytes + } + /// `CScript(vchSig)`: the data push SV Node builds for `FindAndDelete`. + static func pushEncoding(_ data: [UInt8]) -> [UInt8] { + let count = data.count + var result: [UInt8] + if count < Int(Opcode.pushData1.rawValue) { + result = [UInt8(count)] + } else if count <= 0xff { + result = [Opcode.pushData1.rawValue, UInt8(count)] + } else if count <= 0xffff { + result = [Opcode.pushData2.rawValue, + UInt8(truncatingIfNeeded: count), + UInt8(truncatingIfNeeded: count >> 8)] + } else { + result = [Opcode.pushData4.rawValue, + UInt8(truncatingIfNeeded: count), + UInt8(truncatingIfNeeded: count >> 8), + UInt8(truncatingIfNeeded: count >> 16), + UInt8(truncatingIfNeeded: count >> 24)] + } + result += data + return result + } + + /// SV Node `CScript::GetOp2` over raw bytes. Returns the opcode, or `nil` + /// at the end or on a truncated push; on a truncated push `position` is + /// left where the node leaves it (after the opcode and any complete + /// length field). + private static func nodeNextOpcode(_ bytes: [UInt8], _ position: inout Int) -> UInt8? { + guard position < bytes.count else { return nil } + let opcode = bytes[position] + position += 1 + guard opcode <= Opcode.pushData4.rawValue else { return opcode } + var size = 0 + switch opcode { + case Opcode.pushData1.rawValue: + guard bytes.count - position >= 1 else { return nil } + size = Int(bytes[position]) + position += 1 + case Opcode.pushData2.rawValue: + guard bytes.count - position >= 2 else { return nil } + size = Int(bytes[position]) | Int(bytes[position + 1]) << 8 + position += 2 + case Opcode.pushData4.rawValue: + guard bytes.count - position >= 4 else { return nil } + size = Int(bytes[position]) + | Int(bytes[position + 1]) << 8 + | Int(bytes[position + 2]) << 16 + | Int(bytes[position + 3]) << 24 + position += 4 + default: + size = Int(opcode) + } + guard bytes.count - position >= size else { return nil } + position += size + return opcode + } + + /// SV Node `CScript::FindAndDelete`: removes every occurrence of + /// `pattern` that starts at an instruction boundary. A truncated final + /// instruction ends the walk and its bytes are kept. + static func findAndDelete(_ bytes: [UInt8], pattern: [UInt8]) -> [UInt8] { + guard !pattern.isEmpty else { return bytes } var result: [UInt8] = [] - result.reserveCapacity(bytes.count) - var offset = 0 - while offset < bytes.count { - let start = offset - let instruction = try ScriptInstructionDecoder.next( - bytes: bytes, - offset: &offset, - phase: phase, - maximumConsensusPushByteCount: consensusLimits.maximumPushDataByteCount, - maximumResourcePushByteCount: configuration.resourceLimits.maximumPushDataByteCount - ) - if instruction.opcode == .codeSeparator { continue } - let candidate = instruction.data ?? [] - let removesInstruction = isCanonicalSignatureRemovalCandidate(instruction) - && signaturesToRemove.contains { candidate.containsSubsequence($0) } - if !removesInstruction { result.append(contentsOf: bytes[start..= pattern.count, + bytes[position..<(position + pattern.count)].elementsEqual(pattern) { + position += pattern.count + found += 1 + } + kept = position + } while nodeNextOpcode(bytes, &position) != nil + guard found > 0 else { return bytes } + result += bytes[kept...] + return result } - private func isCanonicalSignatureRemovalCandidate( - _ instruction: DecodedScriptInstruction - ) -> Bool { - let opcode = instruction.opcode.rawValue - let data = instruction.data ?? [] - if opcode > Opcode.sixteen.rawValue { return true } - if opcode > Opcode.zero.rawValue, opcode < Opcode.pushData1.rawValue, - data.count == 1, data[0] <= 16 { return false } - if opcode == Opcode.pushData1.rawValue, data.count < Int(Opcode.pushData1.rawValue) { - return false - } - if opcode == Opcode.pushData2.rawValue, data.count <= 0xff { return false } - if opcode == Opcode.pushData4.rawValue, data.count <= 0xffff { return false } - return true + /// SV Node `CTransactionSignatureSerializer::SerializeScriptCode`: drops + /// every OP_CODESEPARATOR found by the instruction walk, stops at a + /// truncated push after writing what the walk consumed, and declares the + /// script size minus the separators found as the CompactSize length. + static func originalDigestScriptCode( + _ bytes: [UInt8] + ) -> (bytes: [UInt8], encodedLength: Int) { + var position = 0 + var separators = 0 + while let opcode = nodeNextOpcode(bytes, &position) { + if opcode == Opcode.codeSeparator.rawValue { separators += 1 } + } + + var result: [UInt8] = [] + result.reserveCapacity(bytes.count) + position = 0 + var segmentStart = 0 + while let opcode = nodeNextOpcode(bytes, &position) { + if opcode == Opcode.codeSeparator.rawValue { + result += bytes[segmentStart..<(position - 1)] + segmentStart = position + } + } + if segmentStart != bytes.count { + result += bytes[segmentStart.. Bool { - if configuration.flags.contains(.nullFail), !nonemptySignature.isEmpty { + /// NULLFAIL applies to the whole signature element, hash-type byte included. + private func signatureFailure(_ signatureWithHashType: [UInt8]) throws -> Bool { + if configuration.flags.contains(.nullFail), enforcesNonMalleability, + !signatureWithHashType.isEmpty { throw ScriptExecutionError.consensus(.nullFail) } return false @@ -1347,17 +1553,3 @@ package struct ScriptMachine { } } } - -private extension Array where Element == UInt8 { - func containsSubsequence(_ needle: [UInt8]) -> Bool { - guard !needle.isEmpty else { return true } - guard needle.count <= count else { return false } - if needle.count == count { return self == needle } - for start in 0...(count - needle.count) { - if self[start..<(start + needle.count)].elementsEqual(needle) { - return true - } - } - return false - } -} diff --git a/Sources/BSVTransaction/LegacySignatureHash.swift b/Sources/BSVTransaction/LegacySignatureHash.swift index 623435f..5d59f26 100644 --- a/Sources/BSVTransaction/LegacySignatureHash.swift +++ b/Sources/BSVTransaction/LegacySignatureHash.swift @@ -95,6 +95,29 @@ public extension Transaction { return Self.digestLegacySignatureMaterial(material) } + /// Returns the legacy digest over script-code bytes whose declared + /// CompactSize length may differ from the bytes written. + /// + /// SV Node's original digest declares the script size minus its + /// OP_CODESEPARATORs but writes only the bytes its instruction walk + /// consumed, so a truncated final push yields fewer bytes than declared. + /// The interpreter computes that walk and passes both values here. + package func legacySignatureHash( + inputIndex: Int, + rawHashType: UInt8, + scriptCodeBytes: [UInt8], + encodedScriptCodeLength: Int, + limits: TransactionLimits + ) throws -> Hash256 { + let material = try legacySignatureMaterial( + inputIndex: inputIndex, + rawHashType: rawHashType, + committedScript: (scriptCodeBytes, encodedScriptCodeLength), + limits: limits + ) + return Self.digestLegacySignatureMaterial(material) + } + private static func digestLegacySignatureMaterial( _ material: LegacySignatureMaterial ) -> Hash256 { @@ -129,12 +152,33 @@ public extension Transaction { guard let sourceOutput = inputs[inputIndex].sourceOutput else { throw TransactionError.missingSourceOutput(inputIndex: inputIndex) } + let committedScript = scriptCode ?? sourceOutput.lockingScript + return try legacySignatureMaterial( + inputIndex: inputIndex, + rawHashType: rawHashType, + committedScript: (committedScript.bytes, committedScript.byteCount), + limits: limits + ) + } + + private func legacySignatureMaterial( + inputIndex: Int, + rawHashType: UInt8, + committedScript: (bytes: [UInt8], encodedLength: Int), + limits: TransactionLimits + ) throws -> LegacySignatureMaterial { + guard inputs.indices.contains(inputIndex) else { + throw TransactionError.invalidInputIndex(inputIndex) + } + guard inputs[inputIndex].sourceOutput != nil else { + throw TransactionError.missingSourceOutput(inputIndex: inputIndex) + } _ = try serializedByteCount(limits: limits) - let committedScript = scriptCode ?? sourceOutput.lockingScript - guard UInt64(committedScript.byteCount) <= limits.maximumScriptByteCount else { + let committedByteCount = max(committedScript.bytes.count, committedScript.encodedLength) + guard UInt64(committedByteCount) <= limits.maximumScriptByteCount else { throw TransactionError.scriptTooLarge( - actual: UInt64(committedScript.byteCount), + actual: UInt64(committedByteCount), maximum: limits.maximumScriptByteCount ) } @@ -157,7 +201,12 @@ public extension Transaction { for index in inputIndices { let input = inputs[index] writer.write(input.previousOutput.wireBytes) - writer.writeVarBytes(index == inputIndex ? committedScript.bytes : []) + if index == inputIndex { + writer.writeCompactSize(UInt64(committedScript.encodedLength)) + writer.write(committedScript.bytes) + } else { + writer.writeVarBytes([]) + } let sequence = outputMode != .all && index != inputIndex ? UInt32.zero : input.sequence diff --git a/Tests/BSVConformanceTests/InterpreterReferenceCorpusTests.swift b/Tests/BSVConformanceTests/InterpreterReferenceCorpusTests.swift index e82e6f8..959f997 100644 --- a/Tests/BSVConformanceTests/InterpreterReferenceCorpusTests.swift +++ b/Tests/BSVConformanceTests/InterpreterReferenceCorpusTests.swift @@ -880,13 +880,9 @@ private func generatedDifferentialCases() -> [InterpreterGeneratedCase] { Opcode.right.rawValue, 2, 0x63, 0x64, Opcode.equal.rawValue], era: .afterChronicle ), - .init( - name: "after-chronicle-arithmetic-right-shift", - locking: [Opcode.three.rawValue, Opcode.negate.rawValue, - Opcode.one.rawValue, Opcode.rightShiftNumber.rawValue, - 1, 0x82, Opcode.equal.rawValue], - era: .afterChronicle - ), + // OP_RSHIFTNUM on a negative value is left out: pinned Go v1.3.3 + // floors (-3 >> 1 == -2) while SV Node rounds toward zero. The node + // result is pinned in NodeConformanceRegressionTests. ] } diff --git a/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift new file mode 100644 index 0000000..d992f0f --- /dev/null +++ b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift @@ -0,0 +1,864 @@ +@testable import BSVInterpreter +import BSVCore +import BSVCrypto +import BSVKeys +import BSVScript +import BSVTransaction +import Testing + +/// SV Node v1.2.3 script rules that the pinned Go SDK v1.3.3 does not follow. +/// +/// Transaction vectors come from TypeScript `@bsv/sdk` 4.1.1 +/// `packages/sdk/src/script/__tests/Spend.node-conformance-regressions.test.ts` +/// (cited as `TS:`), whose verdicts are SV Node's. Rules without a TS +/// vector cite `bitcoin-sv` v1.2.3 `src/script/interpreter.cpp` (`node:`). +@Suite("SV Node script conformance regressions") +struct NodeConformanceRegressionTests { + // MARK: TS node-conformance vectors + + @Test("every TypeScript node-conformance vector gets the node verdict", arguments: Self.vectors) + func nodeVector(_ vector: NodeVector) throws { + if vector.valid { + #expect(try vector.run().stack.last.map(scriptTruth) == true, "TS:\(vector.sourceLine)") + } else { + #expect(throws: ScriptExecutionError.self, "TS:\(vector.sourceLine)") { + try vector.run() + } + } + } + + // MARK: T1 splice operands + + @Test("OP_SUBSTR, OP_LEFT and OP_RIGHT reject operands longer than nine bytes") + func spliceOperandsLongerThanNineBytes() throws { + for lock in [ + "03000102000a01000000000000000000b3", // SUBSTR, ten-byte length 1 + "030001020a0100000000000000000051b3", // SUBSTR, ten-byte offset 1 + "0200010a01000000000000000000b4", // LEFT, ten-byte count 1 + "0200010a01000000000000000000b5", // RIGHT, ten-byte count 1 + ] { + #expect(throws: ScriptExecutionError.consensus(.scriptNumberOverflow), "\(lock)") { + try run(lock: lock, era: .afterChronicle) + } + } + } + + @Test("nine-byte splice operands decode the full signed 64-bit value") + func nineByteSpliceOperands() throws { + let nineByteOne = "09010000000000000000" + let nineByteMinusOne = "09010000000000000080" + for lock in [ + "0300010200" + nineByteOne + "b3" + "0100" + "87", // SUBSTR length 1 gives 00 + "020001" + nineByteOne + "b4" + "0100" + "87", // LEFT 1 gives 00 + "020001" + nineByteOne + "b5" + "0101" + "87", // RIGHT 1 gives 01 + ] { + #expect(try run(lock: lock, era: .afterChronicle).stack == [[1]], "\(lock)") + } + // A nine-byte -1 is out of range, not a truncated 1 or a huge count. + let negativeOne: [(String, ScriptConsensusFailure)] = [ + ("03000102" + nineByteMinusOne + "51b3", .invalidSplitPosition(position: -1, byteCount: 3)), + ("0300010200" + nineByteMinusOne + "b3", .invalidSplitPosition(position: 0, byteCount: 3)), + ("020001" + nineByteMinusOne + "b4", .invalidSplitPosition(position: -1, byteCount: 2)), + ("020001" + nineByteMinusOne + "b5", .invalidSplitPosition(position: -1, byteCount: 2)), + ] + for (lock, failure) in negativeOne { + #expect(throws: ScriptExecutionError.consensus(failure), "\(lock)") { + try run(lock: lock, era: .afterChronicle) + } + } + // TS:164 gen-00795: offset 04 00 00 00 00 00 00 00 80 is -4, not 4. + #expect(throws: ScriptExecutionError.consensus( + .invalidSplitPosition(position: -4, byteCount: 16) + )) { + try run( + lock: "10000102030405060708090a0b0c0d0e0f0904000000000000008054b3040405060787", + era: .afterChronicle + ) + } + for operand in [ + "09ffffffffffffffff00", // 2^64 - 1 + "09000000000000008000", // 2^63 + "09010000000000000001", // value bits in the sign byte + ] { + #expect(throws: ScriptExecutionError.consensus(.scriptNumberOverflow), "\(operand)") { + try run(lock: "020001" + operand + "b4", era: .afterChronicle) + } + } + // -2^63 decodes and saturates to INT32_MIN, which is out of range. + #expect(throws: ScriptExecutionError.consensus( + .invalidSplitPosition(position: Int64(Int32.min), byteCount: 2) + )) { + try run(lock: "020001" + "09000000000000008080" + "b4", era: .afterChronicle) + } + // A large in-range value saturates to INT32_MAX, which is out of range. + #expect(throws: ScriptExecutionError.consensus( + .invalidSplitPosition(position: Int64(Int32.max), byteCount: 2) + )) { + try run(lock: "020001" + "09ffffffffffffff7f00" + "b4", era: .afterChronicle) + } + // MINIMALDATA applies before the nine-byte rule. + #expect(throws: ScriptExecutionError.consensus(.nonMinimalNumber)) { + try run( + lock: "020001" + "0a01000000000000000000" + "b4", + era: .afterChronicle, + flags: [.minimalData] + ) + } + } + + // MARK: T2 / T7 numeric shifts + + @Test("numeric shift counts above INT32_MAX are rejected") + func shiftCountAboveInt32() throws { + // TS:173 gen-00835 and TS:303: 1 >> 2^31 and 1 << 2^31. + for lock in ["51050000008000b77551", "51050000008000b67551", "00050000008000b67551"] { + #expect(throws: ScriptExecutionError.self, "\(lock)") { + try run(lock: lock, era: .afterChronicle) + } + } + #expect(throws: ScriptExecutionError.consensus(.invalidShiftAmount(1 << 31))) { + try run(lock: "51050000008000b77551", era: .afterChronicle) + } + // 0 >> 2^31 is rejected too: bint::operator>>= checks the count first. + #expect(throws: ScriptExecutionError.consensus(.invalidShiftAmount(1 << 31))) { + try run(lock: "00050000008000b77551", era: .afterChronicle) + } + // INT32_MAX itself is a valid right-shift count. + #expect(try run(lock: "5104ffffff7fb70087", era: .afterChronicle).stack == [[1]]) + } + + @Test("OP_LSHIFTNUM bounds the operand size plus shifted bytes by the number limit") + func leftShiftSizeBound() throws { + // TS:191 gen-00813: 1 << INT32_MAX. + #expect(throws: ScriptExecutionError.consensus( + .numberTooLarge(actual: 1 + Int(Int32.max) / 8, maximum: 32_000_000) + )) { + try run(lock: "5104ffffff7fb67551", era: .afterChronicle) + } + // node script_num.cpp operator<<=: zero is bounded too. 256,000,000 + // bits add exactly 32,000,000 bytes; eight more bits exceed the limit. + #expect(try run(lock: "00040040420fb60087", era: .afterChronicle).stack == [[1]]) + #expect(throws: ScriptExecutionError.consensus( + .numberTooLarge(actual: 32_000_001, maximum: 32_000_000) + )) { + try run(lock: "00040840420fb67551", era: .afterChronicle) + } + } + + @Test("OP_RSHIFTNUM rounds negative values toward zero") + func rightShiftRoundsTowardZero() throws { + // -3 >> 1 == -1 (0x81) and -1 >> 1 == 0: BN_rshift shifts the magnitude. + #expect(try run(lock: "538f51b7018187", era: .afterChronicle).stack == [[1]]) + #expect(try run(lock: "4f51b70087", era: .afterChronicle).stack == [[1]]) + #expect(try run(lock: "548f51b7018287", era: .afterChronicle).stack == [[1]]) + #expect(try run(lock: "538f51b7", era: .afterChronicle).stack == [[0x81]]) + } + + // MARK: T3 number size + + @Test("after Chronicle the script number limit is 32,000,000 bytes") + func chronicleNumberLimit() throws { + let vector = try #require(Self.vectors.first { $0.name == "gen-00009" }) + #expect(throws: ScriptExecutionError.consensus( + .numberTooLarge(actual: 32_000_001, maximum: 32_000_000) + )) { + try vector.run() + } + } + + // MARK: T4 SIGHASH_CHRONICLE + + @Test("a SIGHASH_CHRONICLE|FORKID signature verifies against the original digest") + func chronicleSignatureUsesOriginalDigest() throws { + // TS:78 gen-00974: a pre-Chronicle output spent in a Chronicle block + // with hash type 0x61 (ALL|FORKID|CHRONICLE). + let vector = try #require(Self.vectors.first { $0.name == "gen-00974" }) + #expect(try vector.run().stack == [[1]]) + // node:296-303: outside Chronicle rules strict encoding rejects bit 0x20. + #expect(throws: ScriptExecutionError.consensus(.illegalChronicle(0x61))) { + try vector.run(flags: [.enableForkID]) + } + // node:2118: the CHRONICLE bit selects the original digest whatever + // the flags, so without strict encoding the signature still verifies. + #expect(try vector.run(flags: []).stack == [[1]]) + #expect(try vector.run(flags: [.derSignatures, .lowS, .nullFail]).stack == [[1]]) + // TS:97 and TS:106: the original digest walk includes the malformed + // bytes after OP_RETURN. + for name in ["gen-01001", "gen-00999"] { + let walkVector = try #require(Self.vectors.first { $0.name == name }) + #expect(try walkVector.run().stack == [[1]], "\(name)") + } + } + + @Test("strict encoding checks hash types in the node's order") + func hashTypeMatrix() throws { + let vector = try #require(Self.vectors.first { $0.name == "gen-00974" }) + let element = Array(try vector.transaction().inputs[0].unlockingScript.bytes.dropFirst()) + let der = Array(element.dropLast()) + let checkSignature = hex(vector.lockHex) + let profiles: [(ScriptVerificationFlags, (UInt8) -> ScriptConsensusFailure?)] = [ + ([.enableForkID, .chronicle], { hashType in + guard (1...3).contains(hashType & 0x1f) else { return .invalidSignatureHashType(hashType) } + return hashType & 0x40 == 0 ? .illegalForkID(hashType) : nil + }), + ([.enableForkID], { hashType in + guard (1...3).contains(hashType & 0x1f) else { return .invalidSignatureHashType(hashType) } + if hashType & 0x20 != 0 { return .illegalChronicle(hashType) } + return hashType & 0x40 == 0 ? .illegalForkID(hashType) : nil + }), + ([.strictEncoding, .chronicle], { hashType in + guard (1...3).contains(hashType & 0x1f) else { return .invalidSignatureHashType(hashType) } + return hashType & 0x40 != 0 ? .illegalForkID(hashType) : nil + }), + ] + for (flags, expected) in profiles { + for hashType in UInt8.min...UInt8.max { + let signature = der + [hashType] + let lock = [UInt8(signature.count)] + signature + checkSignature + [0x91] + let lockHex = Hex.encode(lock) + if let failure = expected(hashType) { + #expect(throws: ScriptExecutionError.consensus(failure), "\(flags) \(hashType)") { + try run(lock: lockHex, era: .afterGenesis, flags: flags, context: true) + } + } else { + // The encoding passes; the signature does not verify here. + #expect( + try run(lock: lockHex, era: .afterGenesis, flags: flags, context: true).stack == [[1]], + "\(flags) \(hashType)" + ) + } + } + } + } + + + + @Test("the alternate stack does not survive an unlocking-script OP_RETURN") + func altStackDoesNotLeak() throws { + for era in [ScriptExecutionEra.afterGenesis, .afterChronicle] { + #expect(throws: ScriptExecutionError.consensus(.altStackUnderflow)) { + try run(unlock: "516b6a", lock: "6c", era: era) + } + } + } + + // MARK: T6 empty signature and public-key encoding + + @Test("an empty signature still requires a strictly encoded public key") + func emptySignaturePublicKeyEncoding() throws { + // CHECKSIG: OP_0, pubkey 00, CHECKSIG, NOT. + #expect(throws: ScriptExecutionError.consensus(.invalidPublicKeyEncoding)) { + try run(lock: "000100ac91", era: .afterGenesis, flags: [.strictEncoding], context: true) + } + #expect(try run(lock: "000100ac91", era: .afterGenesis, context: true).stack == [[1]]) + // CHECKMULTISIG: dummy, empty signature, 1, pubkey 00, 1, CHECKMULTISIG, NOT. + #expect(throws: ScriptExecutionError.consensus(.invalidPublicKeyEncoding)) { + try run(lock: "000051010051ae91", era: .afterGenesis, flags: [.strictEncoding], context: true) + } + #expect(try run(lock: "000051010051ae91", era: .afterGenesis, context: true).stack == [[1]]) + } + + // MARK: T8 ForkID digest gating + + @Test("a FORKID-bit signature uses the original digest when ForkID is not enabled") + func preForkIDSignatures() throws { + // TS:340: three P2PK inputs signed with 0x01, 0x41 and 0x01 at height 478000. + for (index, lock) in Self.preUAHFLocks.enumerated() { + #expect(try runPreUAHF(index: index, lock: lock).stack == [[1]], "input \(index)") + } + // With ForkID enabled the legacy signatures must use FORKID (node:296-306). + #expect(throws: ScriptExecutionError.consensus(.illegalForkID(0x01))) { + try runPreUAHF(index: 0, lock: Self.preUAHFLocks[0], flags: [.enableForkID]) + } + } + + // MARK: T9 original digest script-code walk + + @Test("the original digest walk writes what the node walk consumes") + func originalDigestWalk() throws { + // TS:311-331: CompactSize plus bytes of the preimage script field. + for (scriptHex, expectedHex) in [ + ("4d0100aa", "044d0100aa"), + ("4e01000000aa", "064e01000000aa"), + ("6a4e050000", "056a4e"), + ("6a4e05000000aabb", "086a4e05000000"), + ("51ab52ab", "025152"), + ("ab", "00"), + ("51ab4c", "0251" + "4c"), + ] { + let walk = ScriptMachine.originalDigestScriptCode(hex(scriptHex)) + #expect([UInt8(walk.encodedLength)] + walk.bytes == hex(expectedHex), "\(scriptHex)") + } + } + + @Test("FindAndDelete removes only exact signature pushes at instruction boundaries") + func findAndDelete() throws { + let signature: [UInt8] = [0xaa, 0xbb] + let pattern = ScriptMachine.pushEncoding(signature) + #expect(pattern == [0x02, 0xaa, 0xbb]) + // Exact pushes are removed, repeated ones too. + #expect(ScriptMachine.findAndDelete(hex("02aabb5102aabb02aabbac"), pattern: pattern) == hex("51ac")) + // A push that merely contains the signature stays (pinned Go removes it). + #expect(ScriptMachine.findAndDelete(hex("03aabbcc51"), pattern: pattern) == hex("03aabbcc51")) + // A match inside push data is not at an instruction boundary. + #expect(ScriptMachine.findAndDelete(hex("0302aabb51"), pattern: pattern) == hex("0302aabb51")) + // A non-minimal push of the same bytes is a different instruction. + #expect(ScriptMachine.findAndDelete(hex("4c02aabb51"), pattern: pattern) == hex("4c02aabb51")) + // A truncated tail ends the walk and is kept. + #expect(ScriptMachine.findAndDelete(hex("02aabb4d05"), pattern: pattern) == hex("4d05")) + // An empty signature is pushed as OP_0. + #expect(ScriptMachine.pushEncoding([]) == [0x00]) + #expect(ScriptMachine.pushEncoding(Array(repeating: 1, count: 76)).prefix(2) == [0x4c, 76]) + #expect(ScriptMachine.pushEncoding(Array(repeating: 1, count: 256)).prefix(3) == [0x4d, 0, 1]) + } + + // MARK: T10 Chronicle malleability relaxation + + @Test("Chronicle relaxes the malleability rules only for transaction versions above one") + func chronicleMalleabilityRelaxation() throws { + // TS:274: SIGPUSHONLY is kept for version one. + let flow = try #require(Self.vectors.first { $0.name == "flow-00961" }) + #expect(throws: ScriptExecutionError.consensus(.signatureScriptNotPushOnly)) { + try flow.run(version: 1) + } + // NULLFAIL (TS:15 crypto-00012). + let crypto = try #require(Self.vectors.first { $0.name == "crypto-00012" }) + #expect(throws: ScriptExecutionError.consensus(.nullFail)) { + try crypto.run(version: 1) + } + // MINIMALDATA (TS:33 arith-00351). + let arith = try #require(Self.vectors.first { $0.name == "arith-00351" }) + #expect(throws: ScriptExecutionError.consensus(.nonMinimalNumber)) { + try arith.run(version: 1) + } + // A version above INT32_MAX is negative to the node, so not malleable. + #expect(throws: ScriptExecutionError.consensus(.signatureScriptNotPushOnly)) { + try flow.run(version: 0x8000_0002) + } + // Without Chronicle rules nothing is relaxed, whatever the version. + #expect(throws: ScriptExecutionError.consensus(.signatureScriptNotPushOnly)) { + try flow.run(era: .afterGenesis, chronicle: false) + } + } + + @Test("Chronicle relaxes MINIMALIF, NULLDUMMY, CLEANSTACK and LOW_S for version two") + func chronicleRelaxationOfRemainingRules() throws { + let minimalIf = ("52", "6351670068") // 2 IF 1 ELSE 0 ENDIF + let nullDummy = ("51", "0000ae") // dummy 1, 0-of-0 CHECKMULTISIG + let cleanStack = ("5151", "51") + let cases: [(String, (String, String), ScriptVerificationFlags, ScriptConsensusFailure)] = [ + ("MINIMALIF", minimalIf, [.minimalIf], .minimalIf), + ("NULLDUMMY", nullDummy, [.strictMultiSignatureDummy], .nullDummy), + ("CLEANSTACK", cleanStack, [.cleanStack, .payToScriptHash], .cleanStackViolation(actualItemCount: 3)), + ] + for (name, scripts, flags, failure) in cases { + #expect(throws: ScriptExecutionError.consensus(failure), "\(name) v1") { + try run(unlock: scripts.0, lock: scripts.1, era: .afterChronicle, flags: flags, context: true, version: 1) + } + #expect(try run( + unlock: scripts.0, lock: scripts.1, era: .afterChronicle, flags: flags, context: true, version: 2 + ).stack.last == [1], "\(name) v2") + } + + // LOW_S: a high-S P2PK signature. + let key = try PrivateKey(Array(repeating: 0, count: 31) + [7]) + let lock = try Script.payToPublicKey(key.publicKey, maximumByteCount: 100) + for version: UInt32 in [1, 2] { + var transaction = try simpleTransaction(version: version, unlocking: [], lock: lock) + let digest = try transaction.legacySignatureHash( + inputIndex: 0, + hashType: .all, + scriptCode: lock, + limits: Self.limits + ) + let low = try key.sign(digest: digest) + let high = try ECDSASignature( + compactBytes: Array(low.compactBytes[..<32]) + + subtract(Array(low.compactBytes[32...]), from: curveOrder) + ) + let element = high.derBytes + [0x01] + transaction.inputs[0].unlockingScript = try Script( + bytes: [UInt8(element.count)] + element, + maximumByteCount: 100 + ) + let execute = { + try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: .afterChronicle, + flags: [.lowS], + resourceLimits: .standard + ), + context: ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: Self.limits + ) + ) + } + if version == 1 { + #expect(throws: ScriptExecutionError.consensus(.invalidSignatureEncoding)) { + try execute() + } + } else { + #expect(try execute().stack == [[1]]) + } + } + } + + // MARK: Other node signature-check rules + + @Test("a CHECKSIG in the unlocking script also commits to the locking script under Chronicle") + func chronicleUnlockingScriptCode() throws { + // node:1472-1481: scriptCode += scriptPubKey when CHRONICLE is set. + let key = try PrivateKey(Array(repeating: 0, count: 31) + [9]) + let lock = try Script(bytes: [Opcode.one.rawValue], maximumByteCount: 1) + let scriptCode = try Script( + bytes: [Opcode.checkSigVerify.rawValue, Opcode.one.rawValue], + maximumByteCount: 2 + ) + var transaction = try simpleTransaction(version: 2, unlocking: [], lock: lock) + let digest = try transaction.forkIDSignatureHash( + inputIndex: 0, + scriptCode: scriptCode, + limits: Self.limits + ) + let element = try key.sign(digest: digest).derBytes + [0x41] + let publicKey = key.publicKey.compressedBytes + transaction.inputs[0].unlockingScript = try Script( + bytes: [UInt8(element.count)] + element + [UInt8(publicKey.count)] + publicKey + + [Opcode.codeSeparator.rawValue, Opcode.checkSigVerify.rawValue], + maximumByteCount: 200 + ) + let context = ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: Self.limits + ) + func execute(_ era: ScriptExecutionEra, _ flags: ScriptVerificationFlags) throws -> ScriptExecutionResult { + try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: era, + flags: flags, + resourceLimits: .standard + ), + context: context + ) + } + #expect(try execute(.afterChronicle, [.enableForkID]).stack == [[1]]) + #expect(try execute(.afterGenesis, [.enableForkID, .chronicle]).stack == [[1]]) + #expect(throws: ScriptExecutionError.consensus(.checkSignatureVerifyFailed)) { + try execute(.afterGenesis, [.enableForkID]) + } + } + + @Test("NULLFAIL applies to every failed non-empty signature") + func nullFailOnEveryFailure() throws { + // A one-byte signature (hash type only) and an invalid public key: the + // node's CheckSig fails and NULLFAIL rejects the non-empty element. + #expect(throws: ScriptExecutionError.consensus(.nullFail)) { + try run(lock: "0101" + "0100" + "ac91", era: .afterGenesis, flags: [.nullFail], context: true) + } + #expect(try run(lock: "0101" + "0100" + "ac91", era: .afterGenesis, context: true).stack == [[1]]) + } + + @Test("CHECKMULTISIG counts are four-byte Script numbers in every era") + func multiSignatureCountSize() throws { + // node:1530-1535: CScriptNum(..., CScriptNum::MAXIMUM_ELEMENT_SIZE). + #expect(throws: ScriptExecutionError.consensus(.numberTooLarge(actual: 5, maximum: 4))) { + try run(lock: "0000050000000000ae", era: .afterGenesis, context: true) + } + #expect(throws: ScriptExecutionError.consensus(.numberTooLarge(actual: 5, maximum: 4))) { + try run(lock: "00050000000000" + "00ae", era: .afterGenesis, context: true) + } + #expect(try run(lock: "00000400000000ae", era: .afterGenesis, context: true).stack == [[1]]) + } +} + +// MARK: - Fixtures + +struct NodeVector: Sendable, CustomTestStringConvertible { + let name: String + let sourceLine: Int + let lockHex: String + let coinHeight: UInt32 + let txHex: String + let valid: Bool + + var testDescription: String { name } + + func transaction(version: UInt32? = nil) throws -> Transaction { + var transaction = try Transaction(hex: txHex, limits: NodeConformanceRegressionTests.limits) + if let version { transaction.version = version } + return transaction + } + + /// TS `createSpend`: current block flags plus the UTXO era by coin height. + var flags: ScriptVerificationFlags { + switch name { + case "eras-00052": + return [.payToScriptHash, .derSignatures, .checkLockTimeVerify] + case "eras-00054": + return [.payToScriptHash, .derSignatures, .checkLockTimeVerify, .checkSequenceVerify] + default: + var flags: ScriptVerificationFlags = [ + .payToScriptHash, .strictEncoding, .derSignatures, .lowS, + .signaturePushOnly, .checkLockTimeVerify, .checkSequenceVerify, + .nullFail, .enableForkID, .chronicle, + ] + if name == "arith-00351" { + flags.formUnion([ + .strictMultiSignatureDummy, .minimalData, + .discourageUpgradeableNops, .cleanStack, + ]) + } + return flags + } + } + + var era: ScriptExecutionEra { + if name == "eras-00052" || name == "eras-00054" { return .beforeGenesis } + if coinHeight >= 943_816 { return .afterChronicle } + if coinHeight >= 620_538 { return .afterGenesis } + return .beforeGenesis + } + + @discardableResult + func run( + flags overrideFlags: ScriptVerificationFlags? = nil, + version: UInt32? = nil, + era overrideEra: ScriptExecutionEra? = nil, + chronicle: Bool = true + ) throws -> ScriptExecutionResult { + let transaction = try transaction(version: version) + let lock = try Script(hex: lockHex, maximumByteCount: 1_000) + var flags = overrideFlags ?? self.flags + if !chronicle { flags.remove(.chronicle) } + return try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: overrideEra ?? era, + flags: flags, + resourceLimits: .standard + ), + context: ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: NodeConformanceRegressionTests.limits + ) + ) + } +} + +extension NodeConformanceRegressionTests { + static let limits: TransactionLimits = { + do { + return try TransactionLimits( + maximumTransactionByteCount: 100_000, + maximumInputCount: 10, + maximumOutputCount: 10, + maximumScriptByteCount: 100_000 + ) + } catch { + preconditionFailure("valid limits") + } + }() + + static let vectors: [NodeVector] = [ + NodeVector( + name: "crypto-00012", + sourceLine: 15, + lockHex: "21035935f55855afd8c999bdb5a8d08ae8e73b7618e200d4ef7687cd55d3c2e4c9d7ac91", + coinHeight: 967896, + txHex: "0200000001d9fa799b3044ad9589c87a3e67980b12da738e9b13542dd868726cf0a0b39e250000000049483045022100d7d09ade8b4adb6372ef31dab5fe96ef44e0661156c1ecf6f81a8353d14060650220057e129a333dda81260ba7ee86b8a15cf88e51ef06a5d30cdebbbfc4f10d361341ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "flow-00961", + sourceLine: 24, + lockHex: "51", + coinHeight: 967896, + txHex: "02000000010a7b1c40c67f02436acff2a4b6e22ca7b3deb60852f4c10f18e05f07e5d0f5260000000002516affffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "arith-00351", + sourceLine: 33, + lockHex: "020100985287", + coinHeight: 967896, + txHex: "020000000120aaf54d327d617af4e5bb4a3db9d7d135afe0ff8f03bd59cc79eb969fb988e600000000014fffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "eras-00001", + sourceLine: 42, + lockHex: "516a", + coinHeight: 620537, + txHex: "02000000018e7c542db81ed89b3270ff26342988db87785631329107fb7a0e11ded53b6e6d0000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "eras-00019", + sourceLine: 51, + lockHex: "5163516700675168", + coinHeight: 620537, + txHex: "0200000001f01a60cf6e52c646d620388d2619756c63fafc35e451377d37bb2e638ed8f4c10000000000ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "gen-00006", + sourceLine: 60, + lockHex: "5103b1710b808b7551", + coinHeight: 620538, + txHex: "0200000001d778b0553b5c7c553a74ae08b43a94b3fc9fc3097fde32fb54d29970050fb8ed0000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "gen-00009", + sourceLine: 69, + lockHex: "51040148e801808b7551", + coinHeight: 943816, + txHex: "02000000010282f68044beaa91d8f3424e5499046c9a2fc62222344f786bdf10882a0dcb050000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "gen-00974", + sourceLine: 78, + lockHex: "2103913a7b50432835163ebc6aa9cad8c3f52e6a37df35be520213a2fa5c0be9b353ac", + coinHeight: 620538, + txHex: "0200000001421e09a1497b8976eafb681be43ab7ff15ca2075266f785f9610e4f935a8f8360000000049483045022100874e74f0c4921c200fbb90fd537ebefb84844f1b74d02355896bee35d213ee1b022048a1a59726aa089318f650f58b413615f32789d9eba562f6a1254d657f75992d61ffffffff02010000000000000001510200000000000000015100000000", + valid: true + ), + NodeVector( + name: "crypto-00084 (version 1)", + sourceLine: 87, + lockHex: "473044022072b7e219170a2ae089c149ae684a1a7ad50a3251ad466b94a145b86bb76d150002205190440eb08efa92ced4e80a9c2f8e2721cf21a9c14d81015d16c05686eda235417521035935f55855afd8c999bdb5a8d08ae8e73b7618e200d4ef7687cd55d3c2e4c9d7ac", + coinHeight: 967896, + txHex: "01000000010339699bf39cbdfa8e8965583d70faa0301fe96efc6f17053cbbb31ff1d0b7670000000048473044022072b7e219170a2ae089c149ae684a1a7ad50a3251ad466b94a145b86bb76d150002205190440eb08efa92ced4e80a9c2f8e2721cf21a9c14d81015d16c05686eda23541ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "gen-01001", + sourceLine: 97, + lockHex: "2103913a7b50432835163ebc6aa9cad8c3f52e6a37df35be520213a2fa5c0be9b353ac6a4d05", + coinHeight: 943816, + txHex: "0200000001df9aea25028895f34dd187cd56c319ed0eb8d6896c2cd0866bc0544fe52394d9000000004847304402204519a364c695b04b7e5017be05deb0a3fdf25d09d31f0940b3e9efedbe7f496f02202c7b917f465dd4a505816f2a28d839d2044dbbdaeb1df9f3c39e9975c6f7e3de61ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "gen-00999", + sourceLine: 106, + lockHex: "2103913a7b50432835163ebc6aa9cad8c3f52e6a37df35be520213a2fa5c0be9b353ac6a4c05aabb", + coinHeight: 943816, + txHex: "0200000001f81e0cf3c931477cbe57a9388d22c15466688974e66c7a7fae77a5623925265d0000000049483045022100e7bd08a7cf0a1bda318923e1e931e83070adb546eed21d79fbc92ef12966f958022071a9fada8e08eafc1758a8dc47501e4999ea89774872a3d96d0611d5aab7548761ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "eras-00015", + sourceLine: 115, + lockHex: "51b17551", + coinHeight: 620537, + txHex: "0200000001b4b3e19df37673ec4804630b153244aa2a83317c5ba79e4b78c085849df944050000000000feffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "eras-00052", + sourceLine: 124, + lockHex: "51b17551", + coinHeight: 100, + txHex: "0200000001bed48f683afbb0e47b069b3120ccc36eff75c5e5183bc47362c878543816d2160000000000feffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "eras-00017", + sourceLine: 133, + lockHex: "51b27551", + coinHeight: 620537, + txHex: "020000000149186975113ea88ff53e1c51d65bc3338afe5d704801d927a4fe8db8224e6b6a000000000000000000010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "eras-00054", + sourceLine: 142, + lockHex: "51b27551", + coinHeight: 100, + txHex: "0200000001c1bf107a0b3b61e2511f9914dfdb0eb4399042a51493aa7d7c0fe9ee82709471000000000000000000010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "bytes-00435 (version 1)", + sourceLine: 151, + lockHex: "b2", + coinHeight: 967896, + txHex: "01000000017e41122de6de8c7c28680fc3a234f7838c43e6592331fe4a0ad68ae13462f6250000000006515253545556ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "gen-00795", + sourceLine: 164, + lockHex: "10000102030405060708090a0b0c0d0e0f0904000000000000008054b3040405060787", + coinHeight: 943816, + txHex: "0200000001bd713e289714213b3d76b5168a550fe3bc8bee30363eb9a72795e051c88686500000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "gen-00835", + sourceLine: 173, + lockHex: "51050000008000b77551", + coinHeight: 943816, + txHex: "0200000001829896aed1733429283adb214280217591f00929568490f2c8530c8a9f7260310000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "arith-00163", + sourceLine: 182, + lockHex: "04ffffff7f98010087", + coinHeight: 967896, + txHex: "0200000001bbc9d9c85aca832a951c9630dbb352b3c012b48c1ecbcfb12ff5bcc67f9fc833000000000153ffffffff010100000000000000015100000000", + valid: true + ), + NodeVector( + name: "gen-00813", + sourceLine: 191, + lockHex: "5104ffffff7fb67551", + coinHeight: 943816, + txHex: "0200000001503dd6f80c4ebe381c7c8fb609d1555c2ea5fa2aa59f002acd05151f46c7ad5d0000000000ffffffff010100000000000000015100000000", + valid: false + ), + NodeVector( + name: "stack-00217", + sourceLine: 200, + lockHex: "0500000080008051", + coinHeight: 967896, + txHex: "020000000187a34732a06ac0f3edeca5c9a239399da4c91d80f507fbd34c06ce985d415f27000000000151ffffffff010100000000000000015100000000", + valid: false + ), + ] + + static let preUAHFTransactionHex = "02000000031c03d65739de2b55f51b600abb4b3eba4c3bbc3c62244bf10eaa53b6c63d39ad000000004948304502210080089464b438a3c3b800805194aaf845845ff0fb73dd55da5bc32a2ba016a0da022003e74a9cf63659240c2814006ada6fb982fdf01c292bff03da79692cafb6c5cd01ffffffff140155ec0e942dc40a8f418e720b4e996e50788fb0b5a4e23a5659df6f939063000000004847304402207acc9a382964cf2c03c83df3f877ddaa942ecfd5fb48c9e4636b1ee46fea0a29022022373d2f768a83c2b5f0a843c0e48bd19716922c4831ba083a4a0e25f14005a641ffffffff8e47aab4115643d43d0428135ef7eb3d37472c0cfec5e3eda8339921f8efeb4a000000004847304402206e1f94c990cb392dab5e7e46faa775bdfeea9ab8787cba307de9c3f7bcec046b022015bedb0d8f5e295de76de219de674c41649057f8e77494855c868b709e14667901ffffffff02010000000000000001510200000000000000015100000000" + + static let preUAHFLocks = [ + "2103913a7b50432835163ebc6aa9cad8c3f52e6a37df35be520213a2fa5c0be9b353ac", + "2103c10f4fba86c5439080cb87226bc19b344eb56e6f4f6db673b6674fdfa63f6d57ac", + "2102dae175dcbf94e5b79a4a53a67ba1259b7825079ec03b2c39101b9438eff5d904ac", + ] + + func runPreUAHF( + index: Int, + lock lockHex: String, + flags: ScriptVerificationFlags = [ + .payToScriptHash, .derSignatures, .checkLockTimeVerify, .checkSequenceVerify, + ] + ) throws -> ScriptExecutionResult { + let transaction = try Transaction(hex: Self.preUAHFTransactionHex, limits: Self.limits) + let lock = try Script(hex: lockHex, maximumByteCount: 1_000) + return try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[index].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: .beforeGenesis, + flags: flags, + resourceLimits: .standard + ), + context: ScriptExecutionContext( + transaction: transaction, + inputIndex: index, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: Self.limits + ) + ) + } + + func simpleTransaction(version: UInt32, unlocking: [UInt8], lock: Script) throws -> Transaction { + Transaction( + version: version, + inputs: [TransactionInput( + previousOutput: try Outpoint( + transactionID: TransactionID(wireBytes: Array(repeating: 0x42, count: 32)), + outputIndex: 0 + ), + unlockingScript: try Script(bytes: unlocking, maximumByteCount: 1_000), + sourceOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock) + )], + outputs: [TransactionOutput( + satoshis: 900, + lockingScript: try Script(bytes: [Opcode.one.rawValue], maximumByteCount: 1) + )] + ) + } + + @discardableResult + func run( + unlock: String = "", + lock: String, + era: ScriptExecutionEra, + flags: ScriptVerificationFlags = [], + context withContext: Bool = false, + version: UInt32 = 2 + ) throws -> ScriptExecutionResult { + let unlocking = try Script(hex: unlock, maximumByteCount: 1_000) + let locking = try Script(hex: lock, maximumByteCount: 1_000) + var context: ScriptExecutionContext? + if withContext { + var transaction = try simpleTransaction(version: version, unlocking: [], lock: locking) + transaction.inputs[0].unlockingScript = unlocking + context = ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: locking), + transactionLimits: Self.limits + ) + } + return try ScriptInterpreter.execute( + unlockingScript: unlocking, + lockingScript: locking, + configuration: ScriptExecutionConfiguration( + era: era, + flags: flags, + resourceLimits: .standard + ), + context: context + ) + } +} + +private func hex(_ text: String) -> [UInt8] { + (try? Hex.decode(text, maximumDecodedByteCount: 10_000)) ?? [] +} + +private func scriptTruth(_ bytes: [UInt8]) -> Bool { + for index in bytes.indices where bytes[index] != 0 { + return !(index == bytes.count - 1 && bytes[index] == 0x80) + } + return false +} + +private let curveOrder: [UInt8] = [ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, + 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, +] + +private func subtract(_ value: [UInt8], from minuend: [UInt8]) -> [UInt8] { + var result = Array(repeating: UInt8(0), count: value.count) + var borrow = 0 + for index in value.indices.reversed() { + var difference = Int(minuend[index]) - Int(value[index]) - borrow + if difference < 0 { + difference += 256 + borrow = 1 + } else { + borrow = 0 + } + result[index] = UInt8(difference) + } + return result +} diff --git a/Tests/BSVInterpreterTests/Reference/InterpreterReferenceNumberBoundaryTests.swift b/Tests/BSVInterpreterTests/Reference/InterpreterReferenceNumberBoundaryTests.swift index 6e01ee5..5b88b57 100644 --- a/Tests/BSVInterpreterTests/Reference/InterpreterReferenceNumberBoundaryTests.swift +++ b/Tests/BSVInterpreterTests/Reference/InterpreterReferenceNumberBoundaryTests.swift @@ -26,7 +26,8 @@ struct InterpreterReferenceNumberBoundaryTests { #expect(afterChronicle.maximumPushDataByteCount == Int(Int32.max)) #expect(afterChronicle.maximumStackItemCount == Int(Int32.max)) #expect(afterChronicle.maximumOperationCountPerScript == Int(Int32.max)) - let chronicleMaximum = 32 * 1_024 * 1_024 + // SV Node MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE = 32 * ONE_MEGABYTE (1,000,000). + let chronicleMaximum = 32_000_000 let chroniclePlusOne = chronicleMaximum + 1 #expect(afterChronicle.maximumScriptNumberByteCount == chronicleMaximum) #expect(afterChronicle.maximumScriptNumberByteCount + 1 == chroniclePlusOne) diff --git a/Tests/BSVInterpreterTests/ScriptInterpreterTests.swift b/Tests/BSVInterpreterTests/ScriptInterpreterTests.swift index 531e208..371bf00 100644 --- a/Tests/BSVInterpreterTests/ScriptInterpreterTests.swift +++ b/Tests/BSVInterpreterTests/ScriptInterpreterTests.swift @@ -42,7 +42,7 @@ struct ScriptInterpreterTests { #expect(result.stack == [[0x2a], [1]]) } - @Test("alternative stack boundary behavior matches ordinary and early-return transitions") + @Test("each script starts with an empty alternate stack, also after an early return") func altStackBoundaries() throws { #expect(throws: ScriptExecutionError.consensus(.altStackUnderflow)) { try execute( @@ -51,16 +51,22 @@ struct ScriptInterpreterTests { ) } - let earlyReturn = try execute( - unlocking: [ - Opcode.one.rawValue, - Opcode.toAltStack.rawValue, - Opcode.return.rawValue, - ], - locking: [Opcode.fromAltStack.rawValue], - era: .afterGenesis - ) - #expect(earlyReturn.stack == [[1]]) + // SV Node evaluates each script with a fresh alternate stack + // (interpreter.cpp EvalScript), so `1 TOALTSTACK RETURN` followed by + // `FROMALTSTACK` fails in every era where RETURN ends the script. + for era in [ScriptExecutionEra.afterGenesis, .afterChronicle] { + #expect(throws: ScriptExecutionError.consensus(.altStackUnderflow)) { + try execute( + unlocking: [ + Opcode.one.rawValue, + Opcode.toAltStack.rawValue, + Opcode.return.rawValue, + ], + locking: [Opcode.fromAltStack.rawValue], + era: era + ) + } + } } @Test("conditionals execute only the selected branch") @@ -580,7 +586,7 @@ struct ScriptInterpreterTests { #expect(result.stack == [[1]]) } - @Test("byte shifts preserve width and after-Chronicle numeric shifts are arithmetic") + @Test("byte shifts preserve width and after-Chronicle numeric right shifts round toward zero") func shifts() throws { for scriptHex in [ "021234549802234087", @@ -593,9 +599,10 @@ struct ScriptInterpreterTests { ).stack == [[1]]) } + // -3 >> 1 == -1: SV Node shifts the magnitude (OpenSSL BN_rshift). #expect(try execute( unlocking: [], - locking: Hex.decode("538f51b701829c", maximumDecodedByteCount: 100), + locking: Hex.decode("538f51b701819c", maximumDecodedByteCount: 100), era: .afterChronicle ).stack == [[1]]) } @@ -742,7 +749,11 @@ struct ScriptInterpreterTests { var malformed = unsigned malformed.inputs[0].unlockingScript = try pushedScript([0x01]) - #expect(throws: ScriptExecutionError.consensus(.evaluatedFalse)) { + // SV Node applies NULLFAIL to every non-empty signature that fails, + // including one rejected before the ECDSA check + // (interpreter.cpp, OP_CHECKSIG: `if (!fSuccess && (flags & + // SCRIPT_VERIFY_NULLFAIL) && vchSig.size())`). + #expect(throws: ScriptExecutionError.consensus(.nullFail)) { try executeTransaction( malformed, spentOutput: spentOutput, From 73e626cff12f62cb126fa5cefe892cd956007d1c Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 18:51:07 +0000 Subject: [PATCH 2/3] Address interpreter review: typed script-code size, structural DER, arithmetic bound - Compute the ForkID digest over raw script-code bytes, so a Chronicle unlocking-plus-locking script code is bounded only by the transaction limits and fails with a typed ScriptExecutionError. - Apply only the node's structural DER rule under strict encoding. A signature with an out-of-range r or s now fails CHECKSIG without an error, as in SV Node. - After Genesis, reject arithmetic results longer than the script-number limit, as the node's big-number operators do. - Document the meaning of bip143SignatureHash and when callers must set chronicle themselves, and record the caller-visible changes in COMP-064. - Remove the unused legacy digest overload and add tests for: - multisig NULLFAIL relaxation; - multisig in the unlocking script under Chronicle; - OP_0 removal for an empty signature; - the zero left-shift boundary. --- Documentation/Compatibility/Rulings.md | 2 +- ...MP-064-Interpreter-Node-Chronicle-Rules.md | 83 ++++-- .../ScriptExecutionConfiguration.swift | 18 ++ Sources/BSVInterpreter/VM/ScriptMachine.swift | 63 ++-- .../BSVTransaction/ForkIDSignatureHash.swift | 46 ++- .../BSVTransaction/LegacySignatureHash.swift | 15 - .../NodeConformanceRegressionTests.swift | 269 ++++++++++++++++++ .../LegacySignatureHashTests.swift | 3 +- 8 files changed, 439 insertions(+), 60 deletions(-) diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 1788d54..b7e7a2c 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -71,7 +71,7 @@ behind the general rule. | COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It validates the exact four-field advertisement, binds it to the requested identifier, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the canonical `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | -| COMP-064 | The interpreter was pinned to Go v1.3.3. TypeScript `@bsv/sdk` 4.1.1 and Go disagree with it on Chronicle splice operands, numeric shifts, the Chronicle number limit (32,000,000 bytes, not 32 MiB), `SIGHASH_CHRONICLE`, malleability relaxation for transaction version above 1, alt-stack clearing, and signature and public-key checks. | Swift follows SV Node v1.2.3 for all of them. It adds `ScriptVerificationFlags.chronicle`, implied by the `.afterChronicle` era, and the consensus failures `illegalChronicle` and `scriptNumberOverflow`. | Script validity is consensus, so the node decides. Where Go differs, Swift no longer matches Go. `NodeConformanceRegressionTests` runs all 21 TypeScript node vectors and a test per rule. See [COMP-064](Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md). | +| COMP-064 | The interpreter was pinned to Go v1.3.3. TypeScript `@bsv/sdk` 4.1.1 and Go disagree with it on Chronicle splice operands, numeric shifts, the Chronicle number limit (32,000,000 bytes, not 32 MiB), `SIGHASH_CHRONICLE`, malleability relaxation for transaction version above 1, alt-stack clearing, signature and public-key checks, structural-only DER, and the bound on arithmetic results. | Swift follows SV Node v1.2.3 for all of them. It adds `ScriptVerificationFlags.chronicle`, implied by the `.afterChronicle` era, and the consensus failures `illegalChronicle` and `scriptNumberOverflow`. | Script validity is consensus, so the node decides. With `.enableForkID` a signature without the ForkID bit is rejected, and callers must pass `.chronicle` themselves for older outputs spent after Chronicle activation. Where Go differs, Swift no longer matches Go. `NodeConformanceRegressionTests` runs all 21 TypeScript node vectors and a test per rule. See [COMP-064](Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md). | ## Scope decisions diff --git a/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md index bb060b8..4bdeed4 100644 --- a/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md +++ b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md @@ -16,8 +16,10 @@ Swift follows SV Node v1.2.3 for the rules below. References are to `src/script/interpreter.cpp` unless noted. 1. **Chronicle flag.** `ScriptVerificationFlags.chronicle` (`1 << 15`) mirrors - `SCRIPT_CHRONICLE`. The `.afterChronicle` era always implies it, and - `.enableForkID` implies `.strictEncoding`, as in the node's standard flags. + `SCRIPT_CHRONICLE`. The `.afterChronicle` era always implies it, because a + post-Chronicle output can only be spent in a Chronicle block. + `.enableForkID` implying `.strictEncoding` predates this ruling and + matches `VerifyScript` (lines 2314-2318). 2. **Malleability relaxation (T10).** `EnforceNonMalleability` (line 40) is false only when `.chronicle` is set and the spending transaction's version, read as a signed 32-bit integer, is greater than 1. Without a transaction @@ -49,35 +51,74 @@ Swift follows SV Node v1.2.3 for the rules below. References are to defined base type, then illegal ForkID, then illegal Chronicle, then `MUST_USE_FORKID` when ForkID is enabled and the bit is missing (line 306). -8. **ForkID digest only with ForkID enabled (T8).** A hash type with the ForkID - bit, verified without `.enableForkID`, uses the original digest. -9. **Original-digest script code (T9).** `SerializeScriptCode` (line 1864) - writes the length minus code separators and the bytes up to where a - failed final push stopped the parser. `FindAndDelete` removes only exact - push encodings of the signature, and applies whenever ForkID is not - enabled or the hash type lacks ForkID (`CleanupScriptCode`, line 255). -10. **Chronicle unlocking script code.** A `CHECKSIG` that runs in the - unlocking script under `.chronicle` signs the unlocking script code - followed by the locking script. -11. **Alt stack (T5).** The alt stack is cleared before each script runs, +8. **Structural DER only.** The DER rule is the node's structural + `IsValidSignatureEncoding` (lines 177-235). A structurally valid + signature whose `r` or `s` is zero or not below the curve order passes + it, counts as low S, and fails verification without an error, as the + node's lax parser reads it as the zero signature. NULLFAIL still applies. +9. **Arithmetic results.** After Genesis, a numeric result longer than the + script-number limit fails with `numberTooLarge`, as the node's big-number + `+=`, `-=` and `*=` do (`script_num.cpp:166, 196, 216`). This covers + `OP_ADD`, `OP_SUB`, `OP_MUL`, `OP_1ADD`, `OP_1SUB` and `OP_2MUL`. Before + Genesis the node computes in int64 and five-byte results stay valid. +10. **ForkID digest only with ForkID enabled (T8).** A hash type with the + ForkID bit, verified without `.enableForkID`, uses the original digest. +11. **Original-digest script code (T9).** `SerializeScriptCode` (line 1864) + writes the length minus code separators and the bytes up to where a + failed final push stopped the parser. `FindAndDelete` removes only exact + push encodings of the signature, and applies whenever ForkID is not + enabled or the hash type lacks ForkID (`CleanupScriptCode`, line 255). + An empty signature removes `OP_0` instructions. +12. **Chronicle unlocking script code.** A `CHECKSIG` or `CHECKMULTISIG` + that runs in the unlocking script under `.chronicle` signs the unlocking + script code followed by the locking script (lines 1472-1481 and + 1568-1576). +13. **Alt stack (T5).** The alt stack is cleared before each script runs, so items do not leak from the unlocking script into the locking script after an early `OP_RETURN`. -12. **Public-key check (T6).** `CheckPubKeyEncoding` runs even for an empty +14. **Public-key check (T6).** `CheckPubKeyEncoding` runs even for an empty signature, in `CHECKSIG` and on every `CHECKMULTISIG` comparison. -13. **NULLFAIL.** When enforced, NULLFAIL applies to every non-empty +15. **NULLFAIL.** When enforced, NULLFAIL applies to every non-empty signature that fails, including one rejected before the ECDSA check (lines 1489 to 1497). -14. **Multisig counts.** `CHECKMULTISIG` key and signature counts are decoded +16. **Multisig counts.** `CHECKMULTISIG` key and signature counts are decoded as 4-byte script numbers in every era. New public consensus failures: `ScriptConsensusFailure.illegalChronicle(UInt8)` and `ScriptConsensusFailure.scriptNumberOverflow`. +## Caller-visible changes + +- **Legacy signatures with `.enableForkID`.** A signature without the + ForkID bit now fails with `illegalForkID` when `.enableForkID` is set. It + used to pass the hash-type check and verify against the legacy digest. + This matches node `SCRIPT_ERR_MUST_USE_FORKID` and closes a replay-style + acceptance. Callers validating pre-UAHF history must not set + `.enableForkID`. +- **`.chronicle` for older outputs.** `.chronicle` is a block-level flag. + Only `.afterChronicle` implies it. For a spend mined at or after Chronicle + activation (mainnet height 943,816) of an `.afterGenesis` or + `.beforeGenesis` output, the caller must pass `.chronicle` to match the + node. Without it Swift is stricter than the node: it rejects `0x20` hash + types and keeps the malleability rules for transaction versions above 1. +- **`.bip143SignatureHash`.** Under strict encoding it only requires the + ForkID bit; a signature without it fails with `invalidSignatureHashType`. + It no longer selects the ForkID digest. That digest is used only with + `.enableForkID`, and without `.enableForkID` a ForkID signature fails with + `illegalForkID`. Use it with `.enableForkID`, where it changes only which + failure is reported. +- **Signature script-code size.** The script code of a signature check, which + under `.chronicle` can be the unlocking script plus the locking script, is + bounded only by the context's `TransactionLimits.maximumScriptByteCount` + and fails with `ScriptExecutionError.transaction(.scriptTooLarge)`. The + node has no such bound; this is a local resource stop. + ## Not changed -- Node also bounds arithmetic results (`OP_ADD`, `OP_MUL` and others) by the - script-number length. Swift bounds them by the push limit. This is outside - T1 to T10 and remains open. +- The node checks SIGPUSHONLY only when `SCRIPT_GENESIS` or + `SCRIPT_CHRONICLE` is set (lines 2321-2333). Swift checks it whenever + `.signaturePushOnly` is passed, so a caller that sets it for a spend in + a block before Genesis activation is stricter than the node. - Signing stays ForkID-only (COMP-023). The interpreter now validates Chronicle/OTDA signatures, but `ForkIDSignatureHashType` does not create them. @@ -93,5 +134,5 @@ is pinned in `NodeConformanceRegressionTests`. ## Tests `Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift` -runs all 21 TypeScript node-conformance vectors and a test for each item -above. Each test fails on the code before this ruling. +runs all 21 TypeScript node-conformance vectors and pins the behaviour +introduced by this ruling, with a test for each item above. diff --git a/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift b/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift index 5d3cc01..9c04773 100644 --- a/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift +++ b/Sources/BSVInterpreter/ScriptExecutionConfiguration.swift @@ -28,6 +28,17 @@ public struct ScriptVerificationFlags: OptionSet, Hashable, Sendable { public static let signaturePushOnly = Self(rawValue: 1 << 10) public static let enableForkID = Self(rawValue: 1 << 11) public static let strictEncoding = Self(rawValue: 1 << 12) + /// Under ``strictEncoding``, requires every non-empty signature's hash + /// type to carry the ForkID bit; one without it fails with + /// ``ScriptConsensusFailure/invalidSignatureHashType(_:)``. + /// + /// The flag does not select the digest. As in SV Node, the ForkID (BIP143) + /// digest is used only when ``enableForkID`` is set, and without + /// ``enableForkID`` a ForkID signature fails with + /// ``ScriptConsensusFailure/illegalForkID(_:)`` under strict encoding. Use + /// the flag together with ``enableForkID``; ``enableForkID`` alone already + /// rejects a signature without the ForkID bit, so the flag changes only + /// which failure is reported. public static let bip143SignatureHash = Self(rawValue: 1 << 13) public static let minimalIf = Self(rawValue: 1 << 14) @@ -44,6 +55,13 @@ public struct ScriptVerificationFlags: OptionSet, Hashable, Sendable { /// spending transaction's version, read as a signed 32-bit value, is /// greater than one. ``ScriptExecutionEra/afterChronicle`` always implies /// this flag. + /// + /// For an output from ``ScriptExecutionEra/beforeGenesis`` or + /// ``ScriptExecutionEra/afterGenesis``, the caller must set this flag when + /// the spending transaction is in a block at or after Chronicle activation + /// (mainnet height 943,816). Without it the interpreter is stricter than + /// the node for such a spend: it rejects `SIGHASH_CHRONICLE` signatures + /// and keeps the malleability rules for transaction versions above one. public static let chronicle = Self(rawValue: 1 << 15) } diff --git a/Sources/BSVInterpreter/VM/ScriptMachine.swift b/Sources/BSVInterpreter/VM/ScriptMachine.swift index 273e3cb..d99d79f 100644 --- a/Sources/BSVInterpreter/VM/ScriptMachine.swift +++ b/Sources/BSVInterpreter/VM/ScriptMachine.swift @@ -813,6 +813,15 @@ package struct ScriptMachine { } catch let error as ScriptNumberError { throw ScriptExecutionError.scriptNumber(error) } + // After Genesis the node's big-number operators reject a result + // longer than the number limit (script_num.cpp:166, 196, 216). Only + // ADD, SUB, MUL and the one-operand forms built on them can grow a + // value; every other result is no longer than an operand that was + // already checked. Before Genesis the node computes in int64 and + // allows five-byte results. + if configuration.era != .beforeGenesis { + try checkNumberSize(encoded.count) + } try checkElementResultSize(encoded.count) mainStack.push(encoded) } @@ -1136,24 +1145,25 @@ package struct ScriptMachine { /// SV Node `CheckSignatureEncoding`: DER, then low S, then the hash type. /// Returns the parsed signature, or `nil` for an empty signature or one - /// that does not parse when no DER rule applies. + /// whose scalars cannot be used, so that the check fails without an error. + /// + /// The DER rule is the node's structural `IsValidSignatureEncoding`. It + /// does not check the scalar range: a structurally valid signature with + /// `r` or `s` zero or at least the curve order passes it, and the node's + /// lax parser then reads it as the zero signature, which is low S and + /// never verifies. private func checkSignatureEncoding(_ signatureWithHashType: [UInt8]) throws -> ECDSASignature? { guard let rawHashType = signatureWithHashType.last else { return nil } let requiresStrictDER = configuration.flags.contains(.strictEncoding) || configuration.flags.contains(.derSignatures) || configuration.flags.contains(.lowS) - var signature: ECDSASignature? - do { - signature = try ECDSASignature( - scriptBytes: Array(signatureWithHashType.dropLast()), - strict: requiresStrictDER - ) - } catch { - if requiresStrictDER { - throw ScriptExecutionError.consensus(.invalidSignatureEncoding) - } - signature = nil + if requiresStrictDER, !Self.isValidSignatureEncoding(signatureWithHashType) { + throw ScriptExecutionError.consensus(.invalidSignatureEncoding) } + let signature = try? ECDSASignature( + scriptBytes: Array(signatureWithHashType.dropLast()), + strict: requiresStrictDER + ) if configuration.flags.contains(.lowS), enforcesNonMalleability, let signature, !signature.isLowS { throw ScriptExecutionError.consensus(.invalidSignatureEncoding) @@ -1162,6 +1172,30 @@ package struct ScriptMachine { return signature } + /// SV Node `IsValidSignatureEncoding` (interpreter.cpp:177-235): the + /// structural DER rules over a signature followed by its hash-type byte. + static func isValidSignatureEncoding(_ signature: [UInt8]) -> Bool { + let size = signature.count + guard (9...73).contains(size), + signature[0] == 0x30, + Int(signature[1]) == size - 3 + else { return false } + let lengthR = Int(signature[3]) + guard 5 + lengthR < size else { return false } + let lengthS = Int(signature[5 + lengthR]) + guard lengthR + lengthS + 7 == size, + signature[2] == 0x02, + lengthR != 0, + signature[4] & 0x80 == 0, + !(lengthR > 1 && signature[4] == 0x00 && signature[5] & 0x80 == 0), + signature[lengthR + 4] == 0x02, + lengthS != 0, + signature[lengthR + 6] & 0x80 == 0, + !(lengthS > 1 && signature[lengthR + 6] == 0x00 && signature[lengthR + 7] & 0x80 == 0) + else { return false } + return true + } + /// SV Node `CheckSignatureEncoding` hash-type rules under STRICTENC. private func checkHashTypeEncoding(_ rawHashType: UInt8) throws { guard configuration.flags.contains(.strictEncoding) else { return } @@ -1222,10 +1256,7 @@ package struct ScriptMachine { return try transaction.forkIDSignatureHash( inputIndex: context.inputIndex, rawHashType: rawHashType, - scriptCode: try Script( - bytes: scriptCode, - maximumByteCount: configuration.resourceLimits.maximumScriptByteCount - ), + scriptCodeBytes: scriptCode, limits: context.transactionLimits ) } diff --git a/Sources/BSVTransaction/ForkIDSignatureHash.swift b/Sources/BSVTransaction/ForkIDSignatureHash.swift index e9f5d96..100dc5f 100644 --- a/Sources/BSVTransaction/ForkIDSignatureHash.swift +++ b/Sources/BSVTransaction/ForkIDSignatureHash.swift @@ -87,11 +87,31 @@ public extension Transaction { rawHashType: UInt8, scriptCode: Script, limits: TransactionLimits + ) throws -> Hash256 { + try forkIDSignatureHash( + inputIndex: inputIndex, + rawHashType: rawHashType, + scriptCodeBytes: scriptCode.bytes, + limits: limits + ) + } + + /// Returns the ForkID digest over raw script-code bytes. + /// + /// The interpreter builds script code that is not itself one script, such + /// as an unlocking script followed by its locking script under Chronicle + /// rules. The only size bound is `limits.maximumScriptByteCount`, which + /// fails with ``TransactionError/scriptTooLarge(actual:maximum:)``. + package func forkIDSignatureHash( + inputIndex: Int, + rawHashType: UInt8, + scriptCodeBytes: [UInt8], + limits: TransactionLimits ) throws -> Hash256 { BSVHashing.sha256d(try forkIDSignaturePreimage( inputIndex: inputIndex, rawHashType: rawHashType, - scriptCode: scriptCode, + scriptCodeBytes: scriptCodeBytes, limits: limits )) } @@ -101,6 +121,20 @@ public extension Transaction { rawHashType: UInt8, scriptCode: Script?, limits: TransactionLimits + ) throws -> [UInt8] { + try forkIDSignaturePreimage( + inputIndex: inputIndex, + rawHashType: rawHashType, + scriptCodeBytes: scriptCode?.bytes, + limits: limits + ) + } + + private func forkIDSignaturePreimage( + inputIndex: Int, + rawHashType: UInt8, + scriptCodeBytes: [UInt8]?, + limits: TransactionLimits ) throws -> [UInt8] { guard inputs.indices.contains(inputIndex) else { throw TransactionError.invalidInputIndex(inputIndex) @@ -112,10 +146,10 @@ public extension Transaction { // This validates every collection/script against caller-selected // bounds before any aggregate serialization or hashing begins. _ = try serializedByteCount(limits: limits) - let committedScript = scriptCode ?? sourceOutput.lockingScript - guard UInt64(committedScript.byteCount) <= limits.maximumScriptByteCount else { + let committedScript = scriptCodeBytes ?? sourceOutput.lockingScript.bytes + guard UInt64(committedScript.count) <= limits.maximumScriptByteCount else { throw TransactionError.scriptTooLarge( - actual: UInt64(committedScript.byteCount), + actual: UInt64(committedScript.count), maximum: limits.maximumScriptByteCount ) } @@ -165,7 +199,7 @@ public extension Transaction { hashOutputs = zeroHash } - let scriptLength = committedScript.byteCount + let scriptLength = committedScript.count let (fixedAndPrefix, fixedOverflow) = 156.addingReportingOverflow( CompactSize.encodedLength(of: UInt64(scriptLength)) ) @@ -178,7 +212,7 @@ public extension Transaction { writer.write(hashPreviousOutputs) writer.write(hashSequences) writer.write(inputs[inputIndex].previousOutput.wireBytes) - writer.writeVarBytes(committedScript.bytes) + writer.writeVarBytes(committedScript) writer.writeUInt64LE(sourceOutput.satoshis) writer.writeUInt32LE(inputs[inputIndex].sequence) writer.write(hashOutputs) diff --git a/Sources/BSVTransaction/LegacySignatureHash.swift b/Sources/BSVTransaction/LegacySignatureHash.swift index 5d59f26..9fa59ad 100644 --- a/Sources/BSVTransaction/LegacySignatureHash.swift +++ b/Sources/BSVTransaction/LegacySignatureHash.swift @@ -80,21 +80,6 @@ public extension Transaction { return Self.digestLegacySignatureMaterial(material) } - package func legacySignatureHash( - inputIndex: Int, - rawHashType: UInt8, - scriptCode: Script, - limits: TransactionLimits - ) throws -> Hash256 { - let material = try legacySignatureMaterial( - inputIndex: inputIndex, - rawHashType: rawHashType, - scriptCode: scriptCode, - limits: limits - ) - return Self.digestLegacySignatureMaterial(material) - } - /// Returns the legacy digest over script-code bytes whose declared /// CompactSize length may differ from the bytes written. /// diff --git a/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift index d992f0f..8b2f840 100644 --- a/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift +++ b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift @@ -862,3 +862,272 @@ private func subtract(_ value: [UInt8], from minuend: [UInt8]) -> [UInt8] { } return result } + +// MARK: - Review follow-ups + +extension NodeConformanceRegressionTests { + private static let generatorPublicKeyHex = + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + + @Test("a structurally valid DER signature with unusable scalars fails CHECKSIG without an error") + func outOfRangeScalarsFailWithoutError() throws { + // node:177-235 IsValidSignatureEncoding is structural only; the lax + // parser reads r or s outside 1.. ScriptExecutionResult { + let standard = ScriptResourceLimits.standard + return try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: .afterChronicle, + flags: [.enableForkID], + resourceLimits: ScriptResourceLimits( + maximumScriptByteCount: scriptLimit, + maximumPushDataByteCount: standard.maximumPushDataByteCount, + maximumStackItemCount: standard.maximumStackItemCount, + maximumStackMemoryByteCount: standard.maximumStackMemoryByteCount, + maximumOperationCountPerScript: standard.maximumOperationCountPerScript, + maximumConditionalDepth: standard.maximumConditionalDepth, + maximumScriptNumberByteCount: standard.maximumScriptNumberByteCount + ) + ), + context: ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: try TransactionLimits( + maximumTransactionByteCount: 100_000, + maximumInputCount: 10, + maximumOutputCount: 10, + maximumScriptByteCount: transactionScriptLimit + ) + ) + ) + } + // The script resource limit bounds each script, not the combined + // script code, so this no longer escapes as a raw ScriptError. + #expect(try execute(scriptLimit: size, transactionScriptLimit: 100_000).stack == [[], [1]]) + // The transaction limit bounds the digest's script code. + #expect(throws: ScriptExecutionError.transaction( + .scriptTooLarge(actual: UInt64(size + 1), maximum: UInt64(size)) + )) { + try execute(scriptLimit: 100_000, transactionScriptLimit: UInt64(size)) + } + } + + @Test("bip143SignatureHash only requires the ForkID bit and does not select the digest") + func bip143SignatureHashFlag() throws { + let key = try PrivateKey(Array(repeating: 0, count: 31) + [13]) + let lock = try Script.payToPublicKey(key.publicKey, maximumByteCount: 100) + let base = try simpleTransaction(version: 2, unlocking: [], lock: lock) + func spend(hashType: UInt8, flags: ScriptVerificationFlags) throws -> ScriptExecutionResult { + var transaction = base + let digest = hashType & 0x40 != 0 + ? try transaction.forkIDSignatureHash(inputIndex: 0, scriptCode: lock, limits: Self.limits) + : try transaction.legacySignatureHash(inputIndex: 0, scriptCode: lock, limits: Self.limits) + let element = try key.sign(digest: digest).derBytes + [hashType] + transaction.inputs[0].unlockingScript = try Script( + bytes: [UInt8(element.count)] + element, + maximumByteCount: 100 + ) + return try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration( + era: .afterGenesis, + flags: flags, + resourceLimits: .standard + ), + context: ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: Self.limits + ) + ) + } + #expect(try spend(hashType: 0x41, flags: [.enableForkID, .bip143SignatureHash]).stack == [[1]]) + // Without enableForkID a ForkID signature is illegal (node:296-300), + // whatever this flag says. + #expect(throws: ScriptExecutionError.consensus(.illegalForkID(0x41))) { + try spend(hashType: 0x41, flags: [.strictEncoding, .bip143SignatureHash]) + } + // With enableForkID a legacy signature fails either way; the flag only + // changes which failure is reported. + #expect(throws: ScriptExecutionError.consensus(.invalidSignatureHashType(0x01))) { + try spend(hashType: 0x01, flags: [.enableForkID, .bip143SignatureHash]) + } + #expect(throws: ScriptExecutionError.consensus(.illegalForkID(0x01))) { + try spend(hashType: 0x01, flags: [.enableForkID]) + } + #expect(try spend(hashType: 0x01, flags: []).stack == [[1]]) + } + + @Test("Chronicle relaxes CHECKMULTISIG NULLFAIL for version two") + func multiSignatureNullFailRelaxation() throws { + // node:1640-1649: dummy, a failing one-byte signature, 1-of-1, NOT. + let lock = "00" + "0101" + "51" + "21" + Self.generatorPublicKeyHex + "51" + "ae91" + #expect(throws: ScriptExecutionError.consensus(.nullFail)) { + try run(lock: lock, era: .afterChronicle, flags: [.nullFail], context: true, version: 1) + } + #expect(try run( + lock: lock, era: .afterChronicle, flags: [.nullFail], context: true, version: 2 + ).stack == [[1]]) + } + + @Test("a CHECKMULTISIG in the unlocking script also commits to the locking script under Chronicle") + func chronicleUnlockingMultiSignatureScriptCode() throws { + // node:1568-1576: scriptCode += scriptPubKey when CHRONICLE is set. + let key = try PrivateKey(Array(repeating: 0, count: 31) + [15]) + let lock = try Script(bytes: [Opcode.one.rawValue], maximumByteCount: 1) + let scriptCode = try Script( + bytes: [Opcode.checkMultiSigVerify.rawValue, Opcode.one.rawValue], + maximumByteCount: 2 + ) + var transaction = try simpleTransaction(version: 2, unlocking: [], lock: lock) + let digest = try transaction.forkIDSignatureHash( + inputIndex: 0, + scriptCode: scriptCode, + limits: Self.limits + ) + let element = try key.sign(digest: digest).derBytes + [0x41] + let publicKey = key.publicKey.compressedBytes + transaction.inputs[0].unlockingScript = try Script( + bytes: [Opcode.zero.rawValue, UInt8(element.count)] + element + [Opcode.one.rawValue] + + [UInt8(publicKey.count)] + publicKey + + [Opcode.one.rawValue, Opcode.codeSeparator.rawValue, Opcode.checkMultiSigVerify.rawValue], + maximumByteCount: 200 + ) + let context = ScriptExecutionContext( + transaction: transaction, + inputIndex: 0, + spentOutput: TransactionOutput(satoshis: 1_000, lockingScript: lock), + transactionLimits: Self.limits + ) + func execute(_ era: ScriptExecutionEra, _ flags: ScriptVerificationFlags) throws -> ScriptExecutionResult { + try ScriptInterpreter.execute( + unlockingScript: transaction.inputs[0].unlockingScript, + lockingScript: lock, + configuration: ScriptExecutionConfiguration(era: era, flags: flags, resourceLimits: .standard), + context: context + ) + } + #expect(try execute(.afterChronicle, [.enableForkID]).stack == [[1]]) + #expect(try execute(.afterGenesis, [.enableForkID, .chronicle]).stack == [[1]]) + #expect(throws: ScriptExecutionError.consensus(.checkMultiSignatureVerifyFailed)) { + try execute(.afterGenesis, [.enableForkID]) + } + } + + @Test("an empty signature removes OP_0 instructions from the legacy script code") + func emptySignatureRemovesOpZero() { + // node:247-256: CScript(vchSig) of an empty signature is OP_0. The + // removal cannot change a verdict, because an empty signature never + // verifies, so it is pinned at the FindAndDelete level. + let pattern = ScriptMachine.pushEncoding([]) + #expect(ScriptMachine.findAndDelete(hex("0051000100ac"), pattern: pattern) == hex("510100ac")) + #expect(ScriptMachine.findAndDelete(hex("51ac"), pattern: pattern) == hex("51ac")) + } + + @Test("OP_LSHIFTNUM of zero accepts exactly the number limit in added bytes") + func zeroLeftShiftBoundary() throws { + // 256,000,007 / 8 == 32,000,000 bytes: allowed; 256,000,008 is not. + #expect(try run(lock: "00040740420fb60087", era: .afterChronicle).stack == [[1]]) + #expect(throws: ScriptExecutionError.consensus( + .numberTooLarge(actual: 32_000_001, maximum: 32_000_000) + )) { + try run(lock: "00040840420fb67551", era: .afterChronicle) + } + } + + private func runBytes(lock: [UInt8], era: ScriptExecutionEra) throws -> ScriptExecutionResult { + try ScriptInterpreter.execute( + unlockingScript: try Script(bytes: [], maximumByteCount: 1), + lockingScript: try Script(bytes: lock, maximumByteCount: lock.count), + configuration: ScriptExecutionConfiguration(era: era, resourceLimits: .standard), + context: nil + ) + } +} + +private func le32(_ value: Int) -> [UInt8] { + (0..<4).map { UInt8(truncatingIfNeeded: value >> (8 * $0)) } +} diff --git a/Tests/BSVTransactionTests/LegacySignatureHashTests.swift b/Tests/BSVTransactionTests/LegacySignatureHashTests.swift index 8e81c36..9c14a87 100644 --- a/Tests/BSVTransactionTests/LegacySignatureHashTests.swift +++ b/Tests/BSVTransactionTests/LegacySignatureHashTests.swift @@ -88,7 +88,8 @@ struct LegacySignatureHashTests { #expect(try transaction.legacySignatureHash( inputIndex: 1, rawHashType: 0x43, - scriptCode: scriptCode, + scriptCodeBytes: scriptCode.bytes, + encodedScriptCodeLength: scriptCode.byteCount, limits: limits ).bytes == expected) } From 19df6abdfc997a05369db8f9c732f86195003770 Mon Sep 17 00:00:00 2001 From: Luke Rohenaz Date: Mon, 16 Nov 2026 19:09:17 +0000 Subject: [PATCH 3/3] Apply LOW_S to r = 0 signatures as the node's lax parser does A structurally valid signature that the strict parser rejects is now checked for LOW_S the way CPubKey::CheckLowS reads it: values longer than 32 bytes or not below the curve order read as the zero signature, otherwise the real s is compared with half the order. So r = 0 with a high s fails LOW_S, as in the node, instead of failing the signature check. Fix the IsValidSignatureEncoding line range and the pre-Genesis result-size wording, and add a 2MUL result-bound test. --- ...MP-064-Interpreter-Node-Chronicle-Rules.md | 12 ++-- Sources/BSVInterpreter/VM/ScriptMachine.swift | 70 ++++++++++++++++--- .../NodeConformanceRegressionTests.swift | 68 ++++++++++++++++++ 3 files changed, 136 insertions(+), 14 deletions(-) diff --git a/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md index 4bdeed4..ea67c3f 100644 --- a/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md +++ b/Documentation/Compatibility/Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md @@ -52,15 +52,19 @@ Swift follows SV Node v1.2.3 for the rules below. References are to `MUST_USE_FORKID` when ForkID is enabled and the bit is missing (line 306). 8. **Structural DER only.** The DER rule is the node's structural - `IsValidSignatureEncoding` (lines 177-235). A structurally valid + `IsValidSignatureEncoding` (lines 177-245). A structurally valid signature whose `r` or `s` is zero or not below the curve order passes - it, counts as low S, and fails verification without an error, as the - node's lax parser reads it as the zero signature. NULLFAIL still applies. + it and fails verification without an error. LOW_S follows the node's lax + parser (`CPubKey::CheckLowS`, `src/pubkey.cpp:32-175, 353-363`): a value + longer than 32 bytes or not below the curve order makes it read the zero + signature, which is low S; otherwise the real `s` is checked, so `r = 0` + with `s` above half the order fails LOW_S. NULLFAIL still applies. 9. **Arithmetic results.** After Genesis, a numeric result longer than the script-number limit fails with `numberTooLarge`, as the node's big-number `+=`, `-=` and `*=` do (`script_num.cpp:166, 196, 216`). This covers `OP_ADD`, `OP_SUB`, `OP_MUL`, `OP_1ADD`, `OP_1SUB` and `OP_2MUL`. Before - Genesis the node computes in int64 and five-byte results stay valid. + Genesis the node computes in int64 with no result check, so a result can + be up to eight bytes (`OP_MUL`). 10. **ForkID digest only with ForkID enabled (T8).** A hash type with the ForkID bit, verified without `.enableForkID`, uses the original digest. 11. **Original-digest script code (T9).** `SerializeScriptCode` (line 1864) diff --git a/Sources/BSVInterpreter/VM/ScriptMachine.swift b/Sources/BSVInterpreter/VM/ScriptMachine.swift index d99d79f..1c587b1 100644 --- a/Sources/BSVInterpreter/VM/ScriptMachine.swift +++ b/Sources/BSVInterpreter/VM/ScriptMachine.swift @@ -817,8 +817,8 @@ package struct ScriptMachine { // longer than the number limit (script_num.cpp:166, 196, 216). Only // ADD, SUB, MUL and the one-operand forms built on them can grow a // value; every other result is no longer than an operand that was - // already checked. Before Genesis the node computes in int64 and - // allows five-byte results. + // already checked. Before Genesis the node computes in int64 with no + // result check, so a result can be up to eight bytes (OP_MUL). if configuration.era != .beforeGenesis { try checkNumberSize(encoded.count) } @@ -1148,10 +1148,13 @@ package struct ScriptMachine { /// whose scalars cannot be used, so that the check fails without an error. /// /// The DER rule is the node's structural `IsValidSignatureEncoding`. It - /// does not check the scalar range: a structurally valid signature with - /// `r` or `s` zero or at least the curve order passes it, and the node's - /// lax parser then reads it as the zero signature, which is low S and - /// never verifies. + /// does not check the scalar range, so a structurally valid signature + /// with `r` or `s` zero or at least the curve order passes it. The node's + /// low-S rule then reads the signature with its lax parser + /// (`CPubKey::CheckLowS`), which keeps `(r, s)` unless a value is longer + /// than 32 bytes or not below the curve order, and only then reads the + /// zero signature. So `r = 0` with a high `s` still fails LOW_S, while an + /// overflowing signature counts as low S. Neither verifies. private func checkSignatureEncoding(_ signatureWithHashType: [UInt8]) throws -> ECDSASignature? { guard let rawHashType = signatureWithHashType.last else { return nil } let requiresStrictDER = configuration.flags.contains(.strictEncoding) @@ -1164,15 +1167,62 @@ package struct ScriptMachine { scriptBytes: Array(signatureWithHashType.dropLast()), strict: requiresStrictDER ) - if configuration.flags.contains(.lowS), enforcesNonMalleability, - let signature, !signature.isLowS { - throw ScriptExecutionError.consensus(.invalidSignatureEncoding) + if configuration.flags.contains(.lowS), enforcesNonMalleability { + let isLowS = signature?.isLowS + ?? Self.laxParseIsLowS(Array(signatureWithHashType.dropLast())) + if !isLowS { + throw ScriptExecutionError.consensus(.invalidSignatureEncoding) + } } try checkHashTypeEncoding(rawHashType) return signature } - /// SV Node `IsValidSignatureEncoding` (interpreter.cpp:177-235): the + /// SV Node `CPubKey::CheckLowS` over a structurally valid DER signature + /// (without its hash type) that the strict parser rejected because a + /// scalar is zero or out of range (pubkey.cpp:32-175, 353-363). + /// + /// The lax parser strips leading zeros. When either value is longer than + /// 32 bytes or not below the curve order, it reads the zero signature, + /// which is low S. Otherwise it keeps the values, so the real `s` is + /// compared with half the curve order. + static func laxParseIsLowS(_ der: [UInt8]) -> Bool { + guard der.count >= 8 else { return true } + let lengthR = Int(der[3]) + guard 6 + lengthR < der.count else { return true } + let r = Array(der[4..<(4 + lengthR)]) + let lengthS = Int(der[5 + lengthR]) + guard 6 + lengthR + lengthS <= der.count else { return true } + let s = Array(der[(6 + lengthR)..<(6 + lengthR + lengthS)]) + guard let r32 = paddedScalar(r), let s32 = paddedScalar(s), + r32.lexicographicallyPrecedes(curveOrder), + s32.lexicographicallyPrecedes(curveOrder) + else { return true } + return !halfCurveOrder.lexicographicallyPrecedes(s32) + } + + /// A big-endian integer as 32 bytes, or `nil` when it needs more. + private static func paddedScalar(_ bytes: [UInt8]) -> [UInt8]? { + let magnitude = bytes.drop { $0 == 0 } + guard magnitude.count <= 32 else { return nil } + return Array(repeating: 0, count: 32 - magnitude.count) + magnitude + } + + private static let curveOrder: [UInt8] = [ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, + 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, + ] + + private static let halfCurveOrder: [UInt8] = [ + 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d, + 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b, 0x20, 0xa0, + ] + + /// SV Node `IsValidSignatureEncoding` (interpreter.cpp:177-245): the /// structural DER rules over a signature followed by its hash-type byte. static func isValidSignatureEncoding(_ signature: [UInt8]) -> Bool { let size = signature.count diff --git a/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift index 8b2f840..c98a200 100644 --- a/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift +++ b/Tests/BSVInterpreterTests/NodeConformance/NodeConformanceRegressionTests.swift @@ -903,6 +903,74 @@ extension NodeConformanceRegressionTests { #expect(!ScriptMachine.isValidSignatureEncoding(hex("300602010002010101") + [0])) } + @Test("LOW_S reads r = 0 with a high s the way the node's lax parser does") + func lowSOnZeroR() throws { + // node interpreter.cpp:282-289 and pubkey.cpp:32-175, 353-363: r = 0 is + // not an overflow, so the lax parse keeps s = n - 1, which is high. + let nMinusOne = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" + let signature = "29" + "3026020100022100" + nMinusOne + "01" + let key = "21" + Self.generatorPublicKeyHex + let checkSig = signature + key + "ac91" + let checkMultiSig = "00" + signature + "51" + key + "51" + "ae91" + for lock in [checkSig, checkMultiSig] { + #expect(throws: ScriptExecutionError.consensus(.invalidSignatureEncoding)) { + try run(lock: lock, era: .afterGenesis, flags: [.lowS], context: true, version: 1) + } + // Chronicle relaxes LOW_S for version two; the check then fails. + #expect(try run( + lock: lock, era: .afterChronicle, flags: [.lowS], context: true, version: 2 + ).stack == [[1]]) + #expect(try run(lock: lock, era: .afterGenesis, flags: [.derSignatures], context: true).stack == [[1]]) + } + // A low s with r = 0 passes LOW_S and simply fails. + let lowS = "09" + "300602010002010101" + #expect(try run(lock: lowS + key + "ac91", era: .afterGenesis, flags: [.lowS], context: true).stack == [[1]]) + // Overflowing values read as the zero signature, which is low S. + let order = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141" + #expect(ScriptMachine.laxParseIsLowS(hex("3026022100" + order + "020101"))) + #expect(!ScriptMachine.laxParseIsLowS(hex("3026020100022100" + nMinusOne))) + #expect(ScriptMachine.laxParseIsLowS(hex("3026020101022100" + String(repeating: "ff", count: 32)))) + } + + @Test("2MUL results are bounded by the number limit") + func twoMulResultBound() throws { + // 2MUL is bn += bn (interpreter.cpp:1247-1249), checked like ADD. + // A local 1,000-byte number budget exercises the same check cheaply. + let size = 1_000 + let largest = Array(repeating: UInt8(0xff), count: size - 1) + [0x7f] + let lock = [Opcode.pushData2.rawValue, UInt8(size & 0xff), UInt8(size >> 8)] + largest + + [0x8d, Opcode.drop.rawValue, Opcode.one.rawValue] + let standard = ScriptResourceLimits.standard + let limits = ScriptResourceLimits( + maximumScriptByteCount: standard.maximumScriptByteCount, + maximumPushDataByteCount: standard.maximumPushDataByteCount, + maximumStackItemCount: standard.maximumStackItemCount, + maximumStackMemoryByteCount: standard.maximumStackMemoryByteCount, + maximumOperationCountPerScript: standard.maximumOperationCountPerScript, + maximumConditionalDepth: standard.maximumConditionalDepth, + maximumScriptNumberByteCount: size + ) + func execute(_ bytes: [UInt8]) throws -> ScriptExecutionResult { + try ScriptInterpreter.execute( + unlockingScript: try Script(bytes: [], maximumByteCount: 1), + lockingScript: try Script(bytes: bytes, maximumByteCount: bytes.count), + configuration: ScriptExecutionConfiguration(era: .afterChronicle, resourceLimits: limits), + context: nil + ) + } + #expect(throws: ScriptExecutionError.resourceBudgetExceeded( + .scriptNumberByteCount(actual: size + 1, maximum: size) + )) { + try execute(lock) + } + // 2MUL of a value one byte shorter fits. + let shorter = Array(repeating: UInt8(0xff), count: size - 2) + [0x3f] + #expect(try execute( + [Opcode.pushData2.rawValue, UInt8((size - 1) & 0xff), UInt8((size - 1) >> 8)] + shorter + + [0x8d, Opcode.drop.rawValue, Opcode.one.rawValue] + ).stack == [[1]]) + } + @Test("ADD, SUB, MUL and 1ADD results are bounded by the number limit after Genesis") func arithmeticResultBound() throws { // node script_num.cpp:166, 196, 216: bint results longer than the