SPB Git

Repository Public

UTXOCoinsDiffTests.swift 48.1 KB 692 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/UTXOCoinsDiffTests.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// Litecoin, Dogecoin and Bitcoin Cash against independent implementations (security/tests/oracles/mc/utxo.py):52//   CashAddr           bitcash's polynomial and bit conversion (and its own parser, where it applies);53//   addresses          bip-utils' coin parameters, Base58Check of the base58 package, bip-utils' Bech32;54//   derivations        bip-utils (BIP-44 / BIP-84);55//   signature hashes   embit (original algorithm, BIP-143), the fork-id algorithm written from the UAHF text;56//   signatures         libsecp256k1 through coincurve (RFC 6979, low-s);57//   transactions       embit digest + libsecp256k1 signature assembled by the oracle, and bitcash's own P2PKH builder.5859private enum U {60    static let script = "utxo"61    static let networks: [BitcoinNetwork] = [.litecoin, .litecoinTestnet, .dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet]62    static let charset = Array("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)63    static let hashSizes = [20, 24, 28, 32, 40, 48, 56, 64]6465    static func available(_ name: String, needs: [String]) -> Bool { MCOracle.available(script, campaign: name, needs: needs) }66    static func batch(_ op: String, _ cases: [Case]) throws -> [Case] { try MCOracle.batch(script, op, cases) }67    static func label(_ package: String, _ what: String = "") -> String { MCOracle.label(script, package, what) }6869    static func key(_ rng: inout AuditRNG) -> Bytes {70        while true {71            let k = rng.bytes(32)72            if Secp256k1.isValidPrivateKey(k) { return k }73        }74    }7576    static func prefix(_ rng: inout AuditRNG) -> String {77        switch rng.int(0...9) {78        case 0...3: return "bitcoincash"79        case 4...5: return "bchtest"80        case 6: return rng.pick(["bchreg", "simpleledger", "ecash", "etoken", "pref", "prefix", "p"])81        default: return String(decoding: (0..<rng.int(1...12)).map { _ in UInt8(rng.int(97...122)) }, as: UTF8.self)82        }83    }8485    /// A random transaction with empty or short scriptSigs, as a signature hash sees it.86    static func transaction(_ rng: inout AuditRNG, inputs: Int, outputs: Int, legacyOnly: Bool = false) -> BitcoinTransaction {87        let ins = (0..<inputs).map { _ in88            BitcoinTransaction.Input(previousOutput: BitcoinOutPoint(hash: rng.bytes(32), index: UInt32(rng.pick([0, 1, 2, 7, 255, 65_536])))!,89                                     scriptSig: rng.int(0...2) == 0 ? rng.bytes(rng.int(1...40)) : [],90                                     sequence: rng.pick([0xffff_ffff, 0xffff_fffe, 0xffff_fffd, 0, 1, UInt32(truncatingIfNeeded: rng.next())]))91        }92        let outs = (0..<outputs).map { _ in93            BitcoinTransaction.Output(value: rng.pick([0, 1, 546, 100_000_000, 2_100_000_000_000_000, rng.next() >> UInt64(rng.int(1...40))]),94                                      scriptPubKey: outputScript(&rng))95        }96        return BitcoinTransaction(version: rng.pick([1, 2, 2, Int32(truncatingIfNeeded: rng.next())]), inputs: ins, outputs: outs,97                                  lockTime: rng.pick([0, 0, 1, 499_999_999, 500_000_000, UInt32(truncatingIfNeeded: rng.next())]))98    }99100    static func outputScript(_ rng: inout AuditRNG) -> Bytes {101        switch rng.int(0...5) {102        case 0, 1: return try! BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20))103        case 2: return try! BitcoinScript.p2sh(scriptHash: rng.bytes(20))104        case 3: return try! BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20))105        case 4: return [0x6a, 0x04] + rng.bytes(4)106        default: return rng.int(0...1) == 0 ? [] : [0x51]107        }108    }109}110111@Suite struct UTXOCoinsDifferential {112    // MARK: CashAddr113114    @Test func cashAddrEncoding() throws {115        let name = "utxo-cashaddr-encode"116        guard U.available(name, needs: ["bitcash"]) else { return }117        let seed = DiffSeed.make(name)118        var rng = AuditRNG(seed: seed)119        var tally = DiffTally(name, algorithm: "CashAddr", parameterSet: "encode: any prefix, types 0…15, the eight hash sizes",120                              oracle: U.label("bitcash", "polymod, convertbits, checksum; Address class for its named versions"), seed: seed)121        var inputs = [(prefix: String, type: UInt8, hash: Bytes)]()122        for _ in 0..<AuditMode.cases(quick: 1500, full: 20000) {123            inputs.append((U.prefix(&rng), UInt8(rng.pick([0, 0, 0, 1, 1, 2, 3, rng.int(0...15)])), rng.bytes(rng.pick([20, 20, 20, rng.pick(U.hashSizes)]))))124        }125        let answers = try U.batch("cashaddr_encode", inputs.map { ["prefix": $0.prefix, "type": Int($0.type), "hash": hex($0.hash)] })126        var named = 0127        for (i, a) in zip(inputs, answers) {128            let ours = CashAddr.encode(prefix: i.prefix, type: i.type, hash: i.hash)129            var ok = ours != nil && ours == a.string("address")130            if let n = a.string("named") {131                named += 1132                ok = ok && ours == n133            }134            // and back135            ok = ok && ours.flatMap { CashAddr.decode($0) } == CashAddr.Decoded(prefix: i.prefix, type: i.type, hash: i.hash)136            tally.check(ok, "prefix=\(i.prefix) type=\(i.type) hash=\(hex(i.hash)) ours=\(ours ?? "nil") reference=\(a)")137        }138        // sizes and types outside the format are not encoded139        for bad in [0, 1, 19, 21, 33, 63, 65, 128] { tally.check(CashAddr.encode(prefix: "bitcoincash", type: 0, hash: Bytes(repeating: 1, count: bad)) == nil, "size \(bad) encoded") }140        tally.check(CashAddr.encode(prefix: "bitcoincash", type: 16, hash: Bytes(repeating: 1, count: 20)) == nil, "type 16 encoded")141        for bad in ["", "BitcoinCash", "bch1", "bit coin", "é"] { tally.check(CashAddr.encode(prefix: bad, type: 0, hash: Bytes(repeating: 1, count: 20)) == nil, "prefix \(bad) encoded") }142        print("UTXO-DIFF \(name): \(named) of \(inputs.count) cases also matched bitcash's Address class")143        #expect(named > 0)144        #expect(tally.finish() == 0)145    }146147    /// Acceptance of valid, altered and crafted strings: the engine's verdict and decoded fields against the rules of148    /// the specification applied with bitcash's primitives. bitcash's own parser is more lenient (it keeps non-zero149    /// padding bits and does not check the hash length) and knows three prefixes and six versions only: where it150    /// accepts what the engine refuses, the strict reference must give one of those reasons.151    @Test func cashAddrDecodingAcceptance() throws {152        let name = "utxo-cashaddr-decode"153        guard U.available(name, needs: ["bitcash"]) else { return }154        let seed = DiffSeed.make(name)155        var rng = AuditRNG(seed: seed)156        var tally = DiffTally(name, algorithm: "CashAddr", parameterSet: "decode: valid, altered (substitutions, case, prefix, length) and crafted strings with a valid checksum",157                              oracle: "CashAddr decoding rules of the specification over " + U.label("bitcash", "polymod, convertbits") + "; bitcash Address.from_string where it applies", seed: seed)158        var texts = [(text: String, defaultPrefix: String?)]()159        var craft = [Case]()160        let n = AuditMode.cases(quick: 2500, full: 30000)161        for _ in 0..<n {162            let prefix = U.prefix(&rng)163            let hash = rng.bytes(rng.pick([20, 20, 20, 20, rng.pick(U.hashSizes)]))164            let type = UInt8(rng.pick([0, 0, 1, 1, 2, 3, rng.int(0...15)]))165            let valid = CashAddr.encode(prefix: prefix, type: type, hash: hash)!166            var bytes = Array(valid.utf8)167            let body = prefix.utf8.count + 1168            func position() -> Int { rng.int(body...(bytes.count - 1)) }169            switch rng.int(0...15) {170            case 0, 1: break171            case 2: bytes[position()] = rng.pick(U.charset)172            case 3:173                bytes[position()] = rng.pick(U.charset)174                bytes[position()] = rng.pick(U.charset)175            case 4: bytes[position()] = rng.pick(Array("bio1BIO!_ -".utf8))176            case 5: bytes = Array(valid.uppercased().utf8)177            case 6:178                let p = rng.int(0...(bytes.count - 1))179                if bytes[p] >= 97, bytes[p] <= 122 { bytes[p] -= 32 }180            case 7: bytes.remove(at: position())181            case 8: bytes.insert(rng.pick(U.charset), at: position())182            case 9: bytes = Array(bytes[body...])183            case 10: bytes = Array(U.prefix(&rng).utf8) + bytes[(body - 1)...]184            case 11: bytes = Array("x:".utf8) + bytes185            case 12: bytes = Array(bytes.prefix(rng.int(0...bytes.count)))186            case 13: bytes[rng.int(0...(body - 2))] = rng.pick(Array("abcxyz0A:".utf8))187            default:188                // crafted by the oracle: a valid checksum over words that are not an address189                var words = Bech32.toWords([(type << 3) | UInt8(U.hashSizes.firstIndex(of: hash.count)!)] + hash)190                switch rng.int(0...4) {191                case 0: words[words.count - 1] |= UInt8(rng.int(1...3))           // padding bits (two for a 20-byte hash)192                case 1: words.append(UInt8(rng.int(0...31)))                        // one word too many193                case 2: words.removeLast()                                          // one too few194                case 3: words[0] |= 0x10                                            // reserved bit of the version byte195                default: words = (0..<rng.int(1...110)).map { _ in UInt8(rng.int(0...31)) }196                }197                craft.append(["prefix": prefix, "words": words.map { Int($0) }])198                continue199            }200            let text = String(decoding: bytes, as: UTF8.self)201            let hasColon = text.contains(":")202            texts.append((text, hasColon ? nil : rng.pick([prefix, "bitcoincash", nil])))203        }204        for a in try U.batch("cashaddr_raw", craft) { texts.append((try #require(a.string("address")), nil)) }205        let answers = try U.batch("cashaddr_decode", texts.map { t in206            var c: Case = ["text": t.text]207            if let d = t.defaultPrefix { c["default_prefix"] = d }208            return c209        })210        var lenient = [String: Int](), bitcashAgreed = 0211        for (t, a) in zip(texts, answers) {212            let ours = CashAddr.decode(t.text, defaultPrefix: t.defaultPrefix)213            tally.verdict(ours != nil)214            let valid = a.bool("valid") ?? false215            var ok = (ours != nil) == valid216            if let ours, valid { ok = ok && ours.prefix == a.string("prefix") && Int(ours.type) == a["type"] as? Int && ours.hash == a.bytes("hash") }217            if let b = a["bitcash"] as? [String: Any] {218                if let ours {219                    // both accept: the same hash and the same prefix220                    bitcashAgreed += 1221                    ok = ok && hex(ours.hash) == b["hash"] as? String && ours.prefix == b["prefix"] as? String222                } else {223                    // only bitcash accepts: the strict rules name why (padding, length)224                    let reason = a.string("reason") ?? "?"225                    lenient[reason, default: 0] += 1226                    ok = ok && ["padding", "length"].contains(reason)227                }228            } else if let ours, ["bitcoincash", "bchtest", "bchreg"].contains(ours.prefix), [20, 32].contains(ours.hash.count),229                      (ours.hash.count == 20 && [0, 1, 2, 3].contains(ours.type)) || (ours.hash.count == 32 && [1, 3].contains(ours.type)) {230                // a version and a prefix bitcash knows, in a single case: it must accept too231                ok = false232            }233            tally.check(ok, "text=\(t.text) default=\(t.defaultPrefix ?? "-") ours=\(String(describing: ours)) reference=\(a)")234        }235        print("UTXO-DIFF \(name): \(texts.count) strings; bitcash's parser agreed on \(bitcashAgreed) accepted addresses; accepted by bitcash only (policy difference, strict reason): \(lenient)")236        #expect(tally.accepted > 100 && tally.judged - tally.accepted > 100)237        #expect(tally.finish() == 0)238    }239240    // MARK: Addresses241242    /// Version bytes, prefixes and address strings of the six networks, and which networks accept which address.243    @Test func addressFormatsAndCrossNetworkAcceptance() throws {244        let name = "utxo-address-formats"245        guard U.available(name, needs: ["bip-utils", "base58", "bitcash"]) else { return }246        let seed = DiffSeed.make(name)247        var rng = AuditRNG(seed: seed)248        var tally = DiffTally(name, algorithm: "addresses of Litecoin, Dogecoin, Bitcoin Cash", parameterSet: "version bytes, Base58Check, Bech32 / Bech32m (ltc, tltc), CashAddr and legacy forms, cross-network acceptance",249                              oracle: U.label("bip-utils", "coin parameters, Bech32") + ", " + U.label("base58") + ", " + U.label("bitcash", "CashAddr checksum"), seed: seed)250        // 1. parameters251        let parameters = try U.batch("parameters", U.networks.map { ["network": $0.rawValue] })252        var versions = [BitcoinNetwork: (p2pkh: Int, p2sh: Int, former: Int?)]()253        for (n, p) in zip(U.networks, parameters) {254            let pkh = p["p2pkh"] as? Int ?? -1, sh = p["p2sh"] as? Int ?? -1255            versions[n] = (pkh, sh, p["p2sh_deprecated"] as? Int)256            tally.check(Int(n.p2pkhVersion) == pkh && Int(n.p2shVersion) == sh && Int(n.wifVersion) == p["wif"] as? Int, "\(n.rawValue) versions reference=\(p)")257            tally.check(n.bech32HRP == p["hrp"] as? String, "\(n.rawValue) hrp reference=\(p)")258            tally.check(n.cashAddrPrefix == p["cashaddr_prefix"] as? String, "\(n.rawValue) CashAddr prefix reference=\(p)")259            tally.check(n.deprecatedP2SHVersion.map { Int($0) } == p["p2sh_deprecated"] as? Int, "\(n.rawValue) former P2SH version reference=\(p)")260        }261        // Bitcoin's own, from Bitcoin Core's chainparams (0 / 5 / bc, 111 / 196 / tb)262        versions[.mainnet] = (0, 5, nil)263        versions[.testnet] = (111, 196, nil)264        versions[.signet] = (111, 196, nil)265266        // 2. addresses267        struct Item { let network: BitcoinNetwork; let kind: String; let hash: Bytes; let version: Int; let form: String }268        var items = [Item]()269        for _ in 0..<AuditMode.cases(quick: 1200, full: 12000) {270            let n = rng.pick(U.networks)271            var kinds = ["p2pkh", "p2pkh", "p2sh"]272            if n.supportsSegWit { kinds += ["witness", "witness", "p2sh_deprecated"] }273            let kind = rng.pick(kinds)274            if kind == "witness" {275                let version = rng.pick([0, 0, 1])276                items.append(Item(network: n, kind: kind, hash: rng.bytes(version == 1 ? 32 : rng.pick([20, 32])), version: version, form: ""))277            } else {278                items.append(Item(network: n, kind: kind, hash: rng.bytes(20), version: 0, form: n.cashAddrPrefix != nil && rng.bool() ? "cashaddr" : ""))279            }280        }281        let answers = try U.batch("address", items.map { ["network": $0.network.rawValue, "kind": $0.kind, "hash": hex($0.hash), "version": $0.version, "form": $0.form] })282        for (i, a) in zip(items, answers) {283            guard let text = a.string("address") else {284                tally.check(false, "reference failed: \(a)")285                continue286            }287            let script: Bytes288            switch i.kind {289            case "p2pkh": script = try BitcoinScript.p2pkh(publicKeyHash: i.hash)290            case "p2sh", "p2sh_deprecated": script = try BitcoinScript.p2sh(scriptHash: i.hash)291            default: script = try BitcoinScript.witnessProgram(version: UInt8(i.version), program: i.hash)292            }293            var ok = true294            let parsed: Result<BitcoinAddress, BitcoinAddress.Error> = Result { try BitcoinAddress(text, network: i.network) }.mapError { $0 as? BitcoinAddress.Error ?? .invalidFormat }295            if i.kind == "p2sh_deprecated" {296                // Litecoin's former P2SH form is also a Bitcoin address: refused, with its own reason297                if case .failure(let e) = parsed { ok = e == .ambiguousLegacyFormat } else { ok = false }298            } else {299                let ours = try? BitcoinAddress(scriptPubKey: script, network: i.network)300                if case .success(let p) = parsed {301                    ok = p.scriptPubKey == script302                    if i.network.cashAddrPrefix != nil {303                        // displayed in CashAddr; the Base58 form is accepted, converted and flagged304                        ok = ok && p.isLegacyFormat == (i.form != "cashaddr") && p.string == ours?.string && (i.form == "cashaddr" ? p.string == text : p.base58String == text)305                    } else {306                        ok = ok && !p.isLegacyFormat && p.string == text && ours?.string == text307                    }308                } else {309                    ok = false310                }311            }312            tally.check(ok, "\(i.network.rawValue) \(i.kind) hash=\(hex(i.hash)) reference=\(text) ours=\(parsed)")313            // 3. every other network: accepted exactly where the reference tables say the encoding is that network's too314            for other in BitcoinNetwork.allCases where other != i.network {315                let accepted = (try? BitcoinAddress(text, network: other)) != nil316                tally.verdict(accepted)317                var expected = false318                if i.kind == "witness" {319                    expected = other.bech32HRP != nil && other.bech32HRP == i.network.bech32HRP320                } else if i.form == "cashaddr" {321                    expected = other.cashAddrPrefix == i.network.cashAddrPrefix322                } else if let v = versions[i.network], let o = versions[other] {323                    let byte = i.kind == "p2pkh" ? v.p2pkh : (i.kind == "p2sh" ? v.p2sh : v.former ?? -1)324                    // the former Litecoin P2SH byte is refused on Litecoin itself, and is Bitcoin's (or a test network's) own325                    expected = byte == o.p2pkh || byte == o.p2sh326                }327                tally.check(accepted == expected, "\(text) (\(i.network.rawValue) \(i.kind)) on \(other.rawValue): accepted=\(accepted) expected=\(expected)")328            }329        }330        #expect(tally.finish() == 0)331    }332333    // MARK: Derivations334335    @Test func accountDerivations() throws {336        let name = "utxo-derivation"337        guard U.available(name, needs: ["bip-utils"]) else { return }338        let seed = DiffSeed.make(name)339        var rng = AuditRNG(seed: seed)340        var tally = DiffTally(name, algorithm: "BIP-32 / BIP-44 / BIP-84 accounts of Litecoin, Dogecoin, Bitcoin Cash", parameterSet: "account path and coin type, account key, address, public key, private key, WIF; receive and change chains",341                              oracle: U.label("bip-utils", "Bip44, Bip84, WifEncoder"), seed: seed)342        struct Item { let seed: Bytes; let network: BitcoinNetwork; let purpose: UTXOAccountPurpose; let chain: UTXOAccount.Chain; let index: UInt32 }343        var items = [Item]()344        for _ in 0..<AuditMode.cases(quick: 400, full: 4000) {345            let n = rng.pick(U.networks)346            // every purpose the network supports; the default one twice as often347            let purpose: UTXOAccountPurpose = n.supportsSegWit ? rng.pick([.bip84, .bip84, .bip44]) : .bip44348            items.append(Item(seed: rng.bytes(rng.pick([16, 32, 64])), network: n, purpose: purpose, chain: rng.bool() ? .receive : .change,349                              index: UInt32(rng.pick([0, 1, 2, 19, 20, rng.int(0...100_000)]))))350        }351        let answers = try U.batch("derive", items.map {352            ["seed": hex($0.seed), "network": $0.network.rawValue, "purpose": Int($0.purpose.rawValue), "change": Int($0.chain.rawValue), "index": Int($0.index)]353        })354        for (i, a) in zip(items, answers) {355            var ok = a.oracleError == nil356            do {357                let master = try ExtendedKey.master(seed: i.seed)358                let account = try UTXOAccount(master: master, network: i.network, purpose: i.purpose)359                ok = ok && account.accountPath.description == a.string("account_path") && Int(i.network.coinType) == a["coin_type"] as? Int360                let accountKey = try ExtendedKey.parse(account.extendedPublicKey(slip132: false)).key361                ok = ok && accountKey.publicKey == a.bytes("account_public_key") && accountKey.chainCode == a.bytes("account_chain_code") && accountKey.depth == 3362                let address = try account.address(chain: i.chain, index: i.index).string363                let publicKey = try account.publicKey(chain: i.chain, index: i.index)364                let key = try account.privateKey(chain: i.chain, index: i.index)365                let wif = try BitcoinWIF.encode(privateKey: key, network: i.network)366                ok = ok && address == a.string("address") && publicKey == a.bytes("public_key") && key == a.bytes("private_key") && wif == a.string("wif")367                // the watch-only account built from the serialized public key gives the same address368                let watch = try UTXOAccount(extendedKey: account.extendedPublicKey(slip132: false), network: i.network, purpose: i.purpose)369                let watched = try watch.address(chain: i.chain, index: i.index).string370                ok = ok && watched == a.string("address") && watch.isWatchOnly371                // the default purpose is BIP-84 where SegWit exists, BIP-44 elsewhere372                let byDefault = try UTXOAccount(master: master, network: i.network).purpose373                ok = ok && byDefault == (i.network.supportsSegWit ? .bip84 : .bip44)374            } catch {375                ok = false376            }377            tally.check(ok, "seed=\(hex(i.seed)) network=\(i.network.rawValue) purpose=\(i.purpose.rawValue) chain=\(i.chain.rawValue) index=\(i.index) reference=\(a)")378        }379        // BIP-84 does not exist where SegWit does not380        for n in [BitcoinNetwork.dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet] {381            let refused = (try? UTXOAccount(master: try ExtendedKey.master(seed: Bytes(repeating: 7, count: 32)), network: n, purpose: .bip84)) == nil382            tally.check(refused, "BIP-84 account accepted on \(n.rawValue)")383        }384        #expect(tally.finish() == 0)385    }386387    // MARK: Signature hashes388389    @Test func originalSignatureHash() throws {390        let name = "utxo-legacy-sighash"391        guard U.available(name, needs: ["embit"]) else { return }392        let seed = DiffSeed.make(name)393        var rng = AuditRNG(seed: seed)394        // embit 0.8.0 serializes the blank outputs of SIGHASH_SINGLE with value 0xffffffff instead of -1 (CTxOut::SetNull):395        // its digest is wrong for SIGHASH_SINGLE on any input but the first. The second reference is the algorithm396        // written in the oracle from Bitcoin Core's SignatureHash, which reproduces every Bitcoin Cash Node vector whose397        // script has no OP_CODESEPARATOR (621 of 1000, SIGHASH_SINGLE on later inputs included). The engine must equal398        // that one on every case, and embit on every case outside its defect.399        var tally = DiffTally(name, algorithm: "original signature hash (Dogecoin, legacy inputs of Litecoin)", parameterSet: "random transactions, the six standard hash types",400                              oracle: U.label("embit", "Transaction.sighash_legacy, except SIGHASH_SINGLE beyond the first input") + " and Bitcoin Core's SignatureHash rewritten in the oracle (hashlib)", seed: seed)401        struct Item { let tx: BitcoinTransaction; let index: Int; let script: Bytes; let type: UInt32 }402        var items = [Item]()403        var outOfRange = 0404        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {405            let tx = U.transaction(&rng, inputs: rng.int(1...4), outputs: rng.int(1...4))406            let index = rng.int(0...(tx.inputs.count - 1))407            let script: Bytes = rng.pick([try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)), try BitcoinScript.p2sh(scriptHash: rng.bytes(20)), [0x51], []])408            let type = rng.pick([UInt32(0x01), 0x01, 0x02, 0x03, 0x81, 0x82, 0x83])409            if type & 0x1f == 3, index >= tx.outputs.count {410                // SIGHASH_SINGLE without a matching output: Bitcoin signs the constant "one" (the historical bug)411                outOfRange += 1412                let ours = try? BitcoinSighash.legacy(transaction: tx, inputIndex: index, scriptCode: script, type: BitcoinSighashType(rawValue: type))413                tally.check(ours == [1] + Bytes(repeating: 0, count: 31), "SIGHASH_SINGLE out of range: \(ours.map(hex) ?? "nil")")414                continue415            }416            items.append(Item(tx: tx, index: index, script: script, type: type))417        }418        // the second reference is itself checked against the node's vectors (rows whose script has no OP_CODESEPARATOR)419        let vectorFile = AuditPaths.vectors.appendingPathComponent("bchn/sighash.json.gz")420        let rows = (try JSONSerialization.jsonObject(with: try AuditVectors.gunzip(try Data(contentsOf: vectorFile))) as? [[Any]] ?? []).dropFirst()421            .filter { $0.count == 6 && !(Hex.decode($0[1] as? String ?? "ab") ?? [0xab]).contains(0xab) }422        let validation = try U.batch("legacy_sighash_both", rows.map { r in423            ["tx": r[0] as? String ?? "", "index": r[2] as? Int ?? 0, "script": r[1] as? String ?? "", "type": Int(UInt32(truncatingIfNeeded: r[3] as? Int ?? 0))] as Case424        })425        var singleBeyondFirst = 0426        for (r, a) in zip(rows, validation) {427            let expected = (r[5] as? String).flatMap { Hex.decode($0) }.map { Bytes($0.reversed()) }428            tally.check(a.bytes("core") != nil && a.bytes("core") == expected, "the Core-faithful reference disagrees with a Bitcoin Cash Node vector: \(r[0])")429            if (r[3] as? Int ?? 0) & 0x1f == 3, (r[2] as? Int ?? 0) > 0 { singleBeyondFirst += 1 }430        }431        #expect(rows.count > 500 && singleBeyondFirst > 0)432        let answers = try U.batch("legacy_sighash_both", items.map { i in ["tx": i.tx.hex, "index": i.index, "script": hex(i.script), "type": Int(i.type)] as Case })433        var embitCompared = 0, embitDefect = 0434        for (i, a) in zip(items, answers) {435            let type = BitcoinSighashType(rawValue: i.type)436            let ours = try? BitcoinSighash.legacy(transaction: i.tx, inputIndex: i.index, scriptCode: i.script, type: type)437            var ok = ours != nil && ours == a.bytes("core")438            if i.type & 0x1f == 3, i.index > 0 {439                // the documented defect of the reference: counted, and expected to differ440                if a.bytes("embit") != ours { embitDefect += 1 }441            } else {442                embitCompared += 1443                ok = ok && ours == a.bytes("embit")444            }445            // the scheme entry points give the same digest, whatever amount they are handed446            ok = ok && (try? BitcoinSighash.digest(scheme: .legacy, isWitness: false, transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: rng.next(), type: type)) == ours447            ok = ok && (try? BitcoinSighash.digest(scheme: .bip143, isWitness: false, transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: rng.next(), type: type)) == ours448            // and the fork-id flag is refused there449            ok = ok && (try? BitcoinSighash.digest(scheme: .legacy, isWitness: false, transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: 0, type: type.withForkID)) == nil450            tally.check(ok, "tx=\(i.tx.hex) index=\(i.index) script=\(hex(i.script)) type=\(i.type) ours=\(ours.map(hex) ?? "nil") reference=\(a)")451        }452        print("UTXO-DIFF \(name): Core-faithful reference validated on \(rows.count) Bitcoin Cash Node vectors (\(singleBeyondFirst) of them SIGHASH_SINGLE beyond the first input)")453        print("UTXO-DIFF \(name): \(items.count) digests equal to the Core-faithful reference; \(embitCompared) of them also compared with embit; \(embitDefect) SIGHASH_SINGLE cases beyond the first input where embit differs (its defect); \(outOfRange) SIGHASH_SINGLE-out-of-range cases checked against the constant")454        #expect(embitCompared > 500)455        #expect(tally.finish() == 0)456    }457458    @Test func forkIDSignatureHash() throws {459        let name = "utxo-forkid-sighash"460        guard U.available(name, needs: ["embit"]) else { return }461        let seed = DiffSeed.make(name)462        var rng = AuditRNG(seed: seed)463        var tally = DiffTally(name, algorithm: "Bitcoin Cash signature hash (SIGHASH_FORKID)", parameterSet: "random transactions and amounts, the six standard hash types with the fork-id flag",464                              oracle: "UAHF replay-protected sighash written in the oracle from the specification (hashlib), transaction parsed by " + U.label("embit"), seed: seed)465        struct Item { let tx: BitcoinTransaction; let index: Int; let script: Bytes; let value: UInt64; let type: UInt32 }466        var items = [Item]()467        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {468            let tx = U.transaction(&rng, inputs: rng.int(1...4), outputs: rng.int(1...4))469            items.append(Item(tx: tx, index: rng.int(0...(tx.inputs.count - 1)),470                              script: rng.pick([try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)), try BitcoinScript.p2sh(scriptHash: rng.bytes(20)), [0x51], rng.bytes(rng.int(0...300))]),471                              value: rng.pick([0, 1, 546, 100_000_000, 2_100_000_000_000_000, rng.next()]), type: rng.pick([UInt32(0x41), 0x41, 0x42, 0x43, 0xc1, 0xc2, 0xc3])))472        }473        let answers = try U.batch("forkid_sighash", items.map { i in ["tx": i.tx.hex, "index": i.index, "script": hex(i.script), "value": i.value, "type": Int(i.type)] as Case })474        for (i, a) in zip(items, answers) {475            let type = BitcoinSighashType(rawValue: i.type)476            let ours = try? BitcoinSighash.forkID(transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: i.value, type: type)477            var ok = ours != nil && ours == a.bytes("digest")478            ok = ok && (try? BitcoinSighash.digest(scheme: .bip143ForkID, isWitness: false, transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: i.value, type: type)) == ours479            // the digest commits to the amount, and it is not the digest Bitcoin (or Dogecoin) would sign480            ok = ok && (try? BitcoinSighash.forkID(transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: i.value &+ 1, type: type)) != ours481            let plain = type.withoutForkID482            ok = ok && (try? BitcoinSighash.legacy(transaction: i.tx, inputIndex: i.index, scriptCode: i.script, type: plain)) != ours483            ok = ok && (try? BitcoinSighash.segwitV0(transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: i.value, type: plain)) != ours484            // without the flag the Bitcoin Cash scheme computes nothing485            ok = ok && (try? BitcoinSighash.digest(scheme: .bip143ForkID, isWitness: false, transaction: i.tx, inputIndex: i.index, scriptCode: i.script, value: i.value, type: plain)) == nil486            tally.check(ok, "tx=\(i.tx.hex) index=\(i.index) script=\(hex(i.script)) value=\(i.value) type=\(i.type) ours=\(ours.map(hex) ?? "nil") reference=\(a)")487        }488        #expect(tally.finish() == 0)489    }490491    // MARK: Signatures and signed transactions492493    /// P2PKH transactions signed by the engine for Dogecoin, Litecoin (legacy inputs) and Bitcoin Cash, rebuilt by the494    /// oracle: embit's digest (or the fork-id digest) and libsecp256k1's RFC 6979 signature. Byte-identical or failed.495    @Test func signedP2PKHTransactions() throws {496        let name = "utxo-signed-p2pkh-transaction"497        guard U.available(name, needs: ["embit", "coincurve"]) else { return }498        let seed = DiffSeed.make(name)499        var rng = AuditRNG(seed: seed)500        var tally = DiffTally(name, algorithm: "signed P2PKH transaction (Dogecoin, Litecoin legacy, Bitcoin Cash)", parameterSet: "raw transaction, txid, scriptSig; compressed and uncompressed keys",501                              oracle: U.label("embit", "sighash_legacy, serialization") + ", " + U.label("coincurve", "libsecp256k1 RFC 6979") + ", fork-id digest of the oracle", seed: seed)502        struct Item { let scheme: UTXOSighashScheme; let unsigned: BitcoinTransaction; let key: Bytes; let compressed: Bool; let script: Bytes; let values: [UInt64]; let signed: BitcoinTransaction? }503        var items = [Item]()504        for _ in 0..<AuditMode.cases(quick: 600, full: 6000) {505            let scheme = rng.pick([UTXOSighashScheme.legacy, .legacy, .bip143, .bip143ForkID, .bip143ForkID])506            let key = U.key(&rng)507            let compressed = rng.int(0...4) != 0508            let script = try BitcoinScript.p2pkh(publicKey: try Secp256k1.publicKey(privateKey: key, compressed: compressed))509            var tx = U.transaction(&rng, inputs: rng.int(1...4), outputs: rng.int(1...3))510            for k in tx.inputs.indices { tx.inputs[k].scriptSig = [] }511            let values = tx.inputs.map { _ in rng.pick([546, 100_000, 100_000_000, rng.next() >> 20]) }512            var signed: BitcoinTransaction? = tx513            for k in tx.inputs.indices {514                do {515                    var t = try #require(signed)516                    try BitcoinSigner.signP2PKH(transaction: &t, inputIndex: k, privateKey: key, value: values[k], spentScriptPubKey: script, scheme: scheme)517                    signed = t518                } catch {519                    signed = nil520                }521            }522            items.append(Item(scheme: scheme, unsigned: tx, key: key, compressed: compressed, script: script, values: values, signed: signed))523        }524        let answers = try U.batch("legacy_signed_tx", items.map { i in525            ["tx": i.unsigned.hex, "key": hex(i.key), "scripts": Array(repeating: hex(i.script), count: i.unsigned.inputs.count), "values": i.values, "forkid": i.scheme == .bip143ForkID,526             "compressed": i.compressed] as Case527        })528        for (i, a) in zip(items, answers) {529            var ok = i.signed != nil && i.signed?.hex == a.string("raw") && i.signed?.txid == a.string("txid")530            if let s = i.signed {531                let spent = i.values.map { BitcoinTransaction.Output(value: $0, scriptPubKey: i.script) }532                // valid under its own scheme; Bitcoin Cash's signatures are invalid under Bitcoin's rules and the reverse533                ok = ok && BitcoinVerifier.isValid(transaction: s, spentOutputs: spent, scheme: i.scheme)534                let other: UTXOSighashScheme = i.scheme == .bip143ForkID ? .bip143 : .bip143ForkID535                ok = ok && !BitcoinVerifier.isValid(transaction: s, spentOutputs: spent, scheme: other)536                ok = ok && !s.hasWitness && s.serialized(includeWitness: true) == s.serialized(includeWitness: false)537                let byte: UInt8 = i.scheme == .bip143ForkID ? 0x41 : 0x01538                ok = ok && s.inputs.allSatisfy { $0.scriptSig.count > 1 && $0.scriptSig[Int($0.scriptSig[0])] == byte }539            }540            tally.check(ok, "scheme=\(i.scheme.rawValue) tx=\(i.unsigned.hex) key=\(hex(i.key)) compressed=\(i.compressed) values=\(i.values) ours=\(i.signed?.hex ?? "nil") reference=\(a)")541        }542        #expect(tally.finish() == 0)543    }544545    /// The same Bitcoin Cash payment built and signed by bitcash itself (version 1, final sequences, lock time 0).546    @Test func bitcoinCashTransactionsAgainstBitcash() throws {547        let name = "utxo-bitcoin-cash-transaction"548        guard U.available(name, needs: ["bitcash"]) else { return }549        let seed = DiffSeed.make(name)550        var rng = AuditRNG(seed: seed)551        var tally = DiffTally(name, algorithm: "Bitcoin Cash P2PKH transaction", parameterSet: "SIGHASH_ALL | SIGHASH_FORKID, 1 to 4 inputs, 1 to 3 outputs; raw transaction byte for byte",552                              oracle: U.label("bitcash", "create_p2pkh_transaction, its own preimage and libsecp256k1 signature"), seed: seed)553        struct Item { let key: Bytes; let utxos: [BitcoinUTXO]; let outputs: [BitcoinTransaction.Output]; let signed: BitcoinTransaction? }554        var items = [Item]()555        for _ in 0..<AuditMode.cases(quick: 500, full: 5000) {556            let key = U.key(&rng)557            let script = try BitcoinScript.p2pkh(publicKey: try Secp256k1.publicKey(privateKey: key))558            let utxos = (0..<rng.int(1...4)).map { _ in559                BitcoinUTXO(outPoint: BitcoinOutPoint(hash: rng.bytes(32), index: UInt32(rng.int(0...5)))!, value: rng.pick([1_000, 546, 12_345_678, rng.next() >> 22]), scriptPubKey: script, confirmations: 1)560            }561            let outputs = (0..<rng.int(1...3)).map { _ in562                BitcoinTransaction.Output(value: UInt64(rng.int(546...5_000_000)), scriptPubKey: rng.bool() ? try! BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)) : try! BitcoinScript.p2sh(scriptHash: rng.bytes(20)))563            }564            var tx = BitcoinTransaction(version: 1, inputs: utxos.map { BitcoinTransaction.Input(previousOutput: $0.outPoint) }, outputs: outputs, lockTime: 0)565            var ok = true566            for (k, u) in utxos.enumerated() {567                do { try BitcoinSigner.signP2PKH(transaction: &tx, inputIndex: k, privateKey: key, value: u.value, spentScriptPubKey: script, scheme: .bip143ForkID) } catch { ok = false }568            }569            items.append(Item(key: key, utxos: utxos, outputs: outputs, signed: ok ? tx : nil))570        }571        let answers = try U.batch("bitcash_tx", items.map { i in572            ["key": hex(i.key),573             "inputs": i.utxos.map { ["txid": $0.outPoint.txid, "vout": Int($0.outPoint.index), "amount": $0.value, "script": hex($0.scriptPubKey)] as Case },574             "outputs": i.outputs.map { ["script": hex($0.scriptPubKey), "amount": $0.value] as Case }]575        })576        for (i, a) in zip(items, answers) {577            var ok = i.signed != nil && i.signed?.hex == a.string("raw")578            if let s = i.signed {579                // a lying amount: the signature made for it is not valid for the true one580                ok = ok && BitcoinVerifier.isValid(transaction: s, spentOutputs: i.utxos.map(\.output), scheme: .bip143ForkID)581                let other = i.utxos.map { BitcoinTransaction.Output(value: $0.value + 1, scriptPubKey: $0.scriptPubKey) }582                ok = ok && !BitcoinVerifier.isValid(transaction: s, spentOutputs: other, scheme: .bip143ForkID)583            }584            tally.check(ok, "key=\(hex(i.key)) ours=\(i.signed?.hex ?? "nil") reference=\(a)")585        }586        #expect(tally.finish() == 0)587    }588589    /// Whole path of the wallet account: builder, HD keys, signature — for the three coins — against the oracle.590    @Test func accountSignedPlans() throws {591        let name = "utxo-account-signed-plan"592        guard U.available(name, needs: ["embit", "coincurve"]) else { return }593        let seed = DiffSeed.make(name)594        var rng = AuditRNG(seed: seed)595        var tally = DiffTally(name, algorithm: "wallet account: build, derive, sign (Litecoin P2WPKH, Dogecoin and Bitcoin Cash P2PKH)", parameterSet: "signed transaction or witness signatures byte for byte",596                              oracle: U.label("embit", "sighash_legacy, sighash_segwit") + ", " + U.label("coincurve", "libsecp256k1 RFC 6979") + ", fork-id digest of the oracle", seed: seed)597        struct Item { let network: BitcoinNetwork; let plan: BitcoinTransactionPlan; let key: Bytes; let signed: BitcoinTransaction }598        var items = [Item]()599        for _ in 0..<AuditMode.cases(quick: 300, full: 3000) {600            let network = rng.pick([BitcoinNetwork.litecoin, .dogecoin, .bitcoinCash, .litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet])601            let account = try UTXOAccount(master: try ExtendedKey.master(seed: rng.bytes(32)), network: network)602            let chain: UTXOAccount.Chain = rng.bool() ? .receive : .change603            let index = UInt32(rng.int(0...30))604            let script = try account.scriptPubKey(chain: chain, index: index)605            // coins of one address, each created by a transaction the test makes606            var previous = [String: BitcoinTransaction]()607            var utxos = [BitcoinUTXO]()608            for _ in 0..<rng.int(1...4) {609                let value = UInt64(rng.int(5_000_000...900_000_000)) * (network.coin == .dogecoin ? 100 : 1)610                let funding = BitcoinTransaction(version: 1, inputs: [.init(previousOutput: BitcoinOutPoint(hash: rng.bytes(32), index: 0)!, scriptSig: [0x51])],611                                                 outputs: [.init(value: 1, scriptPubKey: [0x51]), .init(value: value, scriptPubKey: script)])612                previous[funding.txid] = funding613                utxos.append(BitcoinUTXO(outPoint: BitcoinOutPoint(hash: funding.txidBytes, index: 1)!, value: value, scriptPubKey: script, confirmations: 3,614                                         derivation: .init(chain: chain.rawValue, index: index)))615            }616            let total = utxos.reduce(UInt64(0)) { $0 + $1.value }617            let destination = network.supportsSegWit && rng.bool() ? try BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20)) : try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20))618            var request = BitcoinSpendRequest(network: network, recipients: [.init(value: total / UInt64(rng.int(2...6)), scriptPubKey: destination)], utxos: utxos,619                                              feeRate: FeeRate.minimum(for: network), changeScript: try account.scriptPubKey(chain: .change, index: 40))620            request.seed = rng.next()621            request.currentHeight = UInt32(rng.int(0...3_000_000))622            guard let plan = try? BitcoinTransactionBuilder.build(request), let signed = try? account.sign(plan: plan, previousTransactions: previous) else {623                tally.check(false, "build or sign failed on \(network.rawValue)")624                continue625            }626            items.append(Item(network: network, plan: plan, key: try account.privateKey(chain: chain, index: index), signed: signed))627        }628        // P2PKH coins: the whole transaction; P2WPKH coins: digest by embit, signature by libsecp256k1629        let legacy = items.filter { !$0.network.supportsSegWit }630        let rebuilt = try U.batch("legacy_signed_tx", legacy.map {631            ["tx": $0.plan.transaction.hex, "key": hex($0.key), "scripts": $0.plan.inputs.map { hex($0.scriptPubKey) }, "values": $0.plan.inputs.map(\.value),632             "forkid": $0.network.sighashScheme == .bip143ForkID]633        })634        for (i, a) in zip(legacy, rebuilt) {635            let inputTotal = i.plan.inputs.reduce(UInt64(0)) { $0 + $1.value }636            let conserved = i.signed.outputValue(maximumMoney: i.network.maximumMoney).map { inputTotal - $0 == i.plan.fee } ?? false637            tally.check(i.signed.hex == a.string("raw") && i.signed.txid == a.string("txid") && !i.signed.hasWitness && conserved,638                        "\(i.network.rawValue) plan=\(i.plan.transaction.hex) key=\(hex(i.key)) ours=\(i.signed.hex) reference=\(a)")639        }640        let segwit = items.filter { $0.network.supportsSegWit }641        var digestCases = [Case](), owners = [(Item, Int)]()642        for i in segwit {643            let hash = Hash160.hash(try Secp256k1.publicKey(privateKey: i.key))644            for k in i.plan.inputs.indices {645                digestCases.append(["tx": i.plan.transaction.hex, "index": k, "script": hex(try BitcoinScript.p2pkh(publicKeyHash: hash)), "value": i.plan.inputs[k].value, "type": 1])646                owners.append((i, k))647            }648        }649        let digests = try U.batch("segwit_sighash", digestCases)650        let signatures = try U.batch("sign", zip(owners, digests).map { ["key": hex($0.0.0.key), "digest": $0.1.string("digest") ?? ""] })651        for ((owner, s), d) in zip(zip(owners, signatures), digests) {652            let (i, k) = owner653            let witness = i.signed.inputs[k].witness654            let ok = witness.count == 2 && s.bytes("der").map { $0 + [0x01] } == witness[0] && witness[1] == s.bytes("public_key") && i.signed.inputs[k].scriptSig.isEmpty655                && i.signed.txid == i.plan.transaction.txid656            tally.check(ok, "\(i.network.rawValue) input \(k) plan=\(i.plan.transaction.hex) key=\(hex(i.key)) witness=\(witness.map(hex)) digest=\(d) signature=\(s)")657        }658        print("UTXO-DIFF \(name): \(legacy.count) P2PKH transactions compared whole, \(owners.count) P2WPKH input signatures of \(segwit.count) Litecoin transactions")659        #expect(legacy.count > 50 && owners.count > 50)660        #expect(tally.finish() == 0)661    }662663    @Test func rfc6979SignaturesWithTheCoinSighashBytes() throws {664        let name = "utxo-ecdsa-rfc6979"665        guard U.available(name, needs: ["coincurve"]) else { return }666        let seed = DiffSeed.make(name)667        var rng = AuditRNG(seed: seed)668        var tally = DiffTally(name, algorithm: "ECDSA secp256k1 (RFC 6979, low-s, strict DER) as placed in scripts", parameterSet: "DER signature + sighash byte 0x01 / 0x41 / 0xc1…; verification by the reference",669                              oracle: U.label("coincurve", "libsecp256k1"), seed: seed)670        let order = Hex.decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")!671        var items = [(key: Bytes, digest: Bytes, type: UInt32)]()672        for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {673            let digest = rng.bytes(32, orEdge: [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32), order, [1] + Bytes(repeating: 0, count: 31)], oneIn: 12)674            items.append((U.key(&rng), digest, rng.pick([UInt32(0x01), 0x41, 0x41, 0x02, 0x03, 0x81, 0xc1, 0x42, 0x43])))675        }676        let answers = try U.batch("sign", items.map { ["key": hex($0.key), "digest": hex($0.digest)] })677        var verify = [Case]()678        for (i, a) in zip(items, answers) {679            let ours = try? BitcoinSigner.signature(digest: i.digest, privateKey: i.key, sighashType: BitcoinSighashType(rawValue: i.type))680            let ok = ours != nil && ours == a.bytes("der").map { $0 + [UInt8(i.type)] } && (try? Secp256k1.publicKey(privateKey: i.key)) == a.bytes("public_key")681            tally.check(ok, "key=\(hex(i.key)) digest=\(hex(i.digest)) type=\(i.type) ours=\(ours.map(hex) ?? "nil") reference=\(a)")682            verify.append(["public_key": a.string("public_key") ?? "", "der": hex(Bytes((ours ?? [0]).dropLast())), "digest": hex(i.digest)])683        }684        for (i, v) in zip(items, try U.batch("verify", verify)) { tally.check(v.bool("valid") == true, "reference does not verify our signature: key=\(hex(i.key)) digest=\(hex(i.digest))") }685        // hash types outside the six values (with or without the fork-id flag) are not signed686        for bad: UInt32 in [0x00, 0x04, 0x21, 0x61, 0x80, 0xc0, 0x141, 0xff] {687            tally.check((try? BitcoinSigner.signature(digest: Bytes(repeating: 1, count: 32), privateKey: Bytes(repeating: 1, count: 32), sighashType: BitcoinSighashType(rawValue: bad))) == nil, "hash type \(bad) signed")688        }689        #expect(tally.finish() == 0)690    }691}692
Files main
Menu

Theme