Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/PropertyAuditTests/UTXOCoinsProperties.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraMath44import QyvoraSymmetric45import Testing4647@testable import QyvoraBitcoin48@testable import QyvoraCore49@testable import QyvoraSecp256k15051// Invariants of the Litecoin, Dogecoin and Bitcoin Cash code: CashAddr error detection, address / script round trips52// and the absence of cross-coin acceptance, the builder's value conservation, fee and dust rules per coin, the53// signature type of each coin, PSBTs carrying previous transactions (the fee shown is the fee paid), and replay54// protection between Bitcoin Cash and the chains that sign with the original digest.5556private enum UP {57 static let networks: [BitcoinNetwork] = [.litecoin, .litecoinTestnet, .dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet]58 static let charset = Array("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)5960 /// An account with coins of its own addresses, each created by a transaction made here.61 struct Wallet {62 let account: UTXOAccount63 var utxos: [BitcoinUTXO] = []64 var previous: [String: BitcoinTransaction] = [:]65 }6667 static func wallet(_ rng: inout AuditRNG, network: BitcoinNetwork, coins: Int, purpose: UTXOAccountPurpose? = nil) throws -> Wallet {68 var w = Wallet(account: try UTXOAccount(master: try ExtendedKey.master(seed: rng.bytes(32)), network: network, purpose: purpose))69 let unit: UInt64 = network.coin == .dogecoin ? 100_000_000 : 10_00070 for _ in 0..<coins {71 let chain: UTXOAccount.Chain = rng.bool() ? .receive : .change72 let index = UInt32(rng.int(0...12))73 let script = try w.account.scriptPubKey(chain: chain, index: index)74 let value = unit * UInt64(rng.pick([1, 3, 10, 50, 250, 1_000, 40_000, rng.int(1...100_000)]))75 let filler = (0..<rng.int(0...2)).map { _ in BitcoinTransaction.Output(value: UInt64(rng.int(0...5_000)), scriptPubKey: [0x6a, 0x01, UInt8(rng.int(0...255))]) }76 let funding = BitcoinTransaction(version: 1, inputs: [.init(previousOutput: BitcoinOutPoint(hash: rng.bytes(32), index: UInt32(rng.int(0...3)))!, scriptSig: [0x51])],77 outputs: filler + [.init(value: value, scriptPubKey: script)], lockTime: UInt32(rng.int(0...1_000)))78 if w.previous[funding.txid] != nil { continue }79 w.previous[funding.txid] = funding80 w.utxos.append(BitcoinUTXO(outPoint: BitcoinOutPoint(hash: funding.txidBytes, index: UInt32(filler.count))!, value: value, scriptPubKey: script,81 confirmations: UInt32(rng.int(1...50)), derivation: .init(chain: chain.rawValue, index: index)))82 }83 return w84 }8586 static func destination(_ rng: inout AuditRNG, network: BitcoinNetwork) -> Bytes {87 if network.supportsSegWit, rng.bool() { return try! BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20)) }88 return rng.int(0...3) == 0 ? try! BitcoinScript.p2sh(scriptHash: rng.bytes(20)) : try! BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20))89 }9091 static func rate(_ rng: inout AuditRNG, network: BitcoinNetwork) -> FeeRate {92 let floor = FeeRate.minimum(for: network).milliSatPerVByte, cap = FeeRate.maximum(for: network).milliSatPerVByte93 return FeeRate(milliSatPerVByte: rng.pick([floor, floor, floor + 1, floor * 2, floor * 5, min(cap, floor * 40), floor + UInt64(rng.int(0...Int(min(cap - floor, 50_000_000))))]))94 }95}9697@Suite struct UTXOCoinsProperties {98 // MARK: CashAddr99100 /// The checksum is a BCH code over GF(32) that detects any six substitutions in a 112-character payload: every101 /// single and double substitution tried here must be refused, in the payload and in the prefix.102 @Test func cashAddrRoundTripsAndErrorDetection() {103 let seed = AuditSeed.make("utxo.cashaddr.error-detection")104 var rng = AuditRNG(seed: seed)105 var prop = Prop("round trip; every single substitution, random double and triple substitutions, prefix changes, case mixing, truncation and extension refused",106 algorithm: "CashAddr", seed: seed)107 var singles = 0, doubles = 0, triples = 0108 for _ in 0..<AuditMode.cases(quick: 250, full: 4000) {109 let prefix = rng.pick(["bitcoincash", "bitcoincash", "bchtest", "bchreg", "simpleledger", "ecash", "q", String(decoding: (0..<rng.int(1...40)).map { _ in UInt8(rng.int(97...122)) }, as: UTF8.self)])110 let type = UInt8(rng.pick([0, 1, rng.int(0...15)]))111 let hash = rng.bytes(rng.pick([20, 20, 20, 24, 28, 32, 40, 48, 56, 64]))112 guard let text = CashAddr.encode(prefix: prefix, type: type, hash: hash) else {113 prop.check(false, "not encoded: \(prefix) \(type) \(hash.count)")114 continue115 }116 let expected = CashAddr.Decoded(prefix: prefix, type: type, hash: hash)117 prop.check(CashAddr.decode(text) == expected && CashAddr.decode(text.uppercased()) == expected, "round trip \(text)")118 let bytes = Array(text.utf8), body = prefix.utf8.count + 1119 prop.check(CashAddr.decode(String(decoding: bytes[body...], as: UTF8.self), defaultPrefix: prefix) == expected, "without prefix \(text)")120 // every position of the payload, two other characters each (all 31 in full mode for one address in ten)121 let exhaustive = AuditMode.isFull && rng.int(0...9) == 0122 for p in body..<bytes.count {123 let others = UP.charset.filter { $0 != bytes[p] }124 for c in exhaustive ? others : [rng.pick(others), rng.pick(others)] {125 var m = bytes126 m[p] = c127 singles += 1128 prop.check(CashAddr.decode(String(decoding: m, as: UTF8.self)) == nil, "single substitution accepted at \(p) of \(text)")129 }130 }131 for _ in 0..<60 {132 var m = bytes133 let p = rng.int(body...(bytes.count - 1))134 var q = rng.int(body...(bytes.count - 1))135 if q == p { q = p == bytes.count - 1 ? body : p + 1 }136 m[p] = rng.pick(UP.charset.filter { $0 != bytes[p] })137 m[q] = rng.pick(UP.charset.filter { $0 != bytes[q] })138 doubles += 1139 prop.check(CashAddr.decode(String(decoding: m, as: UTF8.self)) == nil, "double substitution accepted at \(p), \(q) of \(text)")140 }141 for _ in 0..<20 {142 var m = bytes143 var positions = Set<Int>()144 while positions.count < 3 { positions.insert(rng.int(body...(bytes.count - 1))) }145 for p in positions { m[p] = rng.pick(UP.charset.filter { $0 != bytes[p] }) }146 triples += 1147 prop.check(CashAddr.decode(String(decoding: m, as: UTF8.self)) == nil, "triple substitution accepted in \(text)")148 }149 // one letter of the prefix (its five low bits enter the checksum; lower-case letters differ there)150 for p in 0..<(body - 1) {151 var m = bytes152 m[p] = rng.pick((97...122).map { UInt8($0) }.filter { $0 != bytes[p] })153 prop.check(CashAddr.decode(String(decoding: m, as: UTF8.self)) == nil, "prefix substitution accepted at \(p) of \(text)")154 }155 // one letter in the other case, a character less, a character more, a second colon156 var mixed = bytes157 if let p = mixed.indices.filter({ mixed[$0] >= 97 && mixed[$0] <= 122 }).randomElement(using: &rng) {158 mixed[p] -= 32159 if mixed.contains(where: { $0 >= 97 && $0 <= 122 }) { prop.check(CashAddr.decode(String(decoding: mixed, as: UTF8.self)) == nil, "mixed case accepted: \(text)") }160 }161 prop.check(CashAddr.decode(String(decoding: bytes.dropLast(), as: UTF8.self)) == nil, "truncated \(text)")162 prop.check(CashAddr.decode(text + String(decoding: [rng.pick(UP.charset)], as: UTF8.self)) == nil, "extended \(text)")163 prop.check(CashAddr.decode(prefix + ":" + text) == nil && CashAddr.decode(text + ":") == nil, "second colon \(text)")164 prop.check(CashAddr.decode(" " + text) == nil && CashAddr.decode(text + "\n") == nil, "white space \(text)")165 }166 // bounds of the decoder: a prefix above 40 letters and text above 160 characters are refused before any work167 let long = String(repeating: "a", count: 41)168 prop.check(CashAddr.encode(prefix: long, type: 0, hash: Bytes(repeating: 0, count: 20)) == nil, "41-letter prefix encoded")169 prop.check(CashAddr.decode(String(repeating: "q", count: 200_000)) == nil && CashAddr.decode("bitcoincash:" + String(repeating: "q", count: 113)) == nil, "oversized text decoded")170 prop.check(CashAddr.decode("") == nil && CashAddr.decode(":") == nil && CashAddr.decode("bitcoincash:") == nil, "empty forms decoded")171 prop.finish(note: "\(singles) single, \(doubles) double and \(triples) triple substitutions, none accepted")172 }173174 // MARK: Addresses175176 /// address ⇄ script on the six networks, and no acceptance by another coin: the only encodings two networks share177 /// are the ones their reference clients share (Bitcoin Cash's legacy form and Bitcoin; the test-network bytes178 /// 0x6f / 0xc4), and SegWit addresses are never accepted where SegWit does not exist.179 @Test func addressScriptRoundTripAndNoCrossCoinAcceptance() throws {180 let seed = AuditSeed.make("utxo.address.roundtrip")181 var rng = AuditRNG(seed: seed)182 var prop = Prop("address(script) parses back to the script; canonical text; other coins refuse it; witness programs have no address without SegWit",183 algorithm: "addresses of Litecoin, Dogecoin, Bitcoin Cash", seed: seed)184 func coinsAccepting(_ text: String) -> Set<UTXOCoin> { Set(BitcoinNetwork.allCases.filter { !$0.isTest && (try? BitcoinAddress(text, network: $0)) != nil }.map(\.coin)) }185 for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {186 let network = rng.pick(UP.networks)187 let kind = rng.int(0...5)188 let script: Bytes189 switch kind {190 case 0, 1: script = try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20))191 case 2: script = try BitcoinScript.p2sh(scriptHash: rng.bytes(20))192 case 3: script = try BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20))193 case 4: script = try BitcoinScript.p2wsh(scriptHash: rng.bytes(32))194 default: script = try BitcoinScript.p2tr(outputKey: rng.bytes(32))195 }196 let address = try? BitcoinAddress(scriptPubKey: script, network: network)197 if kind >= 3, !network.supportsSegWit {198 prop.check(address == nil, "witness program has an address on \(network.rawValue)")199 // and the address the script has on a SegWit network is refused here200 let foreign = try BitcoinAddress(scriptPubKey: script, network: rng.pick([.mainnet, .testnet, .litecoin, .litecoinTestnet]))201 var refusal: BitcoinAddress.Error?202 do { _ = try BitcoinAddress(foreign.string, network: network) } catch { refusal = error as? BitcoinAddress.Error }203 prop.check(refusal == .wrongNetwork, "\(foreign.string) on \(network.rawValue): \(String(describing: refusal))")204 continue205 }206 guard let address else {207 prop.check(false, "no address for a standard script on \(network.rawValue)")208 continue209 }210 let parsed = try? BitcoinAddress(address.string, network: network)211 prop.check(parsed?.scriptPubKey == script && parsed?.string == address.string && parsed?.isLegacyFormat == false, "round trip \(address.string)")212 prop.check((try? BitcoinAddress(address.string.uppercased(), network: network))?.scriptPubKey == (kind >= 3 || network.cashAddrPrefix != nil ? script : nil)213 || (kind < 3 && network.cashAddrPrefix == nil), "upper-case form of \(address.string)")214 if !network.isTest {215 // main networks: exactly this coin216 prop.check(coinsAccepting(address.string) == [network.coin], "\(address.string) of \(network.rawValue) accepted by \(coinsAccepting(address.string))")217 if network.cashAddrPrefix != nil, let legacy = address.base58String {218 // the legacy form of a Bitcoin Cash address is a Bitcoin address: accepted by both, flagged on Bitcoin Cash219 prop.check(coinsAccepting(legacy) == [.bitcoin, .bitcoinCash], "legacy \(legacy) accepted by \(coinsAccepting(legacy))")220 prop.check((try? BitcoinAddress(legacy, network: network))?.isLegacyFormat == true, "legacy form not flagged: \(legacy)")221 }222 } else {223 // a test-network address is never a main-network address of any coin224 prop.check(coinsAccepting(address.string).isEmpty, "\(address.string) of \(network.rawValue) accepted on a main network")225 }226 // one character changed: never another valid address of the same network with the same script227 var bytes = Array(address.string.utf8)228 let p = rng.int(0...(bytes.count - 1))229 let replacement = rng.pick(Array("qpzry9x8gf2tvdw0s3jn54khce6mua7lABCDEFGHJKLMNPQRSTUVWXYZ123456789".utf8).filter { $0 != bytes[p] })230 bytes[p] = replacement231 let altered = try? BitcoinAddress(String(decoding: bytes, as: UTF8.self), network: network)232 prop.check(altered == nil || altered?.scriptPubKey != script || String(decoding: bytes, as: UTF8.self).lowercased() == address.string.lowercased(), "altered address gives the same script: \(address.string)")233 }234 // CashAddr of other chains and other kinds (SLP, eCash, eToken, regtest; the other Bitcoin Cash network; 32-byte235 // P2SH; token-aware types): never a recipient on Bitcoin Cash, with or without their prefix236 for _ in 0..<AuditMode.cases(quick: 200, full: 2000) {237 let hash = rng.bytes(20)238 let type = UInt8(rng.int(0...1))239 for network in [BitcoinNetwork.bitcoinCash, .bitcoinCashTestnet] {240 let own = try #require(network.cashAddrPrefix)241 for prefix in ["simpleledger", "ecash", "etoken", "bchreg", "slptest", network == .bitcoinCash ? "bchtest" : "bitcoincash"] {242 let foreign = try #require(CashAddr.encode(prefix: prefix, type: type, hash: hash))243 var refusal: BitcoinAddress.Error?244 do { _ = try BitcoinAddress(foreign, network: network) } catch { refusal = error as? BitcoinAddress.Error }245 prop.check(refusal == .wrongNetwork, "\(foreign) on \(network.rawValue): \(String(describing: refusal))")246 // its payload without the prefix: the checksum was computed with another prefix247 let body = String(foreign.dropFirst(prefix.count + 1))248 prop.check((try? BitcoinAddress(body, network: network)) == nil, "payload of \(foreign) accepted without prefix on \(network.rawValue)")249 }250 // kinds the wallet does not pay to, under the network's own prefix251 for (kind, size) in [(UInt8(2), 20), (3, 20), (1, 32), (3, 32), (0, 24)] {252 let other = try #require(CashAddr.encode(prefix: own, type: kind, hash: rng.bytes(size)))253 var refusal: BitcoinAddress.Error?254 do { _ = try BitcoinAddress(other, network: network) } catch { refusal = error as? BitcoinAddress.Error }255 prop.check(refusal == .unsupportedAddressType, "\(other) on \(network.rawValue): \(String(describing: refusal))")256 }257 }258 }259 // Litecoin's former P2SH form, Bitcoin's own, is refused on Litecoin with its own reason260 for _ in 0..<50 {261 let script = try BitcoinScript.p2sh(scriptHash: rng.bytes(20))262 let bitcoin = try BitcoinAddress(scriptPubKey: script, network: .mainnet).string263 var refusal: BitcoinAddress.Error?264 do { _ = try BitcoinAddress(bitcoin, network: .litecoin) } catch { refusal = error as? BitcoinAddress.Error }265 prop.check(refusal == .ambiguousLegacyFormat && bitcoin.hasPrefix("3"), "\(bitcoin) on Litecoin: \(String(describing: refusal))")266 prop.check((try BitcoinAddress(scriptPubKey: script, network: .litecoin)).string.hasPrefix("M"), "Litecoin P2SH does not start with M")267 }268 prop.finish()269 }270271 // MARK: Builder and signatures272273 /// Every transaction the builder makes on the six networks: exact value conservation, fee between the target and274 /// the documented tolerance, no dust, no witness script without SegWit, the network's sequence and lock-time275 /// rules; then the account signs it and every signature verifies under the coin's scheme only.276 @Test func builderAndSignatureInvariantsPerCoin() throws {277 let seed = AuditSeed.make("utxo.builder")278 var rng = AuditRNG(seed: seed)279 var prop = Prop("inputs = outputs + fee; fee ≥ rate × size and ≤ rate × size + change tolerance; no dust output; coin rules for sequence, lock time, witness, sighash byte; signed size ≤ estimate; send-max ≤ balance",280 algorithm: "transaction builder and account signatures (Litecoin, Dogecoin, Bitcoin Cash)", seed: seed)281 var built = 0, refused = 0, sendMax = 0, changeless = 0282 for _ in 0..<AuditMode.cases(quick: 360, full: 6000) {283 let network = rng.pick(UP.networks)284 let scheme = network.sighashScheme285 var w = try UP.wallet(&rng, network: network, coins: rng.int(1...6), purpose: network.supportsSegWit && rng.int(0...3) == 0 ? .bip44 : nil)286 let rate = UP.rate(&rng, network: network)287 let isMax = rng.int(0...4) == 0288 let destination = UP.destination(&rng, network: network)289 let change = try w.account.scriptPubKey(chain: .change, index: 30)290 // one time in five: one coin and an amount that leaves less than a change output is worth (no change)291 let tight = !isMax && rng.int(0...4) == 0292 if tight { w.utxos = [w.utxos[0]] }293 let total = w.utxos.reduce(UInt64(0)) { $0 + $1.value }294 var amount = isMax ? 0 : max(1, total / UInt64(rng.pick([1, 2, 2, 3, 10, 1_000, 100_000_000])))295 if tight, let inputWeight = BitcoinSizeEstimator.inputWeight(scriptPubKey: w.utxos[0].scriptPubKey, inWitnessTransaction: network.supportsSegWit) {296 let fee = rate.fee(weight: BitcoinSizeEstimator.transactionWeight(inputWeights: [inputWeight], outputScripts: [destination], hasWitness: network.supportsSegWit))297 let spare = UInt64(rng.int(0...Int(BitcoinSizeEstimator.dustThreshold(scriptPubKey: change, network: network))))298 if total > fee + spare { amount = total - fee - spare }299 }300 var request = BitcoinSpendRequest(network: network, recipients: isMax ? [] : [.init(value: amount, scriptPubKey: destination)], utxos: w.utxos, feeRate: rate,301 changeScript: rng.int(0...9) == 0 ? nil : change, sendMaxScript: isMax ? destination : nil)302 request.seed = rng.next()303 let height = UInt32(rng.int(0...6_000_000))304 request.currentHeight = rng.int(0...5) == 0 ? nil : height305 let plan: BitcoinTransactionPlan306 do { plan = try BitcoinTransactionBuilder.build(request) } catch let e as BitcoinBuildError {307 refused += 1308 // a refusal is one of the documented reasons, never a transaction309 switch e {310 case .insufficientFunds, .dustOutput, .sendMaxBelowDust, .changeScriptRequired, .feeExceedsCap: prop.check(true)311 default: prop.check(false, "unexpected refusal \(e) on \(network.rawValue)")312 }313 continue314 }315 built += 1316 let tx = plan.transaction317 let outputTotal = tx.outputs.reduce(UInt64(0)) { $0 + $1.value }318 let inputTotal = plan.inputs.reduce(UInt64(0)) { $0 + $1.value }319 prop.check(inputTotal == outputTotal + plan.fee && inputTotal <= total, "value conservation on \(network.rawValue): \(inputTotal) ≠ \(outputTotal) + \(plan.fee)")320 prop.check(Set(plan.inputs.map(\.outPoint)).count == plan.inputs.count && plan.inputs.allSatisfy { u in w.utxos.contains(u) }, "inputs are distinct coins of the wallet")321 prop.check(tx.inputs.map(\.previousOutput) == plan.inputs.map(\.outPoint), "input order")322 // fee: at least the target over the estimated size; above it only by what a change output would have cost323 let required = rate.fee(weight: plan.estimatedWeight)324 let changeScriptForBound = request.changeScript ?? change325 let tolerance = rate.fee(weight: BitcoinSizeEstimator.outputWeight(scriptPubKey: changeScriptForBound))326 + max(BitcoinSizeEstimator.dustThreshold(scriptPubKey: changeScriptForBound, network: network),327 rate.fee(weight: BitcoinSizeEstimator.inputWeight(scriptPubKey: changeScriptForBound, inWitnessTransaction: network.supportsSegWit) ?? 0))328 prop.check(plan.fee >= required, "fee \(plan.fee) below the target \(required) on \(network.rawValue)")329 if plan.changeIndex != nil || plan.sendMaxIndex != nil {330 prop.check(plan.fee == required, "fee \(plan.fee) ≠ \(required) with a change or send-max output on \(network.rawValue)")331 } else {332 changeless += 1333 // Branch and Bound adds the fees input by input, each rounded up to a whole virtual byte and a whole base334 // unit: its result may exceed the cost of change by that rounding, at most one virtual byte per input335 let rounding = rate.fee(vsize: plan.inputs.count + 2) + UInt64(plan.inputs.count + 2)336 prop.check(plan.fee - required <= tolerance + rounding, "changeless excess \(plan.fee - required) above the tolerance \(tolerance) + \(rounding) on \(network.rawValue)")337 }338 prop.check(plan.fee <= request.maximumFee && rate >= .minimum(for: network) && rate <= .maximum(for: network), "fee cap")339 // outputs: none below the network's dust threshold, change and send-max included; no witness program without SegWit340 for (k, o) in tx.outputs.enumerated() {341 prop.check(!BitcoinSizeEstimator.isDust(o, network: network) && o.value > 0, "dust output \(k) (\(o.value)) on \(network.rawValue)")342 prop.check(network.supportsSegWit || BitcoinScript.witnessProgram(of: o.scriptPubKey) == nil, "witness program paid on \(network.rawValue)")343 }344 if let c = plan.changeIndex { prop.check(tx.outputs[c].scriptPubKey == change && plan.sendMaxIndex == nil, "change script") }345 if isMax {346 sendMax += 1347 let k = plan.sendMaxIndex348 // every coin worth its own input is spent; one left out costs more to spend than it holds349 let left = w.utxos.filter { u in !plan.inputs.contains(u) }350 let uneconomical = left.allSatisfy { u in u.inputWeight.map { u.value <= rate.fee(weight: $0) } ?? true }351 prop.check(k != nil && tx.outputs.count == 1 && tx.outputs[0].scriptPubKey == destination && tx.outputs[0].value == inputTotal - plan.fee && uneconomical,352 "send-max on \(network.rawValue): \(left.count) coins left out")353 } else {354 prop.check(tx.outputs.contains { $0.value == amount && $0.scriptPubKey == destination } && tx.outputs.count <= 2, "recipient output")355 }356 // sequence and lock time357 let sequence: UInt32 = network.supportsRBF ? 0xffff_fffd : 0xffff_fffe358 prop.check(tx.inputs.allSatisfy { $0.sequence == sequence } && tx.signalsRBF == network.supportsRBF, "sequence on \(network.rawValue)")359 if request.currentHeight != nil { prop.check(tx.lockTime <= height && tx.lockTime + 99 >= height, "lock time \(tx.lockTime) for height \(height)") } else { prop.check(tx.lockTime == 0, "lock time without height") }360 prop.check(tx.version == 2 && !tx.hasWitness && tx.inputs.allSatisfy { $0.scriptSig.isEmpty } && plan.network == network, "unsigned form")361362 // signature by the account363 var signed: BitcoinTransaction?364 do { signed = try w.account.sign(plan: plan, previousTransactions: w.previous) } catch { prop.check(false, "sign failed on \(network.rawValue): \(error)") }365 guard let signed else { continue }366 let spent = plan.inputs.map(\.output)367 prop.check(BitcoinVerifier.isValid(transaction: signed, spentOutputs: spent, scheme: scheme), "signature invalid on \(network.rawValue)")368 prop.check(signed.outputs == tx.outputs && signed.lockTime == tx.lockTime && signed.inputs.map(\.sequence) == tx.inputs.map(\.sequence), "signing changed the transaction")369 // never below the target rate: the real size is within the estimate370 prop.check(signed.vsize <= plan.estimatedVSize && plan.fee >= rate.fee(vsize: signed.vsize), "signed size \(signed.vsize) above the estimate \(plan.estimatedVSize)")371 if w.account.purpose == .bip44 {372 let byte: UInt8 = scheme == .bip143ForkID ? 0x41 : 0x01373 prop.check(!signed.hasWitness && signed.serialized(includeWitness: true) == signed.serialized(includeWitness: false) && signed.vsize == signed.serialized().count374 && signed.inputs.allSatisfy { $0.scriptSig.count > 1 && $0.scriptSig[Int($0.scriptSig[0])] == byte }, "P2PKH signature form on \(network.rawValue)")375 // serialized without marker and flag: the fifth byte is the input count376 prop.check(signed.serialized()[4] == UInt8(signed.inputs.count), "marker / flag bytes on \(network.rawValue)")377 } else {378 prop.check(signed.hasWitness && signed.inputs.allSatisfy { $0.scriptSig.isEmpty && $0.witness.count == 2 && $0.witness[0].last == 0x01 } && signed.txid == tx.txid, "P2WPKH signature form")379 }380 // the other schemes refuse it (a legacy input of Litecoin is the same under .legacy and .bip143)381 for other in UTXOSighashScheme.allCases where other != scheme {382 if w.account.purpose == .bip44, Set([other, scheme]) == [.bip143, .legacy] { continue }383 prop.check(!BitcoinVerifier.isValid(transaction: signed, spentOutputs: spent, scheme: other), "valid under \(other.rawValue) too (\(network.rawValue))")384 }385 // amounts: P2PKH outside Bitcoin Cash does not commit to them — which is why the previous transactions are required386 let inflated = spent.map { BitcoinTransaction.Output(value: $0.value + 1, scriptPubKey: $0.scriptPubKey) }387 let commits = scheme == .bip143ForkID || w.account.purpose == .bip84388 prop.check(BitcoinVerifier.isValid(transaction: signed, spentOutputs: inflated, scheme: scheme) == !commits, "amount commitment on \(network.rawValue)")389 prop.check(w.account.requiresPreviousTransactions == !commits, "requiresPreviousTransactions on \(network.rawValue)")390 if !commits {391 var refusedWithout = false, refusedLying = false392 do { _ = try w.account.sign(plan: plan) } catch BitcoinAccountError.unauthenticatedInput { refusedWithout = true } catch {}393 // a previous transaction that is not the one spent (another amount, hence another identifier)394 var lying = w.previous395 let victim = plan.inputs[0].outPoint.txid396 if var p = lying[victim] {397 p.outputs[Int(plan.inputs[0].outPoint.index)].value += 1_000398 lying[victim] = p399 }400 do { _ = try w.account.sign(plan: plan, previousTransactions: lying) } catch BitcoinAccountError.unauthenticatedInput { refusedLying = true } catch {}401 prop.check(refusedWithout && refusedLying, "signed without an authenticated previous transaction on \(network.rawValue)")402 }403 }404 // refusals that are rules of the networks405 for network in UP.networks {406 let w = try UP.wallet(&rng, network: network, coins: 3)407 let change = try w.account.scriptPubKey(chain: .change, index: 0)408 let p2pkh = try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20))409 func error(_ recipients: [BitcoinTransaction.Output], rate: FeeRate, change: Bytes?, max: Bytes? = nil) -> BitcoinBuildError? {410 do { _ = try BitcoinTransactionBuilder.build(BitcoinSpendRequest(network: network, recipients: recipients, utxos: w.utxos, feeRate: rate, changeScript: change, sendMaxScript: max)); return nil } catch {411 return error as? BitcoinBuildError412 }413 }414 let floor = FeeRate.minimum(for: network), cap = FeeRate.maximum(for: network)415 let dust = BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2pkh, network: network)416 prop.check(error([.init(value: dust, scriptPubKey: p2pkh)], rate: FeeRate(milliSatPerVByte: floor.milliSatPerVByte - 1), change: change) == .feeRateOutOfRange, "rate below the floor on \(network.rawValue)")417 prop.check(error([.init(value: dust, scriptPubKey: p2pkh)], rate: FeeRate(milliSatPerVByte: cap.milliSatPerVByte + 1), change: change) == .feeRateOutOfRange, "rate above the ceiling on \(network.rawValue)")418 prop.check(error([.init(value: dust - 1, scriptPubKey: p2pkh)], rate: floor, change: change) == .dustOutput(index: 0), "output below dust on \(network.rawValue)")419 prop.check(error([.init(value: network.maximumMoney + 1, scriptPubKey: p2pkh)], rate: floor, change: change) != nil, "amount above the monetary range on \(network.rawValue)")420 if !network.supportsSegWit {421 let witness = try BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20)), taproot = try BitcoinScript.p2tr(outputKey: rng.bytes(32))422 for script in [witness, taproot] {423 prop.check(error([.init(value: dust * 2, scriptPubKey: script)], rate: floor, change: change) == .witnessScriptNotSupported, "witness recipient on \(network.rawValue)")424 prop.check(error([.init(value: dust * 2, scriptPubKey: p2pkh)], rate: floor, change: script) == .witnessScriptNotSupported, "witness change on \(network.rawValue)")425 prop.check(error([], rate: floor, change: nil, max: script) == .witnessScriptNotSupported, "witness send-max on \(network.rawValue)")426 }427 }428 }429 prop.finish(note: "\(built) transactions built and signed (\(sendMax) send-max, \(changeless) without change), \(refused) requests refused for a documented reason")430 #expect(built > 100 && sendMax > 10 && changeless > 0)431 }432433 /// Fee floors, ceilings and dust thresholds per coin against the reference clients' formulas, the estimate434 /// conversions, and the ceilings of an unaudited build.435 @Test func feeDustAndLimitConstants() throws {436 let seed = AuditSeed.make("utxo.fee-policy")437 var rng = AuditRNG(seed: seed)438 var prop = Prop("dust thresholds follow GetDustThreshold at the coin's rate (Litecoin) or the coin's fixed limit (Dogecoin, Bitcoin Cash); estimates are clamped to [floor, ceiling]; unaudited ceilings per coin",439 algorithm: "fee and dust policy (Litecoin, Dogecoin, Bitcoin Cash)", seed: seed)440 let p2pkh = try BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 1, count: 20)), p2sh = try BitcoinScript.p2sh(scriptHash: Bytes(repeating: 1, count: 20))441 let p2wpkh = try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 1, count: 20)), p2wsh = try BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 1, count: 32))442 let opReturn: Bytes = [0x6a, 0x02, 0x01, 0x02]443 // Litecoin Core: GetDustThreshold = (output size + 148, or + 67 for a witness program) × DUST_RELAY_TX_FEE (30 000 / kvB)444 for n in [BitcoinNetwork.litecoin, .litecoinTestnet] {445 prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2pkh, network: n) == (34 + 148) * 30, "Litecoin P2PKH dust")446 prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2sh, network: n) == (32 + 148) * 30, "Litecoin P2SH dust")447 prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wpkh, network: n) == (31 + 67) * 30, "Litecoin P2WPKH dust")448 prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wsh, network: n) == (43 + 67) * 30, "Litecoin P2WSH dust")449 prop.check(FeeRate.minimum(for: n) == FeeRate(satPerVByte: 1) && FeeRate.maximum(for: n) == FeeRate(satPerVByte: 5_000), "Litecoin fee bounds")450 }451 // Dogecoin Core 1.14.6+: soft dust limit 0.01 DOGE for every output, recommended fee 0.01 DOGE per 1000 bytes452 for n in [BitcoinNetwork.dogecoin, .dogecoinTestnet] {453 for s in [p2pkh, p2sh] { prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: s, network: n) == 1_000_000, "Dogecoin dust") }454 prop.check(FeeRate.minimum(for: n).fee(vsize: 1_000) == 1_000_000 && FeeRate.minimum(for: n).fee(vsize: 226) == 226_000, "Dogecoin recommended fee")455 // ten times the relay floor of the node (0.001 DOGE / kB), and never below it for any size456 prop.check(FeeRate.minimum(for: n).milliSatPerVByte == 10 * 100_000, "Dogecoin floor is ten times the relay minimum")457 prop.check(FeeRate.maximum(for: n).fee(vsize: 1_000) == 100_000_000, "Dogecoin ceiling is 1 DOGE per kB")458 }459 // Bitcoin Cash Node: 1 sat / byte, dust 546 sat (3 × the relay fee of a 182-byte P2PKH output and input)460 for n in [BitcoinNetwork.bitcoinCash, .bitcoinCashTestnet] {461 for s in [p2pkh, p2sh] { prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: s, network: n) == 546, "Bitcoin Cash dust") }462 prop.check(FeeRate.minimum(for: n) == FeeRate(satPerVByte: 1) && FeeRate.maximum(for: n) == FeeRate(satPerVByte: 1_000), "Bitcoin Cash fee bounds")463 }464 for n in UP.networks {465 prop.check(BitcoinSizeEstimator.dustThreshold(scriptPubKey: opReturn, network: n) == 0, "OP_RETURN has no dust threshold")466 prop.check(FeeRate.minimum(for: n) < FeeRate.maximum(for: n), "floor below ceiling")467 // sizes without SegWit are plain byte counts: one P2PKH input and two P2PKH outputs are at most 226 bytes468 if !n.supportsSegWit {469 let w = BitcoinSizeEstimator.transactionWeight(inputWeights: [BitcoinSizeEstimator.inputWeight(scriptPubKey: p2pkh, inWitnessTransaction: false)!], outputScripts: [p2pkh, p2pkh], hasWitness: false)470 // 10 bytes of overhead, a 148-byte input (72-byte signature element at most), two 34-byte outputs471 prop.check(w == 4 * (10 + 148 + 68), "plain size of a P2PKH payment: \(w / 4)")472 }473 }474 // estimates of the node (coins per 1000 bytes) and of Esplora (base units per byte)475 for _ in 0..<AuditMode.cases(quick: 4000, full: 40000) {476 let n = rng.pick(UP.networks)477 let value = rng.pick([0.00001, 0.01, 1.0, 5.0, 999.9999, 1000.0, 1000.0001, 0, -1, .nan, .infinity, -.infinity, Double(rng.next() % 1_000_000) / 1e8, Double(rng.next() % 1_000_000_000) / 1e3,478 Double(bitPattern: rng.next())])479 let perKiloByte = FeeRate.fromEstimate(coinsPerKiloByte: value)480 if value.isFinite, value > 0, value <= 1_000 {481 let exact = value * 100_000_000482 prop.check(perKiloByte != nil && Double(perKiloByte!.milliSatPerVByte) >= exact - 1e-3 && Double(perKiloByte!.milliSatPerVByte) <= exact + 1, "conversion of \(value) coins / kB: \(String(describing: perKiloByte))")483 } else {484 prop.check(perKiloByte == nil, "estimate \(value) converted")485 }486 let perByte = FeeRate.fromEstimate(satPerVByte: value)487 prop.check((perByte != nil) == (value.isFinite && value >= 0 && value <= 1_000_000), "estimate \(value) per byte")488 for r in [perKiloByte, perByte].compactMap({ $0 }) {489 let c = r.clamped(to: n)490 prop.check(c >= .minimum(for: n) && c <= .maximum(for: n) && (r < .minimum(for: n) || r > .maximum(for: n) || c == r), "clamp of \(r) on \(n.rawValue)")491 }492 }493 // ceilings of an unaudited build494 prop.check(MainnetPolicy.utxoLimits(.litecoin) == .init(value: .usd(150), feePerTransaction: 100_000, feeRatePerVByte: 200), "Litecoin ceilings")495 prop.check(MainnetPolicy.utxoLimits(.dogecoin) == .init(value: .usd(150), feePerTransaction: 500_000_000, feeRatePerVByte: 100_000), "Dogecoin ceilings")496 prop.check(MainnetPolicy.utxoLimits(.bitcoinCash) == .init(value: .usd(150), feePerTransaction: 50_000, feeRatePerVByte: 20), "Bitcoin Cash ceilings")497 for n in UP.networks where n.isTest { prop.check(MainnetPolicy.utxoLimits(n) == nil, "ceilings on a test network") }498 for n in UP.networks where !n.isTest {499 let l = MainnetPolicy.utxoLimits(n)!500 // the ceiling rate is a rate the builder accepts, and is not below the floor501 prop.check(FeeRate(satPerVByte: l.feeRatePerVByte) <= .maximum(for: n) && FeeRate(satPerVByte: l.feeRatePerVByte) >= .minimum(for: n), "ceiling rate within the network's bounds on \(n.rawValue)")502 }503 for _ in 0..<AuditMode.cases(quick: 3000, full: 30000) {504 let usd = rng.pick([150.0, 0, 1, -1, .nan, .infinity, Double(rng.next() % 1_000_000) / 100])505 let price = rng.pick([0.0, -1, .nan, .infinity, 1e-300, 1e-9, 0.08, 95.5, 480.0, 1e12, Double(rng.next() % 10_000_000) / 1_000, Double(bitPattern: rng.next())])506 let ceiling = MainnetPolicy.nativeCeiling(usd: usd, priceUSD: price, decimals: 8)507 if usd.isFinite, usd >= 0, price.isFinite, price > 0 {508 let exact = usd / price * 1e8509 // never above the exact value; no ceiling at all (payment refused) when the conversion is not finite510 prop.check(ceiling.map { exact >= 9.2e18 || Double($0) <= exact } ?? !exact.isFinite, "ceiling \(String(describing: ceiling)) for \(usd) USD at \(price)")511 } else {512 prop.check(ceiling == nil, "ceiling computed from usd=\(usd) price=\(price)")513 }514 }515 prop.finish()516 }517518 // MARK: PSBT with previous transactions519520 /// The fee-burn attack through a PSBT. Whatever is done to the amounts a PSBT states — on the wire or through its521 /// public properties — the engine either refuses to sign or the fee it reports is the fee the signed transaction522 /// pays, computed from previous outputs authenticated by their transaction identifier.523 @Test func psbtPreviousTransactionsAuthenticateTheFee() throws {524 let seed = AuditSeed.make("utxo.psbt.previous-transactions")525 var rng = AuditRNG(seed: seed)526 var prop = Prop("PSBT fee = authenticated inputs − outputs, or no fee and no signature: missing, replaced, altered previous transactions and witness-UTXO records",527 algorithm: "BIP-174 with PSBT_IN_NON_WITNESS_UTXO (Dogecoin, Bitcoin Cash, Litecoin legacy)", seed: seed)528 var signedCount = 0529 for _ in 0..<AuditMode.cases(quick: 150, full: 2500) {530 let network = rng.pick([BitcoinNetwork.dogecoin, .dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet, .litecoin])531 let w = try UP.wallet(&rng, network: network, coins: rng.int(1...4), purpose: .bip44)532 let total = w.utxos.reduce(UInt64(0)) { $0 + $1.value }533 var request = BitcoinSpendRequest(network: network, recipients: [.init(value: max(BitcoinSizeEstimator.dustThreshold(scriptPubKey: [0x76], network: network), total / 3), scriptPubKey: try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)))],534 utxos: w.utxos, feeRate: .minimum(for: network), changeScript: try w.account.scriptPubKey(chain: .change, index: 7))535 request.seed = rng.next()536 guard let plan = try? BitcoinTransactionBuilder.build(request) else { continue }537 // without the previous transactions there is no PSBT at all for these inputs538 var missing = false539 do { _ = try w.account.psbt(for: plan) } catch PSBTError.nonWitnessUTXORequired { missing = true } catch {}540 prop.check(missing, "PSBT made without previous transactions on \(network.rawValue)")541 guard let psbt = try? w.account.psbt(for: plan, previousTransactions: w.previous) else {542 prop.check(false, "no PSBT on \(network.rawValue)")543 continue544 }545 let wire = psbt.serialized()546 // what the cold device does: parse, name the network, read the fee, sign547 guard var cold = try? PSBT(parsing: wire) else {548 prop.check(false, "own PSBT does not parse")549 continue550 }551 cold.prepare(for: network)552 prop.check(cold.fee == plan.fee && cold.serialized() == wire, "fee of the parsed PSBT \(String(describing: cold.fee)) ≠ \(plan.fee)")553 var signedPSBT = cold554 let added = try? w.account.sign(psbt: &signedPSBT)555 prop.check(added == plan.inputs.count, "signatures added: \(String(describing: added))")556 if (try? signedPSBT.finalize()) != nil, let tx = try? signedPSBT.extractTransaction() {557 signedCount += 1558 let direct = try? w.account.sign(plan: plan, previousTransactions: w.previous)559 prop.check(tx == direct && BitcoinVerifier.isValid(transaction: tx, spentOutputs: plan.inputs.map(\.output), scheme: network.sighashScheme), "PSBT signature ≠ direct signature")560 let paid = plan.inputs.reduce(UInt64(0)) { $0 + $1.value } - tx.outputs.reduce(UInt64(0)) { $0 + $1.value }561 prop.check(paid == cold.fee, "fee shown \(String(describing: cold.fee)) ≠ fee paid \(paid)")562 } else {563 prop.check(false, "finalize / extract failed on \(network.rawValue)")564 }565566 // attack 1: the previous transaction of one input is replaced by one stating another amount (on the wire)567 let k = rng.int(0...(plan.inputs.count - 1))568 let outPoint = plan.inputs[k].outPoint569 var fake = try #require(w.previous[outPoint.txid])570 fake.outputs[Int(outPoint.index)].value = rng.bool() ? fake.outputs[Int(outPoint.index)].value / 10 : fake.outputs[Int(outPoint.index)].value * 3571 var forged = psbt572 forged.inputs[k].nonWitnessUTXO = fake573 var refusedAtParse = false574 do { _ = try PSBT(parsing: forged.serialized()) } catch PSBTError.nonWitnessUTXOMismatch { refusedAtParse = true } catch {}575 prop.check(refusedAtParse, "a PSBT with a replaced previous transaction parses")576 // the same through the public property, without the wire: no amount is reported, nothing is signed577 forged.prepare(for: network)578 prop.check(forged.spentOutput(inputIndex: k) == nil && forged.fee == nil, "fee \(String(describing: forged.fee)) reported from an unauthenticated previous transaction")579 var attempt = forged580 var refused = false581 do { _ = try w.account.sign(psbt: &attempt) } catch { refused = true }582 prop.check(refused && attempt.inputs.allSatisfy { $0.partialSignatures.isEmpty }, "signed over a replaced previous transaction")583 prop.check((try? forged.setNonWitnessUTXO(fake, inputIndex: k)) == nil, "setNonWitnessUTXO accepted another transaction")584585 // attack 2: the previous transaction is removed and a witness-UTXO record states a lower amount586 var stripped = psbt587 stripped.inputs[k].nonWitnessUTXO = nil588 stripped.inputs[k].witnessUTXO = BitcoinTransaction.Output(value: plan.inputs[k].value / 2, scriptPubKey: plan.inputs[k].scriptPubKey)589 if var reparsed = try? PSBT(parsing: stripped.serialized()) {590 reparsed.prepare(for: network)591 // Dogecoin and Bitcoin Cash: the fee is unknown; Litecoin (BIP-143 scheme, legacy input): the signer refuses592 if network.sighashScheme != .bip143 { prop.check(reparsed.fee == nil, "fee \(String(describing: reparsed.fee)) computed from a witness-UTXO record on \(network.rawValue)") }593 var again = reparsed594 var refusedAgain = false595 do { _ = try w.account.sign(psbt: &again) } catch { refusedAgain = true }596 prop.check(refusedAgain && again.inputs[k].partialSignatures.isEmpty, "signed an input whose amount only a witness-UTXO record states (\(network.rawValue))")597 } else {598 prop.check(false, "stripped PSBT does not parse")599 }600601 // attack 3: an output index beyond the previous transaction, and a truncated previous transaction602 var beyond = psbt603 var short = try #require(w.previous[outPoint.txid])604 short.outputs = Array(short.outputs.prefix(Int(outPoint.index)))605 beyond.inputs[k].nonWitnessUTXO = short606 prop.check((try? PSBT(parsing: beyond.serialized())) == nil && beyond.spentOutput(inputIndex: k) == nil && beyond.fee == nil, "output index beyond the previous transaction")607 }608 // an oversized previous transaction (a hostile indexer or QR): parsed and hashed in linear time, then refused for its identifier609 var big = BitcoinTransaction(version: 1, inputs: [.init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: 9, count: 32), index: 0)!, scriptSig: [0x51])],610 outputs: (0..<20_000).map { BitcoinTransaction.Output(value: UInt64($0), scriptPubKey: Bytes(repeating: 0x51, count: 40)) })611 big.lockTime = 1612 let raw = big.serialized()613 let start = Date()614 let parsed = try? BitcoinTransaction(parsing: raw, allowWitness: false)615 let utxo = BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: 3, count: 32), index: 19_999)!, value: 19_999, scriptPubKey: Bytes(repeating: 0x51, count: 40), confirmations: 1)616 prop.check(parsed == big && parsed.map { !utxo.isAuthenticated(by: $0) } == true, "large previous transaction")617 prop.check(Date().timeIntervalSince(start) < 5, "a \(raw.count)-byte previous transaction took \(Date().timeIntervalSince(start)) s")618 prop.finish(note: "\(signedCount) PSBTs signed, finalized and extracted; a \(raw.count)-byte previous transaction parsed and hashed within the time bound")619 #expect(signedCount > 50)620 }621622 // MARK: Replay protection623624 /// Bitcoin Cash signatures carry SIGHASH_FORKID and sign another digest than Bitcoin's: the same key and the same625 /// outpoint signed for one chain never validate on the other. Dogecoin and Litecoin sign the same digest as626 /// Bitcoin for a P2PKH input: only the outpoint (and the address bytes) tie such a signature to its chain.627 @Test func replayProtectionBetweenTheChains() throws {628 let seed = AuditSeed.make("utxo.replay")629 var rng = AuditRNG(seed: seed)630 var prop = Prop("a Bitcoin Cash signature is invalid under Bitcoin's / Dogecoin's rules and the reverse; the fork-id flag is mandatory there and refused elsewhere; identical transactions give identical legacy signatures on Bitcoin, Litecoin and Dogecoin",631 algorithm: "replay protection (SIGHASH_FORKID)", seed: seed)632 for _ in 0..<AuditMode.cases(quick: 300, full: 4000) {633 let key = randomKey(&rng)634 let script = try BitcoinScript.p2pkh(publicKey: try Secp256k1.publicKey(privateKey: key))635 let value = UInt64(rng.int(1_000...1_000_000_000))636 let unsigned = BitcoinTransaction(version: 2, inputs: [.init(previousOutput: BitcoinOutPoint(hash: rng.bytes(32), index: UInt32(rng.int(0...3)))!, sequence: 0xffff_fffe)],637 outputs: [.init(value: value / 2, scriptPubKey: try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)))])638 let spent = [BitcoinTransaction.Output(value: value, scriptPubKey: script)]639 func sign(_ scheme: UTXOSighashScheme) throws -> BitcoinTransaction {640 var t = unsigned641 try BitcoinSigner.signP2PKH(transaction: &t, inputIndex: 0, privateKey: key, value: value, spentScriptPubKey: script, scheme: scheme)642 return t643 }644 let cash = try sign(.bip143ForkID), doge = try sign(.legacy), bitcoin = try sign(.bip143)645 prop.check(BitcoinVerifier.isValid(transaction: cash, spentOutputs: spent, scheme: .bip143ForkID), "Bitcoin Cash signature invalid on Bitcoin Cash")646 prop.check(!BitcoinVerifier.isValid(transaction: cash, spentOutputs: spent, scheme: .bip143) && !BitcoinVerifier.isValid(transaction: cash, spentOutputs: spent, scheme: .legacy),647 "Bitcoin Cash signature valid on Bitcoin or Dogecoin")648 prop.check(!BitcoinVerifier.isValid(transaction: doge, spentOutputs: spent, scheme: .bip143ForkID) && !BitcoinVerifier.isValid(transaction: bitcoin, spentOutputs: spent, scheme: .bip143ForkID),649 "Bitcoin / Dogecoin signature valid on Bitcoin Cash")650 // the flag is what a Bitcoin node rejects, the digest is what a Bitcoin Cash node rejects: both differ651 let cashByte = cash.inputs[0].scriptSig[Int(cash.inputs[0].scriptSig[0])], plainByte = doge.inputs[0].scriptSig[Int(doge.inputs[0].scriptSig[0])]652 prop.check(cashByte == 0x41 && plainByte == 0x01, "sighash bytes \(cashByte) / \(plainByte)")653 let forkDigest = try BitcoinSighash.forkID(transaction: unsigned, inputIndex: 0, scriptCode: script, value: value)654 let plainDigest = try BitcoinSighash.legacy(transaction: unsigned, inputIndex: 0, scriptCode: script, type: .all)655 prop.check(forkDigest != plainDigest, "the two chains sign the same digest")656 // relabelling the byte does not help: the signature is over another digest657 var relabelled = cash658 relabelled.inputs[0].scriptSig[Int(relabelled.inputs[0].scriptSig[0])] = 0x01659 prop.check(!BitcoinVerifier.isValid(transaction: relabelled, spentOutputs: spent, scheme: .bip143) && !BitcoinVerifier.isValid(transaction: relabelled, spentOutputs: spent, scheme: .legacy),660 "relabelled Bitcoin Cash signature valid on Bitcoin")661 var flagged = doge662 flagged.inputs[0].scriptSig[Int(flagged.inputs[0].scriptSig[0])] = 0x41663 prop.check(!BitcoinVerifier.isValid(transaction: flagged, spentOutputs: spent, scheme: .bip143ForkID), "relabelled Dogecoin signature valid on Bitcoin Cash")664 // the residual fact: the original digest is the same on Bitcoin, Litecoin and Dogecoin665 prop.check(doge == bitcoin, "legacy signatures differ between schemes .legacy and .bip143")666 }667 // derivation paths: one coin type per coin on main networks, so no key is shared between the coins there668 let types = Dictionary(grouping: BitcoinNetwork.allCases.filter { !$0.isTest }, by: \.coinType)669 prop.check(types.count == 4 && types.values.allSatisfy { $0.count == 1 }, "coin types of the main networks are not distinct: \(types)")670 let master = try ExtendedKey.master(seed: rng.bytes(32))671 var keys = Set<Bytes>()672 for n in BitcoinNetwork.allCases where !n.isTest {673 for purpose in UTXOAccountPurpose.allCases where n.supports(purpose) { keys.insert(try UTXOAccount(master: master, network: n, purpose: purpose).publicKey(chain: .receive, index: 0)) }674 }675 prop.check(keys.count == 6, "a main-network key is shared between two coins or purposes (\(keys.count) distinct of 6)")676 // test networks all use coin type 1: Dogecoin Testnet and Bitcoin Cash Testnet (BIP-44) share their keys, as do677 // Bitcoin Testnet / Signet and Litecoin Testnet (BIP-84) — stated in the review register as a residual fact678 let dogeTest = try UTXOAccount(master: master, network: .dogecoinTestnet).publicKey(chain: .receive, index: 0)679 let cashTest = try UTXOAccount(master: master, network: .bitcoinCashTestnet).publicKey(chain: .receive, index: 0)680 let liteTest = try UTXOAccount(master: master, network: .litecoinTestnet).publicKey(chain: .receive, index: 0)681 let bitcoinTest = try UTXOAccount(master: master, network: .testnet).publicKey(chain: .receive, index: 0)682 prop.check(dogeTest == cashTest && liteTest == bitcoinTest && dogeTest != liteTest, "test-network key sharing is not what the register states")683 prop.finish()684 }685}686