Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/Analysis.swift8// Module : Qyvora Bitcoin9// 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 Foundation42import QyvoraMath43import QyvoraCore4445/// Whether the public key(s) guarding a script are already visible on chain. This is what matters against an46/// adversary able to derive a private key from a public key (a large quantum computer running Shor's algorithm):47/// a key that was never published is only reachable through its hash.48public enum PublicKeyExposure: String, Codable, Sendable, CaseIterable {49 /// Only a hash of the key or script is on chain, and nothing was ever spent from it (P2PKH, P2SH, P2WPKH, P2WSH).50 case hashedUnrevealed51 /// A hashed script that has already been spent from: the spending input published the key(s).52 case revealedBySpend53 /// The script itself contains the key (P2PK, bare multisig, the Taproot output key).54 case revealedByScript55 /// Nothing can be said: provably unspendable, non-standard, or a witness version without assigned meaning.56 case undetermined57}5859public struct PublicKeyExposureAssessment: Equatable, Sendable {60 public let exposure: PublicKeyExposure61 public let scriptType: BitcoinScriptType62 /// One sentence for the user interface.63 public let explanation: String64}6566/// One on-chain (or mempool) event touching a script, as the caller knows it from its indexer.67public struct ScriptActivity: Equatable, Hashable, Sendable {68 public enum Kind: String, Sendable, Codable {69 /// A transaction output paid to the script.70 case funded71 /// A transaction input spent an output of the script.72 case spent73 }7475 public let scriptPubKey: Bytes76 public let kind: Kind77 /// Transaction that created the output (funded) or that spent it (spent), display hexadecimal.78 public let txid: String79 /// Block height, nil while unconfirmed.80 public let height: UInt32?8182 public init(scriptPubKey: Bytes, kind: Kind, txid: String, height: UInt32?) {83 self.scriptPubKey = scriptPubKey84 self.kind = kind85 self.txid = txid86 self.height = height87 }88}8990/// Address reuse found for one script.91public struct AddressReuseFinding: Equatable, Sendable {92 public let scriptPubKey: Bytes93 /// Distinct transactions that paid the script.94 public let fundingTransactionCount: Int95 /// More than one transaction paid the script.96 public let fundedByMultipleTransactions: Bool97 /// The script received a payment after one of its outputs had been spent (its public key was already published).98 public let fundedAfterSpend: Bool99}100101/// Pure privacy and key-exposure analysis over data the caller supplies; nothing here touches the network.102public enum BitcoinPrivacyAnalysis {103 /// Classifies the exposure of the key(s) behind a script. `hasSpend` says whether any output of this exact script has104 /// already been spent (on chain or in the mempool).105 public static func publicKeyExposure(scriptPubKey: Bytes, hasSpend: Bool) -> PublicKeyExposureAssessment {106 let cls = BitcoinScript.classify(scriptPubKey)107 func result(_ e: PublicKeyExposure, _ text: String) -> PublicKeyExposureAssessment {108 PublicKeyExposureAssessment(exposure: e, scriptType: cls.type, explanation: text)109 }110 switch cls {111 case .p2pk:112 return result(.revealedByScript, "Pay-to-public-key output: the public key is written in the output itself.")113 case .multisig:114 return result(.revealedByScript, "Bare multisig output: every public key is written in the output itself.")115 case .p2tr:116 return result(.revealedByScript, "Taproot output: the output key is a public key written in the output itself.")117 case .p2pkh, .p2wpkh:118 return hasSpend119 ? result(.revealedBySpend, "This address has already been spent from: its public key was published by that spend.")120 : result(.hashedUnrevealed, "Only the hash of the public key is on chain; the key stays hidden until the first spend.")121 case .p2sh, .p2wsh:122 return hasSpend123 ? result(.revealedBySpend, "This address has already been spent from: its script and public keys were published by that spend.")124 : result(.hashedUnrevealed, "Only the hash of the script is on chain; its public keys stay hidden until the first spend.")125 case .nullData:126 return result(.undetermined, "Data carrier output: it holds no key and can never be spent.")127 case .witnessUnknown:128 return result(.undetermined, "Witness program of a version without assigned meaning: exposure cannot be assessed.")129 case .unknown:130 return result(.undetermined, "Non-standard script: exposure cannot be assessed.")131 }132 }133134 /// Exposure of each UTXO, using `activity` to know which scripts already have a spend.135 public static func publicKeyExposure(utxos: [BitcoinUTXO], activity: [ScriptActivity]) -> [BitcoinOutPoint: PublicKeyExposureAssessment] {136 let spentScripts = Set(activity.filter { $0.kind == .spent }.map(\.scriptPubKey))137 var out = [BitcoinOutPoint: PublicKeyExposureAssessment]()138 for u in utxos { out[u.outPoint] = publicKeyExposure(scriptPubKey: u.scriptPubKey, hasSpend: spentScripts.contains(u.scriptPubKey)) }139 return out140 }141142 /// Address reuse per script: funded by more than one transaction, or funded after a spend.143 ///144 /// "After" is decided on block heights: a funding at a greater height than the earliest spend, or an unconfirmed145 /// funding while a spend is confirmed. Two events of the same block, or both unconfirmed, cannot be ordered from the146 /// data given and are not counted (a deposit spent within the same block is not reuse). Scripts without any finding147 /// are omitted; the result is sorted by script for determinism.148 public static func addressReuse(activity: [ScriptActivity]) -> [AddressReuseFinding] {149 var byScript = [Bytes: [ScriptActivity]]()150 for a in activity { byScript[a.scriptPubKey, default: []].append(a) }151 var findings = [AddressReuseFinding]()152 for (script, events) in byScript {153 let fundings = events.filter { $0.kind == .funded }154 let fundingTxids = Set(fundings.map(\.txid))155 let spendHeights = events.filter { $0.kind == .spent }.map(\.height)156 var after = false157 if !spendHeights.isEmpty {158 let earliestConfirmed = spendHeights.compactMap { $0 }.min()159 for f in fundings {160 switch (f.height, earliestConfirmed) {161 case (.some(let fh), .some(let sh)): if fh > sh { after = true }162 case (.none, .some): after = true163 default: break164 }165 }166 }167 let multiple = fundingTxids.count > 1168 if multiple || after {169 findings.append(AddressReuseFinding(scriptPubKey: script, fundingTransactionCount: fundingTxids.count,170 fundedByMultipleTransactions: multiple, fundedAfterSpend: after))171 }172 }173 return findings.sorted { $0.scriptPubKey.lexicographicallyPrecedes($1.scriptPubKey) }174 }175176 /// True when the address (given by its script) shows reuse in `activity`.177 public static func isReused(scriptPubKey: Bytes, activity: [ScriptActivity]) -> Bool {178 !addressReuse(activity: activity.filter { $0.scriptPubKey == scriptPubKey }).isEmpty179 }180}181