-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathWallet.kt
More file actions
403 lines (364 loc) · 16.3 KB
/
Wallet.kt
File metadata and controls
403 lines (364 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
* Copyright 2021-2026 thunderbiscuit and contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the ./LICENSE file.
*/
package org.bitcoindevkit.devkitwallet.domain
import android.util.Log
import kotlinx.coroutines.runBlocking
import org.bitcoindevkit.Address
import org.bitcoindevkit.AddressInfo
import org.bitcoindevkit.Amount
import org.bitcoindevkit.BlockId
import org.bitcoindevkit.CanonicalTx
import org.bitcoindevkit.CbfBuilder
import org.bitcoindevkit.CbfClient
import org.bitcoindevkit.ChainPosition
import org.bitcoindevkit.Descriptor
import org.bitcoindevkit.DescriptorSecretKey
import org.bitcoindevkit.FeeRate
import org.bitcoindevkit.IpAddress
import org.bitcoindevkit.KeychainKind
import org.bitcoindevkit.Mnemonic
import org.bitcoindevkit.Network
import org.bitcoindevkit.Peer
import org.bitcoindevkit.Persister
import org.bitcoindevkit.Psbt
import org.bitcoindevkit.ScanType
import org.bitcoindevkit.Script
import org.bitcoindevkit.TxBuilder
import org.bitcoindevkit.Update
import org.bitcoindevkit.WordCount
import org.bitcoindevkit.devkitwallet.data.ActiveWalletScriptType
import org.bitcoindevkit.devkitwallet.data.ConfirmationBlock
import org.bitcoindevkit.devkitwallet.data.NewWalletConfig
import org.bitcoindevkit.devkitwallet.data.RecoverWalletConfig
import org.bitcoindevkit.devkitwallet.data.SingleWallet
import org.bitcoindevkit.devkitwallet.data.Timestamp
import org.bitcoindevkit.devkitwallet.data.TxDetails
import org.bitcoindevkit.devkitwallet.domain.utils.intoDomain
import org.bitcoindevkit.devkitwallet.domain.utils.intoProto
import org.bitcoindevkit.devkitwallet.presentation.viewmodels.mvi.Recipient
import java.util.UUID
import org.bitcoindevkit.Wallet as BdkWallet
private const val TAG = "Wallet"
class Wallet private constructor(
private val wallet: BdkWallet,
private val walletSecrets: WalletSecrets,
private val connection: Persister,
private var fullScanCompleted: Boolean,
private val walletId: String,
private val userPreferencesRepository: UserPreferencesRepository,
private val internalAppFilesPath: String,
blockchainClientsConfig: BlockchainClientsConfig,
) {
private var currentBlockchainClient: BlockchainClient? = blockchainClientsConfig.getClient()
public var kyotoClient: CbfClient? = null
fun getWalletSecrets(): WalletSecrets {
return walletSecrets
}
fun createTransaction(recipientList: List<Recipient>, feeRate: FeeRate, opReturnMsg: String?): Psbt {
// technique 1 for adding a list of recipients to the TxBuilder
// var txBuilder = TxBuilder()
// for (recipient in recipientList) {
// txBuilder = txBuilder.addRecipient(address = recipient.first, amount = recipient.second)
// }
// txBuilder = txBuilder.feeRate(satPerVbyte = fee_rate)
// technique 2 for adding a list of recipients to the TxBuilder
var txBuilder =
recipientList.fold(TxBuilder()) { builder, recipient ->
// val address = Address(recipient.address)
val scriptPubKey: Script = Address(recipient.address, Network.TESTNET).scriptPubkey()
builder.addRecipient(scriptPubKey, Amount.fromSat(recipient.amount))
}
// if (!opReturnMsg.isNullOrEmpty()) {
// txBuilder = txBuilder.addData(opReturnMsg.toByteArray(charset = Charsets.UTF_8).asUByteArray().toList())
// }
return txBuilder.feeRate(feeRate).finish(wallet)
}
// @OptIn(ExperimentalUnsignedTypes::class)
// fun createSendAllTransaction(
// recipient: String,
// feeRate: Float,
// enableRBF: Boolean,
// opReturnMsg: String?
// ): PartiallySignedTransaction {
// val scriptPubkey: Script = Address(recipient).scriptPubkey()
// var txBuilder = TxBuilder()
// .drainWallet()
// .drainTo(scriptPubkey)
// .feeRate(satPerVbyte = feeRate)
//
// if (enableRBF) {
// txBuilder = txBuilder.enableRbf()
// }
// if (!opReturnMsg.isNullOrEmpty()) {
// txBuilder = txBuilder.addData(opReturnMsg.toByteArray(charset = Charsets.UTF_8).asUByteArray().toList())
// }
// return txBuilder.finish(wallet).psbt
// }
// fun createBumpFeeTransaction(txid: String, feeRate: Float): PartiallySignedTransaction {
// return BumpFeeTxBuilder(txid = txid, newFeeRate = feeRate)
// .enableRbf()
// .finish(wallet = wallet)
// }
fun sign(psbt: Psbt): Boolean {
return wallet.sign(psbt)
}
fun broadcast(signedPsbt: Psbt): String {
currentBlockchainClient?.broadcast(signedPsbt.extractTx())
?: throw IllegalStateException("Blockchain client not initialized")
return signedPsbt.extractTx().computeTxid().toString()
}
private fun getAllTransactions(): List<CanonicalTx> = wallet.transactions()
fun getAllTxDetails(): List<TxDetails> {
val transactions = getAllTransactions()
return transactions.map { tx ->
val txid = tx.transaction.computeTxid()
val (sent, received) = wallet.sentAndReceived(tx.transaction)
var feeRate: FeeRate? = null
var fee: Amount? = null
// TODO: I don't know why we're getting negative fees here, but it looks like a bug
try {
fee = wallet.calculateFee(tx.transaction)
} catch (e: Exception) {
Log.e(TAG, "Error calculating fee rate for tx $txid: $e")
}
try {
feeRate = wallet.calculateFeeRate(tx.transaction)
} catch (e: Exception) {
Log.e(TAG, "Error calculating fee for tx $txid: $e")
}
val (confirmationBlock, confirmationTimestamp, pending) =
when (val position = tx.chainPosition) {
is ChainPosition.Unconfirmed -> Triple(null, null, true)
is ChainPosition.Confirmed ->
Triple(
ConfirmationBlock(position.confirmationBlockTime.blockId.height),
Timestamp(position.confirmationBlockTime.confirmationTime),
false,
)
}
TxDetails(
tx.transaction,
txid.toString(),
sent.toSat(),
received.toSat(),
fee?.toSat() ?: 0uL,
feeRate,
pending,
confirmationBlock,
confirmationTimestamp
)
}
}
// fun getTransaction(txid: String): TransactionDetails? {
// val allTransactions = getAllTransactions()
// allTransactions.forEach {
// if (it.txid == txid) {
// return it
// }
// }
// return null
// }
fun getBalance(): ULong = wallet.balance().total.toSat()
fun getNewAddress(): AddressInfo = wallet.revealNextAddress(KeychainKind.EXTERNAL)
fun getLastCheckpoint(): BlockId = wallet.latestCheckpoint()
fun startKyotoNode() {
Log.i(TAG, "Starting Kyoto node")
// val ip: IpAddress = IpAddress.fromIpv4(68u, 47u, 229u, 218u) // Signet
val ip: IpAddress = IpAddress.fromIpv4(10u, 0u, 2u, 2u) // Regtest
val peer1: Peer = Peer(ip, 18444u, false) // Regtest
// val peer1: Peer = Peer(ip, null, false)
val peers: List<Peer> = listOf(peer1)
val (client, node) =
CbfBuilder()
.dataDir(this.internalAppFilesPath)
.peers(peers)
.connections(1u)
.scanType(ScanType.Sync)
.build(this.wallet)
node.run()
kyotoClient = client
Log.i(TAG, "Kyoto node started")
}
suspend fun stopKyotoNode() {
kyotoClient?.shutdown()
}
fun applyUpdate(update: Update) {
wallet.applyUpdate(update)
wallet.persist(connection)
}
companion object {
fun createWallet(
newWalletConfig: NewWalletConfig,
internalAppFilesPath: String,
userPreferencesRepository: UserPreferencesRepository,
): Wallet {
val mnemonic = Mnemonic(WordCount.WORDS12)
val bip32ExtendedRootKey = DescriptorSecretKey(newWalletConfig.network, mnemonic, null)
val descriptor: Descriptor =
createScriptAppropriateDescriptor(
newWalletConfig.scriptType,
bip32ExtendedRootKey,
newWalletConfig.network,
KeychainKind.EXTERNAL,
)
val changeDescriptor: Descriptor =
createScriptAppropriateDescriptor(
newWalletConfig.scriptType,
bip32ExtendedRootKey,
newWalletConfig.network,
KeychainKind.INTERNAL,
)
val walletId = UUID.randomUUID().toString()
val connection = Persister.newSqlite("$internalAppFilesPath/wallet-${walletId.take(8)}.sqlite3")
// Create SingleWallet object for saving to datastore
val newWalletForDatastore: SingleWallet =
SingleWallet
.newBuilder()
.setId(walletId)
.setName(newWalletConfig.name)
.setNetwork(newWalletConfig.network.intoProto())
.setScriptType(ActiveWalletScriptType.P2WPKH)
.setDescriptor(descriptor.toStringWithSecret())
.setChangeDescriptor(changeDescriptor.toStringWithSecret())
.setRecoveryPhrase(mnemonic.toString())
.build()
// TODO: launch this correctly, not on the main thread
// Save the new wallet to the datastore
runBlocking { userPreferencesRepository.updateActiveWallets(newWalletForDatastore) }
val bdkWallet =
BdkWallet(
descriptor = descriptor,
changeDescriptor = changeDescriptor,
network = newWalletConfig.network,
persister = connection,
)
val walletSecrets = WalletSecrets(descriptor, changeDescriptor, mnemonic.toString())
return Wallet(
wallet = bdkWallet,
walletSecrets = walletSecrets,
connection = connection,
fullScanCompleted = false,
walletId = walletId,
userPreferencesRepository = userPreferencesRepository,
internalAppFilesPath = internalAppFilesPath,
blockchainClientsConfig = BlockchainClientsConfig.createDefaultConfig(newWalletConfig.network),
)
}
fun loadActiveWallet(
activeWallet: SingleWallet,
internalAppFilesPath: String,
userPreferencesRepository: UserPreferencesRepository,
): Wallet {
val descriptor = Descriptor(activeWallet.descriptor, activeWallet.network.intoDomain())
val changeDescriptor = Descriptor(activeWallet.changeDescriptor, activeWallet.network.intoDomain())
val connection = Persister.newSqlite("$internalAppFilesPath/wallet-${activeWallet.id.take(8)}.sqlite3")
val bdkWallet =
BdkWallet.load(
descriptor = descriptor,
changeDescriptor = changeDescriptor,
persister = connection,
)
val walletSecrets = WalletSecrets(descriptor, changeDescriptor, activeWallet.recoveryPhrase)
return Wallet(
wallet = bdkWallet,
walletSecrets = walletSecrets,
connection = connection,
fullScanCompleted = activeWallet.fullScanCompleted,
walletId = activeWallet.id,
userPreferencesRepository = userPreferencesRepository,
internalAppFilesPath = internalAppFilesPath,
blockchainClientsConfig = BlockchainClientsConfig.createDefaultConfig(
activeWallet.network.intoDomain()
),
)
}
fun recoverWallet(
recoverWalletConfig: RecoverWalletConfig,
internalAppFilesPath: String,
userPreferencesRepository: UserPreferencesRepository,
): Wallet {
Log.i(TAG, "Recovering wallet with config: $recoverWalletConfig")
var descriptor: Descriptor? = null
var changeDescriptor: Descriptor? = null
var mnemonicString: String = ""
// If there is a recovery phrase, we use it to recover the wallet
if (recoverWalletConfig.recoveryPhrase != null && recoverWalletConfig.scriptType != null) {
val mnemonic: Mnemonic = Mnemonic.fromString(recoverWalletConfig.recoveryPhrase)
mnemonicString = mnemonic.toString()
val bip32ExtendedRootKey = DescriptorSecretKey(recoverWalletConfig.network, mnemonic, null)
descriptor =
createScriptAppropriateDescriptor(
recoverWalletConfig.scriptType,
bip32ExtendedRootKey,
recoverWalletConfig.network,
KeychainKind.EXTERNAL,
)
changeDescriptor =
createScriptAppropriateDescriptor(
recoverWalletConfig.scriptType,
bip32ExtendedRootKey,
recoverWalletConfig.network,
KeychainKind.INTERNAL,
)
} else {
descriptor = recoverWalletConfig.descriptor
changeDescriptor = recoverWalletConfig.changeDescriptor
}
val walletId = UUID.randomUUID().toString()
val connection = Persister.newSqlite("$internalAppFilesPath/wallet-${walletId.take(8)}.sqlite3")
// Create SingleWallet object for saving to datastore
val newWalletForDatastore: SingleWallet =
SingleWallet
.newBuilder()
.setId(walletId)
.setName(recoverWalletConfig.name)
.setNetwork(recoverWalletConfig.network.intoProto())
.setScriptType(recoverWalletConfig.scriptType ?: ActiveWalletScriptType.UNKNOWN)
.setDescriptor(descriptor.toStringWithSecret())
.setChangeDescriptor(changeDescriptor.toStringWithSecret())
.setRecoveryPhrase(mnemonicString)
.build()
// TODO: launch this correctly, not on the main thread
// Save the new wallet to the datastore
runBlocking { userPreferencesRepository.updateActiveWallets(newWalletForDatastore) }
val bdkWallet =
BdkWallet(
descriptor = descriptor,
changeDescriptor = changeDescriptor,
persister = connection,
network = recoverWalletConfig.network,
)
val walletSecrets = WalletSecrets(descriptor, changeDescriptor, mnemonicString)
return Wallet(
wallet = bdkWallet,
walletSecrets = walletSecrets,
connection = connection,
fullScanCompleted = false,
walletId = walletId,
userPreferencesRepository = userPreferencesRepository,
internalAppFilesPath = internalAppFilesPath,
blockchainClientsConfig = BlockchainClientsConfig.createDefaultConfig(recoverWalletConfig.network),
)
}
}
}
fun createScriptAppropriateDescriptor(
scriptType: ActiveWalletScriptType,
bip32ExtendedRootKey: DescriptorSecretKey,
network: Network,
keychain: KeychainKind,
): Descriptor {
return when (scriptType) {
ActiveWalletScriptType.P2WPKH -> Descriptor.newBip84(bip32ExtendedRootKey, keychain, network)
ActiveWalletScriptType.P2TR -> Descriptor.newBip86(bip32ExtendedRootKey, keychain, network)
ActiveWalletScriptType.UNKNOWN -> TODO()
ActiveWalletScriptType.UNRECOGNIZED -> TODO()
}
}
data class WalletSecrets(
val descriptor: Descriptor,
val changeDescriptor: Descriptor,
val recoveryPhrase: String,
)