bitcoin-kit-ios

我要开发同款
匿名用户2021年11月30日
15阅读
所属分类、Web3、区块链
授权协议MIT License

作品详情

BitcoinKit-iOS

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,MasternodesvalidationUsage

Onthispage,we'lluseKitstorefertooneofBitcoinKit.swift,BitcoinCashKit.swiftandDashKit.swiftkits.

Initialization

Kitsrequiresyoutoprovidemnemonicphrasewhenitisinitialized:

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.

syncModeparameter

Kitscanrestoreexistingwalletorcreateanewone.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.StartingandStopping

Kitsrequiretobestartedwithstartcommand.Itwillbeinsyncedstateaslongasitispossible.Youcancallstoptostopit

bitcoinKit.start()bitcoinKit.stop()Gettingwalletdata

Kitsholdallkindsofdataobtainedfromandneededforworkingwithblockchainnetwork

CurrentBalance

BalanceisprovidedinSatoshi:

bitcoinKit.balance//2937096768LastBlockInfo

LastblockinfocontainsheaderHash,heightandtimestampthatcanbeusedfordisplayingsyncinfotouser:

bitcoinKit.lastBlockInfo//▿Optional<BlockInfo>//▿some:BlockInfo//-headerHash://"00000000000041ae2164b486398415cca902a41214cad72291ee04b212bed4c4"//-height:1446751//▿timestamp:Optional<Int>//-some:1544097931ReceiveAddress

Getanaddresswhichyoucanreceivecoinsto.Receiveaddressischangedeachtimeafteryouactuallygetatransactioninwhichyoureceivecoinstothataddress

bitcoinKit.receiveAddress//"mgv1KTzGZby57K5EngZVaPdPtphPmEWjiS"Transactions

Kitshavetransactions(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:1543995972

DashTransactionInfo:

//▿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:1543995972Creatingnewtransaction

Inordertocreatenewtransaction,callsend(to:String,value:Int,feeRate:Int)methodonKits

trybitcoinKit.send(to:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY",value:1000000,feeRate:10000)

Thisfirstvalidatesagivenaddressandamount,createsnewtransaction,thensendsitoverthepeersnetwork.Ifthere'sanyerrorwithgivenaddress/amountornetwork,itraisesanexception.

Validatingtransactionbeforesend

Onecanvalidateaddressandfeebyusingfollowingmethods:

trybitcoinKit.validate(address:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY")trybitcoinKit.fee(for:1000000,toAddress:"mrjQyzbX9SiJxRC2mQhT4LvxFEmt9KEeRY",senderPay:true,feeRate:10000)

senderPayparameterdefineswhopaysthefee

ParsingBIP21URI

YoucanuseparsemethodtoparseaBIP21URI:

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:nilSubscribingtoBitcoinKitdata

Kitsprovidewithdataliketransactions,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+InstallationCocoaPods

CocoaPodsisadependencymanagerforCocoaprojects.Youcaninstallitwiththefollowingcommand:

$geminstallcocoapods

CocoaPods1.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'end

Then,runthefollowingcommand:

$podinstallExampleProject

Allfeaturesofthelibraryareusedinexampleproject.Itcanbereferredasastartingpointforusageofthelibrary.

ExampleProjectDependenciesHSHDWalletKit-HDWalletrelatedfeatures,mnemonicphrasegeneration.OpenSslKit.swift-Cryptofunctionsrequiredforworkingwithblockchain.Secp256k1Kit.swift-Cryptofunctionsrequiredforworkingwithblockchain.DashdependenciesBlsKit.swiftX11Kit.swiftLicense

TheBitcoinKit-iOStoolkitisopensourceandavailableunderthetermsoftheMITLicense.

查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论