SPB Git

Repository Public

EncodingProperties.swift 19.2 KB 323 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/EncodingProperties.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 Testing4546@testable import QyvoraBitcoin47@testable import QyvoraCore48@testable import QyvoraEthereum49@testable import QyvoraSecp256k15051// Round-trip and agreement invariants of the encodings and derivations the wallet relies on.5253func randomKey(_ rng: inout AuditRNG) -> Bytes {54    while true {55        let k = rng.bytes(32)56        if Secp256k1.isValidPrivateKey(k) { return k }57    }58}5960@Suite struct EthereumEncodingProperties {61    static func randomRLP(_ rng: inout AuditRNG, depth: Int) -> RLP {62        if depth >= 4 || rng.int(0...2) > 0 {63            let lengths = [0, 1, 1, 2, 31, 32, 55, 56, 57, 255, 256, 300]64            var b = rng.bytes(rng.pick(lengths))65            if b.count == 1, rng.bool() { b[0] &= 0x7f }66            return .bytes(b)67        }68        return .list((0..<rng.int(0...6)).map { _ in randomRLP(&rng, depth: depth + 1) })69    }7071    @Test func rlpRoundTrip() throws {72        let seed = AuditSeed.make("rlp.roundtrip")73        var rng = AuditRNG(seed: seed)74        var prop = Prop("decode(encode(x)) = x and encode(decode(b)) = b; trailing data and nesting beyond the limit refused", algorithm: "RLP", seed: seed)75        for _ in 0..<AuditMode.cases(quick: 3000, full: 30000) {76            let item = Self.randomRLP(&rng, depth: 0)77            let encoded = item.encoded78            let decoded = try? RLP.decode(encoded)79            prop.check(decoded == item, "round trip")80            prop.check(decoded?.encoded == encoded, "canonical re-encoding")81            prop.check((try? RLP.decode(encoded + [0x00])) == nil, "trailing byte accepted")82            if encoded.count > 1 { prop.check((try? RLP.decode(Bytes(encoded.dropLast()))) == nil, "truncated input accepted") }83        }84        // non-canonical forms85        for bad: Bytes in [[0x81, 0x05], [0xb8, 0x01, 0x41], [0xb8, 0x00], [0xf8, 0x00], [0xb9, 0x00, 0x38] + Bytes(repeating: 1, count: 56), [0xbf] + Bytes(repeating: 0xff, count: 8)] {86            prop.check((try? RLP.decode(bad)) == nil, "non-canonical or oversized length accepted: \(Hex.encode(bad.prefix(4)))")87        }88        // 100 nested lists: refused, without recursion trouble89        var deep = RLP.list([])90        for _ in 0..<100 { deep = .list([deep]) }91        prop.check((try? RLP.decode(deep.encoded)) == nil, "nesting of 100 accepted")92        prop.finish()93    }9495    @Test func transactionRoundTrip() throws {96        let seed = AuditSeed.make("eip1559.roundtrip")97        var rng = AuditRNG(seed: seed)98        var prop = Prop("sign → raw → decode = same transaction; sender = signer; chain id inside the signed payload", algorithm: "EIP-1559 transaction", seed: seed)99        func amount(_ rng: inout AuditRNG) -> UInt256 {100            let n = rng.pick([0, 1, 8, 16, 32])101            return UInt256(bigEndian: Bytes(repeating: 0, count: 32 - n) + rng.bytes(n))!102        }103        for _ in 0..<AuditMode.cases(quick: 300, full: 3000) {104            let key = randomKey(&rng)105            let tip = UInt256(rng.next() >> 20)106            let (maxFee, _) = tip.addingReportingOverflow(UInt256(rng.next() >> 20))107            let to: EthereumAddress? = rng.int(0...9) == 0 ? nil : EthereumAddress(bytes: rng.bytes(20))108            let access = (0..<rng.int(0...2)).map { _ in109                EIP1559Transaction.AccessListEntry(address: EthereumAddress(bytes: rng.bytes(20))!, storageKeys: (0..<rng.int(0...3)).map { _ in rng.bytes(32) })110            }111            let tx = EIP1559Transaction(112                chainID: rng.pick([1, 11_155_111, 17000, rng.next() >> 12]), nonce: rng.next() >> UInt64(rng.int(0...63)),113                maxPriorityFeePerGas: tip, maxFeePerGas: maxFee, gasLimit: rng.next() >> 30, to: to, value: amount(&rng),114                data: rng.bytes(rng.pick([0, 0, 4, 68, 200])), accessList: access)115            let signed = try tx.sign(privateKey: key)116            let decoded = try? SignedEIP1559Transaction.decode(signed.raw)117            prop.check(decoded == signed, "signed round trip")118            prop.check((try? EIP1559Transaction.decodeUnsigned(tx.unsignedPayload)) == tx, "unsigned round trip")119            let expected = try EthereumAddress(publicKey: try Secp256k1.publicKey(privateKey: key, compressed: false))120            prop.check((try? signed.sender()) == expected, "sender")121            // replay protection: the same fields on another chain give another digest and the signature no longer recovers the signer122            var other = tx123            other.chainID = tx.chainID &+ 1124            prop.check(other.signingHash != tx.signingHash, "chain id not part of the digest")125            let replay = SignedEIP1559Transaction(transaction: other, yParity: signed.yParity, r: signed.r, s: signed.s)126            prop.check((try? replay.sender()) != expected, "signature valid on another chain id")127            // a flipped bit in the raw transaction never decodes to the same signer and fields128            var raw = signed.raw129            raw[rng.int(1...(raw.count - 1))] ^= UInt8(1 << rng.int(0...7))130            if let d = try? SignedEIP1559Transaction.decode(raw) {131                prop.check(!(d.transaction == tx && (try? d.sender()) == expected), "bit flip kept transaction and signer")132            } else {133                prop.check(true)134            }135        }136        prop.finish()137    }138139    @Test func addressChecksum() throws {140        let seed = AuditSeed.make("eip55")141        var rng = AuditRNG(seed: seed)142        var prop = Prop("EIP-55: checksummed form round-trips, a wrong mixed-case checksum is refused", algorithm: "Ethereum address", seed: seed)143        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {144            let a = EthereumAddress(bytes: rng.bytes(20))!145            let text = a.checksummed146            prop.check(EthereumAddress(text) == a, "checksummed round trip")147            prop.check(EthereumAddress(text.lowercased()) == a, "lower case accepted")148            // flip the case of one letter: mixed case with a wrong checksum149            var chars = Array(text)150            if let i = chars.indices.dropFirst(2).first(where: { chars[$0].isLetter }) {151                chars[i] = chars[i].isUppercase ? Character(chars[i].lowercased()) : Character(chars[i].uppercased())152                let altered = String(chars)153                let mixed = altered.dropFirst(2).contains { $0.isUppercase } && altered.dropFirst(2).contains { $0.isLowercase && $0.isLetter }154                if mixed { prop.check(EthereumAddress(altered) == nil, "wrong checksum accepted: \(altered)") }155            }156            prop.check(EthereumAddress(String(text.dropLast())) == nil && EthereumAddress(text + "0") == nil && EthereumAddress(String(text.dropFirst(2))) == nil, "wrong length or prefix")157        }158        prop.finish()159    }160}161162@Suite struct BitcoinEncodingProperties {163    static func randomTransaction(_ rng: inout AuditRNG, witness: Bool) -> BitcoinTransaction {164        let inputs = (0..<rng.int(1...4)).map { _ in165            BitcoinTransaction.Input(166                previousOutput: BitcoinOutPoint(hash: rng.bytes(32), index: UInt32(truncatingIfNeeded: rng.next() >> 40))!,167                scriptSig: witness ? [] : rng.bytes(rng.int(0...110)), sequence: UInt32(truncatingIfNeeded: rng.next()),168                witness: witness ? (0..<rng.int(1...3)).map { _ in rng.bytes(rng.pick([0, 33, 71, 72])) } : [])169        }170        let outputs = (0..<rng.int(1...4)).map { _ in171            BitcoinTransaction.Output(value: rng.next() % 2_100_000_000_000_000, scriptPubKey: [0x00, 0x14] + rng.bytes(20))172        }173        return BitcoinTransaction(version: rng.bool() ? 2 : 1, inputs: inputs, outputs: outputs, lockTime: UInt32(truncatingIfNeeded: rng.next()))174    }175176    @Test func transactionRoundTrip() throws {177        let seed = AuditSeed.make("btc.tx.roundtrip")178        var rng = AuditRNG(seed: seed)179        var prop = Prop("parse(serialize(tx)) = tx with and without witness; truncation and trailing bytes refused", algorithm: "Bitcoin transaction", seed: seed)180        for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {181            let witness = rng.bool()182            let tx = Self.randomTransaction(&rng, witness: witness)183            let bytes = tx.serialized()184            let parsed = try? BitcoinTransaction(parsing: bytes)185            prop.check(parsed == tx, "round trip")186            prop.check(parsed?.serialized() == bytes, "re-serialisation")187            prop.check((try? BitcoinTransaction(parsing: bytes + [0])) == nil, "trailing byte accepted")188            prop.check((try? BitcoinTransaction(parsing: Bytes(bytes.dropLast(rng.int(1...min(8, bytes.count)))))) == nil, "truncated input accepted")189            if witness {190                // the witness-stripped form parses to the same transaction without witnesses191                let stripped = try? BitcoinTransaction(parsing: tx.serialized(includeWitness: false))192                prop.check(stripped?.outputs == tx.outputs && stripped?.inputs.map(\.previousOutput) == tx.inputs.map(\.previousOutput), "stripped form")193            }194        }195        prop.finish()196    }197198    @Test func psbtRoundTrip() throws {199        let seed = AuditSeed.make("psbt.roundtrip")200        var rng = AuditRNG(seed: seed)201        var prop = Prop("PSBT built from a transaction serialises and parses back to an equal object", algorithm: "PSBT (BIP-174)", seed: seed)202        for _ in 0..<AuditMode.cases(quick: 500, full: 5000) {203            var tx = Self.randomTransaction(&rng, witness: false)204            tx = BitcoinTransaction(205                version: tx.version, inputs: tx.inputs.map { BitcoinTransaction.Input(previousOutput: $0.previousOutput, sequence: $0.sequence) },206                outputs: tx.outputs, lockTime: tx.lockTime)207            guard var psbt = try? PSBT(unsignedTransaction: tx) else {208                prop.check(false, "PSBT(unsignedTransaction:) refused a valid unsigned transaction")209                continue210            }211            for i in tx.inputs.indices where rng.bool() {212                try psbt.setWitnessUTXO(BitcoinTransaction.Output(value: rng.next() % 1_000_000_000, scriptPubKey: [0x00, 0x14] + rng.bytes(20)), inputIndex: i)213            }214            let bytes = psbt.serialized()215            let parsed = try? PSBT(parsing: bytes)216            prop.check(parsed == psbt, "round trip")217            prop.check(parsed?.serialized() == bytes, "re-serialisation")218            prop.check((try? PSBT(parsing: Bytes(bytes.dropLast()))) == nil, "truncated PSBT accepted")219        }220        prop.finish()221    }222223    @Test func derivationDescriptorsAndAddresses() throws {224        let seed = AuditSeed.make("bip32.agreement")225        var rng = AuditRNG(seed: seed)226        var prop = Prop("public derivation = neutered private derivation; hardened from public refused; xpub/descriptor/address round trips", algorithm: "BIP-32 / descriptors / addresses", seed: seed)227        for _ in 0..<AuditMode.cases(quick: 150, full: 1500) {228            let master = try ExtendedKey.master(seed: rng.bytes(rng.pick([16, 32, 64])))229            // the three Bitcoin networks: BIP-84 accounts and descriptors (the other UTXO coins have their own suite, UTXOCoinsProperties)230            let network = rng.pick([BitcoinNetwork.mainnet, .testnet, .signet])231            let account = try master.derive(DerivationPath("m/84'/\(network.coinType)'/\(rng.int(0...5))'")!)232            let publicAccount = account.neutered233            // public vs private derivation over a random non-hardened path234            var prv = account, pub = publicAccount235            for _ in 0..<rng.int(1...4) {236                let child = ChildIndex.normal(UInt32(truncatingIfNeeded: rng.next() >> 33))237                prv = try prv.derive(child)238                pub = try pub.derive(child)239                prop.check(prv.neutered.publicKey == pub.publicKey && prv.chainCode == pub.chainCode && pub.privateKey == nil, "public = private derivation")240                prop.check(prv.publicKey == (try Secp256k1.publicKey(privateKey: prv.privateKey!)), "public key of the derived private key")241            }242            prop.check((try? publicAccount.derive(.hardened(0))) == nil, "hardened derivation from a public key")243            // extended-key text round trip (xpub/tpub and xprv/tprv)244            let pubVersion: ExtendedKey.Version = network.isTest ? .tpub : .xpub, prvVersion: ExtendedKey.Version = network.isTest ? .tprv : .xprv245            let xpub = try publicAccount.serialized(pubVersion), xprv = try account.serialized(prvVersion)246            let p1 = try? ExtendedKey.parse(xpub), p2 = try? ExtendedKey.parse(xprv)247            prop.check(p1?.key.publicKey == publicAccount.publicKey && p1?.key.chainCode == account.chainCode && p1?.version == pubVersion, "xpub round trip")248            prop.check(p2?.key.privateKey == account.privateKey && p2?.version == prvVersion, "xprv round trip")249            prop.check((try? publicAccount.serialized(prvVersion)) == nil, "public key serialised as private")250            var chars = Array(xpub)251            let k = rng.int(4...(chars.count - 1))252            chars[k] = chars[k] == "2" ? "3" : "2"253            prop.check((try? ExtendedKey.parse(String(chars))) == nil, "altered xpub accepted (Base58Check)")254            // descriptors: text → parse → same descriptor and same scripts; checksum enforced255            let descriptors = try OutputDescriptor.bip84(accountKey: account, network: network, masterFingerprint: master.fingerprint)256            for d in [descriptors.receive, descriptors.change] {257                let parsed = try? OutputDescriptor(parsing: d.string, requireChecksum: true)258                prop.check(parsed == d, "descriptor round trip")259                let index = UInt32(rng.int(0...1000))260                let script = try d.scriptPubKey(index: index)261                prop.check(try parsed?.scriptPubKey(index: index) == script, "same script after parsing")262                var text = Array(d.string)263                text[text.count - 1] = text[text.count - 1] == "q" ? "p" : "q"264                prop.check((try? OutputDescriptor(parsing: String(text))) == nil, "wrong descriptor checksum accepted")265                // the address of the descriptor is the BIP-84 address of the derived key, and it round-trips266                let branch: UInt32 = d == descriptors.receive ? 0 : 1267                let key = try publicAccount.derive(.normal(branch)).derive(.normal(index))268                let address = try BitcoinAddress.p2wpkh(publicKey: key.publicKey, network: network)269                prop.check(try d.address(index: index, network: network) == address, "descriptor address = BIP-84 address")270                let reparsed = try? BitcoinAddress(address.string, network: network)271                prop.check(reparsed == address && reparsed?.scriptPubKey == script, "address round trip")272                let wrong: BitcoinNetwork = network == .mainnet ? .testnet : .mainnet273                prop.check(BitcoinAddress.parse(address.string, network: wrong) == nil, "address accepted on the wrong network")274                var a = Array(address.string)275                let j = rng.int(4...(a.count - 1))276                a[j] = a[j] == "q" ? "p" : "q"277                prop.check(BitcoinAddress.parse(String(a), network: network) == nil, "altered address accepted (Bech32 checksum)")278            }279        }280        prop.finish()281    }282283    @Test func base58AndBech32() {284        let seed = AuditSeed.make("base58.bech32")285        var rng = AuditRNG(seed: seed)286        var prop = Prop("Base58Check and Bech32/Bech32m: round trips, single-character errors detected, variants not interchangeable", algorithm: "Base58Check / Bech32", seed: seed)287        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {288            var payload = rng.bytes(rng.int(1...40))289            if rng.int(0...3) == 0 { payload = Bytes(repeating: 0, count: rng.int(1...4)) + payload }290            let text = Base58Check.encode(payload)291            prop.check(Base58Check.decode(text) == payload, "Base58Check round trip")292            var chars = Array(text)293            let i = rng.int(0...(chars.count - 1))294            chars[i] = chars[i] == "z" ? "y" : "z"295            if String(chars) != text { prop.check(Base58Check.decode(String(chars)) != payload, "Base58Check altered text decodes to the same payload") }296            prop.check(Base58.bitcoin.decode(Base58.bitcoin.encode(payload)) == payload, "Base58 round trip")297298            let data = rng.bytes(rng.int(0...40))299            prop.check(Bech32.fromWords(Bech32.toWords(data)) == data, "5-bit regrouping round trip")300            for variant in [Bech32.Variant.bech32, .bech32m] {301                let words = Bech32.toWords(data)302                guard let encoded = Bech32.encode(hrp: "tb", words: words, variant: variant) else {303                    prop.check(words.count + 9 > 90, "encode refused a short string")304                    continue305                }306                prop.check(Bech32.decode(encoded, variant: variant)?.words == words, "Bech32 round trip")307                prop.check(Bech32.decode(encoded, variant: variant == .bech32 ? .bech32m : .bech32) == nil, "variant confusion")308                prop.check(Bech32.decode(encoded.uppercased(), variant: variant)?.words == words, "upper case accepted")309                var c = Array(encoded)310                let j = rng.int(3...(c.count - 1))311                c[j] = c[j] == "q" ? "p" : "q"312                prop.check(Bech32.decode(String(c), variant: variant) == nil, "single substitution accepted")313                var mixed = Array(encoded)314                if let l = mixed.indices.first(where: { mixed[$0].isLetter && $0 > 2 }) {315                    mixed[l] = Character(mixed[l].uppercased())316                    prop.check(Bech32.decode(String(mixed), variant: variant) == nil, "mixed case accepted")317                }318            }319        }320        prop.finish()321    }322}323
Files main
Menu

Theme