SPB Git

Repository Public

AccountTests.swift 7.7 KB 143 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraBitcoinTests/AccountTests.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 Testing42import QyvoraMath43import QyvoraSymmetric44import QyvoraSecp256k145import QyvoraCore46@testable import QyvoraBitcoin4748func unhex(_ s: String) -> Bytes { Hex.decode(s)! }4950let abandonWords = Array(repeating: "abandon", count: 11) + ["about"]5152func abandonMaster() throws -> ExtendedKey {53    try ExtendedKey.master(seed: try BIP39.seed(mnemonic: abandonWords))54}5556@Suite struct BIP84AccountTests {57    @Test func bip84OfficialVector() throws {58        let account = try BIP84Account(master: try abandonMaster(), network: .mainnet)59        #expect(account.extendedPublicKey() == "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs")60        #expect(try account.address(chain: .receive, index: 0).string == "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")61        #expect(try account.address(chain: .receive, index: 1).string == "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g")62        #expect(try account.address(chain: .change, index: 0).string == "bc1q8c6fshw2dlwun7ekn9qwf37cu2rn755upcp6el")63        #expect(try account.publicKey(chain: .receive, index: 0).hex == "0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c")64        #expect(account.path(chain: .change, index: 7).description == "m/84'/0'/0'/1/7")65        #expect(!account.isWatchOnly)66    }6768    @Test func watchOnlyMatchesAndCannotSign() throws {69        let full = try BIP84Account(master: try abandonMaster(), network: .mainnet)70        for text in [full.extendedPublicKey(slip132: true), full.extendedPublicKey(slip132: false)] {71            let watch = try BIP84Account(extendedKey: text, network: .mainnet)72            #expect(watch.isWatchOnly)73            #expect(try watch.address(chain: .receive, index: 5) == full.address(chain: .receive, index: 5))74            #expect(try watch.address(chain: .change, index: 3) == full.address(chain: .change, index: 3))75            var psbt = try PSBT(unsignedTransaction: BitcoinTransaction(inputs: [], outputs: []))76            #expect(throws: BitcoinAccountError.watchOnly) { try watch.sign(psbt: &psbt) }77        }78        #expect(throws: BitcoinAccountError.networkMismatch) { try BIP84Account(extendedKey: full.extendedPublicKey(), network: .testnet) }79        #expect(throws: BitcoinAccountError.invalidAccountKey) { try BIP84Account(extendedKey: "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYt", network: .mainnet) }80    }8182    @Test func testnetAccountUsesCoinType1() throws {83        let account = try BIP84Account(master: try abandonMaster(), network: .testnet)84        #expect(account.accountPath.description == "m/84'/1'/0'")85        let a = try account.address(chain: .receive, index: 0)86        #expect(a.string.hasPrefix("tb1q"))87        #expect(account.extendedPublicKey().hasPrefix("vpub"))88        #expect(account.extendedPublicKey(slip132: false).hasPrefix("tpub"))89    }9091    @Test func gapLimitLogic() throws {92        let account = try BIP84Account(master: try abandonMaster(), network: .testnet)93        #expect(account.nextUnusedIndex(used: []) == 0)94        #expect(account.nextUnusedIndex(used: [0, 1, 4]) == 5)95        #expect(account.scanRange(used: [0, 1, 4]) == 0..<25)96        let next = try account.nextUnusedAddress(chain: .receive, used: [0, 2])97        #expect(next.index == 3)98        #expect(try next.address == account.address(chain: .receive, index: 3))99        #expect(try account.nextUnusedAddress(chain: .receive, used: [0, 2], skipping: 19).index == 22)100        #expect(throws: BitcoinAccountError.gapLimitReached) { try account.nextUnusedAddress(chain: .receive, used: [0, 2], skipping: 20) }101102        // discovery: indices 0, 3 and 22 used (22 is within 20 of 3), 50 is beyond the gap and must not be found103        var usedScripts = Set<Bytes>()104        for i in [0, 3, 22, 50] as [UInt32] { usedScripts.insert(try account.scriptPubKey(chain: .receive, index: i)) }105        let found = try account.discover(chain: .receive, usedScripts: usedScripts)106        #expect(found.used == [0, 3, 22])107        #expect(found.nextUnused == 23)108        let none = try account.discover(chain: .change, usedScripts: usedScripts)109        #expect(none.used.isEmpty && none.nextUnused == 0)110    }111112    @Test func scriptLookup() throws {113        let account = try BIP84Account(master: try abandonMaster(), network: .mainnet)114        let script = try account.scriptPubKey(chain: .change, index: 4)115        let p = try #require(account.locate(scriptPubKey: script, searchLimit: 10))116        #expect(p.chain == .change && p.index == 4)117        #expect(account.locate(scriptPubKey: script, searchLimit: 4) == nil)118        let index = try account.scriptIndex(receiveCount: 6, changeCount: 6)119        #expect(index.count == 12)120        let q = try #require(index.locate(script))121        #expect(q.chain == .change && q.index == 4)122        #expect(index.locate(try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 7, count: 20))) == nil)123    }124125    @Test func accountDescriptors() throws {126        let master = try abandonMaster()127        let account = try BIP84Account(master: master, network: .mainnet)128        let d = try account.descriptors()129        let xpub = account.extendedPublicKey(slip132: false)130        #expect(d.receive.body == "wpkh([73c5da0a/84h/0h/0h]\(xpub)/0/*)")131        #expect(d.change.body == "wpkh([73c5da0a/84h/0h/0h]\(xpub)/1/*)")132        #expect(d.combined.body == "wpkh([73c5da0a/84h/0h/0h]\(xpub)/<0;1>/*)")133        #expect(try d.receive.address(index: 0, network: .mainnet).string == "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")134        #expect(try d.change.address(index: 0, network: .mainnet).string == "bc1q8c6fshw2dlwun7ekn9qwf37cu2rn755upcp6el")135        #expect(try d.combined.address(index: 0, branch: 1, network: .mainnet).string == "bc1q8c6fshw2dlwun7ekn9qwf37cu2rn755upcp6el")136        // text round trip, checksum included137        let reparsed = try OutputDescriptor(parsing: d.receive.string, requireChecksum: true)138        #expect(reparsed == d.receive)139        #expect(try d.combined.singlePath(1) == d.change)140        #expect(throws: DescriptorError.networkMismatch) { try d.receive.address(index: 0, network: .testnet) }141    }142}143
Files main
Menu

Theme