yenom / BitcoinKit

Bitcoin protocol toolkit for Swift
MIT License
841 stars 261 forks source link

Refactor wallet #228

Closed usatie closed 4 years ago

usatie commented 4 years ago

Description of the Change

The Wallet related classes in this library focus on non-networking things.

Wallet usage

// Creating wallet
let wallet = Wallet.create(passphrase: "BitcoinKit-sample-wallet", network: .mainnet)

// Get receive address
wallet.address

// Get change address
wallet.changeAddress

// Get all the addresses
wallet.addresses

// Increment address index for receive address
wallet.incrementExternalIndex(by: 1)

// Increment address index for change address
wallet.incrementInternalIndex(by: 1)

// Get private keys for the addresses
wallet.privKeys

Plan, Build, and Sign a transaction

Assume you already have unspent transactions with theire keys.

let unspentTransactions: [UnspentTransaction] = ...
let privKeys: [PrivateKey] = ...

And then, Plan, Build and Sign a transaction.

// 1. Plan a transaction
let planner = TransactionPlanner(feePerByte: 1)
let plan = planner.plan(unspentTransactions: unspentTransactions, amount: targetAmount)

// 2. Build an unsigned transaction
let unsignedTx = TransactionBuilder.build(from: plan, toAddress: toAddress, changeAddress: changeAddress)

// 3. Sign the transaction
let sighashHelper = BCHSignatureHashHelper(hashType: .ALL)
let signer = TransactionSigner(unspentTransactions: plan.unspentTransactions, transaction: unsignedTx, sighashHelper: sighashHelper)
let signedTx = signer.sign(with: privKeys)

Benefits

More reliability, testability, and stability.

Possible Drawbacks

Users have to implement networking part on their own. APIs/SPV etc...

Planning to implement such networking features as a separated framework on top of this library.

Applicable issues

closes #143