A native Bitcoin SPV client library for iOS with BIP32 support.
BitcoinSPV is a native Bitcoin SPV (Simplified Payment Verification) client library for iOS written in Objective-C. It conveniently supports Bloom filters (BIP37) and hierarchical deterministic wallets (BIP32).
BitcoinSPV is still experimental and you DO NOT want to use it in production environments today.
The library is thorough and features a moderately high granularity to isolate the smallest bits of the Bitcoin protocol. Many atomic classes make up the whole thing in tiny steps while also decoupling the user from the areas he's not interested in, because files interdependency is kept at an unnoticeable minimum.
Grouped by area:
Global
NSError
objects returned by the library.Parameters
Core
Blockchain
Protocol
Networking
Wallet
Currency
Web
BIPS
BitcoinSPV depends on four well known libraries:
Setup is straightforward thanks to the brilliant CocoaPods utility. I usually test the software on iOS 7 but everything should be fine on 6.x as well.
Add the following line:
pod 'BitcoinSPV', '~> 0.7.1'
and run on the terminal:
$ pod install
Beware that some recent versions of CocoaPods may break static linking unless you remove the following line from the Pods/Pods.*.xcconfig
configuration files:
OTHER_LIBTOOLFLAGS = $(OTHER_LDFLAGS)
All the imports are public but the one you generally need is #import "BitcoinSPV.h"
.
The BitcoinSPVTests
target comes with a couple of automated tests. They don't completely test all the library features (especially the networking area), but they're certainly required to succeed. A single fail guarantees that something's broken.
Some tests write files on disk in the global Library/Caches
of the iPhone Simulator. You can find them under the BitcoinSPVTests
subdirectory.
Developers familiar with bitcoinj may recall some of the class names in the following snippets:
#import "BitcoinSPV.h"
- (void)createWallet
{
WSParameters *parameters = WSParametersForNetworkType(WSNetworkTypeTestnet3);
WSSeed *seed = [[WSSeedGenerator sharedInstance] generateRandomSeed];
// now's the time to backup the seed somewhere, show it to the user etc.
id<WSBlockStore> store = [[WSMemoryBlockStore alloc] initWithParameters:parameters];
WSHDWallet *wallet = [[WSHDWallet alloc] initWithParameters:parameters seed:seed];
WSBlockChainDownloader *downloader = [[WSBlockChainDownloader alloc] initWithStore:store wallet:wallet];
WSPeerGroup *peerGroup = [[WSPeerGroup alloc] initWithParameters:parameters];
[peerGroup startConnections];
[peerGroup startDownloadWithDownloader:downloader];
// strongly retain peer group
self.peerGroup = peerGroup;
}
#import "BitcoinSPV.h"
- (void)restoreWallet
{
WSParameters *parameters = WSParametersForNetworkType(WSNetworkTypeTestnet3);
WSSeed *seed = WSSeedMakeFromISODate(@"enter your bip39 mnemonic seed phrase", @"2014-02-28");
id<WSBlockStore> store = [[WSMemoryBlockStore alloc] initWithParameters:parameters];
WSHDWallet *wallet = [[WSHDWallet alloc] initWithParameters:parameters seed:seed];
WSBlockChainDownloader *downloader = [[WSBlockChainDownloader alloc] initWithStore:store wallet:wallet];
WSPeerGroup *peerGroup = [[WSPeerGroup alloc] initWithParameters:parameters];
[peerGroup startConnections];
[peerGroup startDownloadWithDownloader:downloader];
// strongly retain peer group
self.peerGroup = peerGroup;
}
Bitcoin nodes can operate on three networks:
Most initializers depend on network parameters, you can get a reference with the following code:
// networkType must be one of: WSNetworkTypeMain, WSNetworkTypeTestnet3, WSNetworkTypeRegtest
WSParameters *networkParameters = WSParametersForNetworkType(WSNetworkTypeTestnet3);
...
WARNING: operating on main network may cost you real money, make sure you know what you're doing!
BIP39 gives special hints on how human-readable phrases (mnemonics) can produce a binary seed for HD wallets. BitcoinSPV implements the BIP39 specification in the WSSeedGenerator
class that can be used to:
However, mnemonics in BitcoinSPV are usually wrapped in a WSSeed
object that also contains the time the mnemonic was first created. Blockchain sync time can be dramatically faster by specifying such a time (called the "fast catch-up time") because blocks found before won't contain relevant transactions to our wallet and can be safely skipped.
HD wallets are described in BIP32. In BitcoinSPV they're instances of the WSHDWallet
class and built from a WSSeed
object with an optional gap limit (default is 10). An additional set of look-ahead addresses is also pregenerated internally to prevent Bloom filter from being reloaded each time a transaction consumes a new address.
It's worth noting that the seed mnemonic is a very sensitive information -it technically holds all your coins- and as such it's not serialized with the [WSWallet saveToPath:]
method: this means you must store it elsewhere, e.g. in the keychain. The mnemonic will be vital to restore later a serialized wallet with the [WSHDWallet loadFromPath:parameters:seed:]
method.
Classes implementing the WSBlockStore
protocol take charge of serializing a blockchain. There is currently one implementation: WSMemoryBlockStore
. The name is quite self-explanatory.
The WSPeerGroup
class holds the whole logic for connecting to the Bitcoin network and is the main event notification source. A group can simultaneously connect to several nodes, enforce the number of connected nodes and download the blockchain to a block store. When built with a wallet it also forwards relevant blocks and transactions to the wallet. The wallet in turn registers them and internally updates its history, UTXOs, confirmations etc.
Last but not least, the key interaction with the network is clearly the ability of publishing transactions. Not surprisingly, this is done with the publishTransaction:
method.
Bitcoin structures are generally little-endian, an example consequence is that transaction and block hashes are seen "reversed" in hex editors compared to how we see them on web blockchain explorers like Blockchain.info. There are exceptions, though, because network addresses retain the standard big-endian byte order. Yes, this all makes binary encoding quite error-prone.
That's why BitcoinSPV wraps the encoding internals in the WSBuffer
and WSMutableBuffer
classes. With a buffer class you can safely read/write arbitrary bytes or basic structures like hashes, network addresses, inventories etc. without the hassle of protocol byte order.
BitcoinSPV relies on the Grand Central Dispatch, meaning that most of the code is expected to run on multiple queues to achieve best performance. In an attempt to limit the overall complexity, I cut mutable objects usage to a minimum. The immutable approach dramatically simplifies critical sections and guarantees the integrity of serialized data for free. No Core Data entity is mutable, nor are blockchain-related structures in general. Think about it, altering an accepted block would even defeat the purpose of the protocol.
Sensitive data are never serialized automatically so that clients will be able to save them by other, safer means. For example, transactions and addresses of a HD wallet can be safely written to a file, while the secret mnemonic deserves more attention. You may store it encrypted into the keychain, you may retrieve it encrypted from a service provider and decrypt it locally, you may even decide not to store it at all. In fact there's total freedom on how to preserve mnemonics security.
BitcoinSPV is still a work-in-progress and will eventually undergo huge modifications. Several basic things are left to do, sorted by priority:
BitcoinSPV is released under the GPLv3.
Basically those willing to use BitcoinSPV for their software are forced to release their source as well, because the whole point is about keeping Bitcoin-related software as transparent as possible to increase both trust and community contributions.
Nothing more is due as long as this rule of thumb is followed, still a note in the credits would be appreciated.
The developer takes no responsibility for lost money or any damage due to BitcoinSPV regular usage or bugs. Use at your own risk.
Twitter: @keeshux
Website: davidederosa.com