|
| 1 | +package org.bitcoindevkit |
| 2 | +import java.io.File |
| 3 | +import java.nio.file.Paths |
| 4 | + |
| 5 | +fun main(){ |
| 6 | + val (descriptor, changeDescriptor) = createDescriptorsFromBip32RootKey( |
| 7 | + ActiveWalletScriptType.P2WPKH, |
| 8 | + Network.REGTEST |
| 9 | + ) |
| 10 | + println("Descriptor: $descriptor") |
| 11 | + println("Change descriptor: $changeDescriptor") |
| 12 | + |
| 13 | + val persistenceFilePath = getPersistenceFilePath() |
| 14 | + println("Persistence file path: $persistenceFilePath") |
| 15 | + |
| 16 | + val connection: Persister = Persister.newSqlite(persistenceFilePath) |
| 17 | + val wallet = Wallet(descriptor, changeDescriptor, Network.REGTEST, connection) |
| 18 | + val changeAddress = wallet.revealNextAddress(KeychainKind.INTERNAL).address |
| 19 | + val address = wallet.revealNextAddress(KeychainKind.EXTERNAL).address |
| 20 | + |
| 21 | + println("Change address: $changeAddress") |
| 22 | + println("Address: $address") |
| 23 | +} |
| 24 | + |
| 25 | +fun createDescriptorsFromBip32RootKey ( |
| 26 | + activeWalletScriptType: ActiveWalletScriptType, |
| 27 | + network: Network) : Array<Descriptor>{ |
| 28 | + val mnemonic = Mnemonic(WordCount.WORDS12) |
| 29 | + val bip32ExtendedRootKey = DescriptorSecretKey(network, mnemonic, null) |
| 30 | + println("Bip32 root key: $bip32ExtendedRootKey") |
| 31 | + |
| 32 | + val descriptor: Descriptor = createScriptAppropriateDescriptor( |
| 33 | + activeWalletScriptType, |
| 34 | + bip32ExtendedRootKey, |
| 35 | + network, |
| 36 | + KeychainKind.EXTERNAL, |
| 37 | + ) |
| 38 | + val changeDescriptor: Descriptor = createScriptAppropriateDescriptor( |
| 39 | + activeWalletScriptType, |
| 40 | + bip32ExtendedRootKey, |
| 41 | + network, |
| 42 | + KeychainKind.INTERNAL, |
| 43 | + ) |
| 44 | + return arrayOf(descriptor, changeDescriptor) |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +fun createScriptAppropriateDescriptor( |
| 49 | + scriptType: ActiveWalletScriptType, |
| 50 | + bip32ExtendedRootKey: DescriptorSecretKey, |
| 51 | + network: Network, |
| 52 | + keychain: KeychainKind, |
| 53 | +): Descriptor { |
| 54 | + return when (scriptType) { |
| 55 | + ActiveWalletScriptType.P2WPKH -> Descriptor.newBip84( |
| 56 | + bip32ExtendedRootKey, |
| 57 | + keychain, |
| 58 | + network |
| 59 | + ) |
| 60 | + ActiveWalletScriptType.P2TR -> Descriptor.newBip86( |
| 61 | + bip32ExtendedRootKey, |
| 62 | + keychain, |
| 63 | + network |
| 64 | + ) |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fun getPersistenceFilePath(): String { |
| 69 | + val currentDirectory = Paths.get("").toAbsolutePath().toString() + "/bdk-jvm/examples/src/main/kotlin/bdk_persistence.sqlite" |
| 70 | + File(currentDirectory).apply { |
| 71 | + if (exists()) delete() |
| 72 | + } |
| 73 | + return currentDirectory |
| 74 | +} |
| 75 | + |
| 76 | +enum class ActiveWalletScriptType { |
| 77 | + P2WPKH, |
| 78 | + P2TR, |
| 79 | +} |
0 commit comments