Bitcoin,BitcoinCash(ABC)andDashwallettoolkitforSwift.ThisisafullimplementationofSPVnodeincludingwalletcreation/restore,synchronizationwithnetwork,send/receivetransactions,andmore.TherepositoryincludesthemainBitcoinCore.swiftandBitcoinKit.swift,BitcoinCashKit.swiftandDashKit.swiftseparatepods.
FeaturesFullSPVimplementationforfastmobileperformanceSend/ReceiveLegacytransactions(P2PKH,P2PK,P2SH)BIP32hierarchicaldeterministicwalletsimplementation.BIP39mnemoniccodeforgeneratingdeterministickeys.BIP44multi-accounthierarchyfordeterministicwallets.BIP21URIschemes,whichincludepaymentaddress,amount,labelandotherparamsBitcoinKit.swiftSend/ReceiveSegwittransactions(P2WPKH)Send/ReceiveSegwittransactionscompatiblewithlegacywallets(P2WPKH-SH)base58,bech32BitcoinCashKit.swiftbech32cashaddraddressesDashKit.swiftInstantsendLLMQlock,MasternodesvalidationUsageOnthispage,we'lluseKitstorefertooneofBitcoinKit.swift,BitcoinCashKit.swiftandDashKit.swiftkits.
InitializationKitsrequiresyoutoprovidemnemonicphrasewhenitisinitialized:
letwords=["word1",...,"word12"]BitcoinletbitcoinKit=BitcoinKit(withWords:words,walletId:"bitcoin-wallet-id",syncMode:.api,networkType:.mainNet)BitcoinCashletbitcoinCashKit=BitcoinCashKit(withWords:words,walletId:"bitcoin-cash-wallet-id",syncMode:.api,networkType:.mainNet)DashletdashKit=DashKit(withWords:words,walletId:"dash-wallet-id",syncMode:.api,networkType:.mainNet)All3Kitscanbeconfiguredtoworkin.mainNetor.testNet.
syncModeparameterKitscanrestoreexistingwalletorcreateanewone.Whenrestoring,itgeneratesaddressesforgivenwalletaccordingtobip44protocol,thenitpullsallhistoricaltransactionsforeachofthoseaddresses.Thisisdoneonlyonceoninitialsync.syncModeparameterdefineswhereitpullshistoricaltransactionsfrom.Whentheyarepulled,itcontinuestosyncaccordingtoSPVprotocolnomatterwhichsyncModewasusedforinitialsync.Thereare3modesavailable:
.full:Fullysynchronizesfrompeer-to-peernetworkstartingfromtheblockwhenbip44wasintroduced.Thismodeisthemostprivate(sinceitfullycomplieswithSPVprotocol),butittakesapproximately2hourstosyncuptonow(June10,2019)..api:TransactionsbeforecheckpointarepulledfromAPI(currentlyInsightAPIorBcoinAPI).Thentherestissynchronizedfrompeer-to-peernetwork.Thisisthefastestone,butit'spossibleforanattackertolearnwhichaddressesyouown.Checkpointsareupdatedwitheachnewreleaseandhardcodedsotheblocksvalidationisnotbroken..newWallet:Noneedtopulltransactions.Additionalparameters:confirmationsThreshold:Minimumnumberofconfirmationsrequiredforanunspentoutputinincomingtransactiontobespent(default:6)minLogLevel:Canbeconfiguredfordebugpurposesifrequired.StartingandStoppingKitsrequiretobestartedwithstartcommand.Itwillbeinsyncedstateaslongasitispossible.Youcancallstoptostopit
bitcoinKit.start()bitcoinKit.stop()GettingwalletdataKitsholdallkindsofdataobtainedfromandneededforworkingwithblockchainnetwork
CurrentBalanceBalanceisprovidedinSatoshi:
bitcoinKit.balance//2937096768LastBlockInfoLastblockinfocontainsheaderHash,heightandtimestampthatcanbeusedfordisplayingsyncinfotouser:
bitcoinKit.lastBlockInfo//▿Optional<BlockInfo>//▿some:BlockInfo//-headerHash://"00000000000041ae2164b486398415cca902a41214cad72291ee04b212bed4c4"//-height:1446751//▿timestamp:Optional<Int>//-some:1544097931ReceiveAddressGetanaddresswhichyoucanreceivecoinsto.Receiveaddressischangedeachtimeafteryouactuallygetatransactioninwhichyoureceivecoinstothataddress
bitcoinKit.receiveAddress//"mgv1KTzGZby57K5EngZVaPdPtphPmEWjiS"TransactionsKitshavetransactions(fromHash:nil,limit:nil)methodswhichreturnSingle<TransactionInfo>(forBitcoinKitandBitcoinCashKit)andSingle<DashTransactionInfo>(forDashKit)RXSingleObservers.
TransactionInfo:
//▿TransactionInfo//-transactionHash:"0f83c9b330f936dc4a2458b7d3bb06dce6647a521bf6d98f9c9d3cdd5f6d2a73"//-transactionIndex:500000//▿from:2elements//▿0:TransactionAddressInfo//-address:"mft8jpnf3XwwqhaYSYMSXePFN85mGU4oBd"//-mine:true//▿1:TransactionAddressInfo//-address:"mnNS5LEQDnYC2xqT12MnQmcuSvhfpem8gt"//-mine:true//▿to:2elements//▿0:TransactionAddressInfo//-address:"n43efNftHQ1cXYMZK4Dc53wgR6XgzZHGjs"//-mine:false//▿1:TransactionAddressInfo//-address:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY"//-mine:true//-amount:-800378//▿blockHeight:Optional<Int>//-some:1446602//▿timestamp:Optional<Int>//-some:1543995972DashTransactionInfo:
//▿DashTransactionInfo//-transactionHash:"0f83c9b330f936dc4a2458b7d3bb06dce6647a521bf6d98f9c9d3cdd5f6d2a73"//-transactionIndex:500000//-instantTx:true//▿from:2elements//▿0:TransactionAddressInfo//-address:"mft8jpnf3XwwqhaYSYMSXePFN85mGU4oBd"//-mine:true//▿1:TransactionAddressInfo//-address:"mnNS5LEQDnYC2xqT12MnQmcuSvhfpem8gt"//-mine:true//▿to:2elements//▿0:TransactionAddressInfo//-address:"n43efNftHQ1cXYMZK4Dc53wgR6XgzZHGjs"//-mine:false//▿1:TransactionAddressInfo//-address:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY"//-mine:true//-amount:-800378//▿blockHeight:Optional<Int>//-some:1446602//▿timestamp:Optional<Int>//-some:1543995972CreatingnewtransactionInordertocreatenewtransaction,callsend(to:String,value:Int,feeRate:Int)methodonKits
trybitcoinKit.send(to:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY",value:1000000,feeRate:10000)Thisfirstvalidatesagivenaddressandamount,createsnewtransaction,thensendsitoverthepeersnetwork.Ifthere'sanyerrorwithgivenaddress/amountornetwork,itraisesanexception.
ValidatingtransactionbeforesendOnecanvalidateaddressandfeebyusingfollowingmethods:
trybitcoinKit.validate(address:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY")trybitcoinKit.fee(for:1000000,toAddress:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY",senderPay:true,feeRate:10000)senderPayparameterdefineswhopaysthefee
ParsingBIP21URIYoucanuseparsemethodtoparseaBIP21URI:
bitcoinKit.parse(paymentAddress:"bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz")//▿BitcoinPaymentData//-address:"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"//-version:nil//▿amount:Optional<Double>//-some:50.0//▿label:Optional<String>//-some:"Luke-Jr"//▿message:Optional<String>//-some:"Donationforprojectxyz"//-parameters:nilSubscribingtoBitcoinKitdataKitsprovidewithdataliketransactions,blocks,balance,kitsstateinreal-time.BitcoinCoreDelegateprotocolmustbeimplementedandsettoKitsinstancetoreceivethatdata.
classManager{init(words:[String]){bitcoinKit=BitcoinKit(withWords:words,walletId:"bitcoin-wallet-id")bitcoinKit.delegate=self}}extensionManager:BitcoinCoreDelegate{functransactionsUpdated(inserted:[TransactionInfo],updated:[TransactionInfo]){}functransactionsDeleted(hashes:[String]){}funcbalanceUpdated(balance:Int){}funclastBlockInfoUpdated(lastBlockInfo:BlockInfo){}publicfunckitStateUpdated(state:BitcoinCore.KitState){//BitcoinCore.KitStatecanbeoneof3followingstates://.synced//.syncing(progress:Double)//.notSynced////Thesestatescanbeusedtoimplementprogressbar,etc}}Listenereventsareruninadedicatedbackgroundthread.ItcanbeswitchedtomainthreadbysettingthedelegateQueuepropertytoDispatchQueue.main
bitcoinKit.delegateQueue=DispatchQueue.mainPrerequisitesXcode10.0+Swift5+iOS11+InstallationCocoaPodsCocoaPodsisadependencymanagerforCocoaprojects.Youcaninstallitwiththefollowingcommand:
$geminstallcocoapodsCocoaPods1.5.0+isrequiredtobuildBitcoinKit.
TointegrateBitcoinKitintoyourXcodeprojectusingCocoaPods,specifyitinyourPodfile:
source'https://github.com/CocoaPods/Specs.git'platform:ios,'10.0'use_frameworks!target'<YourTargetName>'dopod'BitcoinCore.swift'pod'BitcoinKit.swift'pod'BitcoinCashKit.swift'pod'DashKit.swift'endThen,runthefollowingcommand:
$podinstallExampleProjectAllfeaturesofthelibraryareusedinexampleproject.Itcanbereferredasastartingpointforusageofthelibrary.
ExampleProjectDependenciesHSHDWalletKit-HDWalletrelatedfeatures,mnemonicphrasegeneration.OpenSslKit.swift-Cryptofunctionsrequiredforworkingwithblockchain.Secp256k1Kit.swift-Cryptofunctionsrequiredforworkingwithblockchain.DashdependenciesBlsKit.swiftX11Kit.swiftLicenseTheBitcoinKit-iOStoolkitisopensourceandavailableunderthetermsoftheMITLicense.
评论