### Complete Bitcoin RPC Example Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted An end-to-end example demonstrating daemon startup, RPC client initialization, making calls, and clean shutdown. Ensure to call waitUntilStopped() from a detached Task or background queue. ```swift import Bitcoin import Foundation // Demo credentials — username "111", password "222". Regtest only. let auth = RPCAuth( username: "111", salt: "14c1e13a71b7d6a4dab6c9d8f107bb5b", passwordHMAC: "73b9fbbd71dbbb1476efa6da7b37dde5111153a17ccb5fdef79537d276fd03d4" ) let dataDirectory = URL.temporaryDirectory.appending(path: "bitcoin-regtest") try FileManager.default.createDirectory(at: dataDirectory, withIntermediateDirectories: true) let config = BitcoinConfig .regtest() .rpcAuth(auth) .server() .dataDir(dataDirectory.path(percentEncoded: false)) try Daemon.start(with: config) let cookieFile = dataDirectory.appending(path: "regtest/.cookie") try await Daemon.bootstrap(cookieFile: cookieFile, port: 18443) let client = RPCClient( url: URL(string: "http://127.0.0.1:18443")!, username: "111", password: "222" ) let info: BlockchainInfo = try await client.getBlockchainInfo() print("Chain: \(info.chain)") print("Blocks: \(info.blocks)") _ = try await client.stop() Daemon.waitUntilStopped() ``` -------------------------------- ### Start Bitcoin Daemon Source: https://docs.21.dev/data/documentation/bitcoin/daemon Starts the `bitcoind` process with specified arguments. Ensure the daemon is not already running. ```swift Daemon.start(["-regtest", "-server"]) ``` -------------------------------- ### Start the Embedded Bitcoin Daemon Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Start the bitcoind daemon on a detached thread using the provided configuration. The call returns immediately. A thrown ConfigError indicates no daemon process was started. ```swift try Daemon.start(with: config) ``` -------------------------------- ### Configure and Start Embedded Bitcoin Daemon Source: https://docs.21.dev/data/documentation/bitcoin This snippet demonstrates how to configure a regtest node, set RPC authentication, and start the embedded Bitcoin Core daemon. It then creates an RPC client to query blockchain information. ```swift import Bitcoin // Configure a regtest node let auth = RPCAuth(username: "user", salt: "abc", passwordHMAC: "def") let config = BitcoinConfig.regtest().rpcAuth(auth).server() // Start the embedded daemon try Daemon.start(with: config) // Create an RPC client let client = RPCClient( url: URL(string: "http://127.0.0.1:18443")!, username: "user", password: "pass" ) // Query the blockchain let info = try await client.getBlockchainInfo() print("Chain: \(info.chain), Height: \(info.blocks)") ``` -------------------------------- ### Create Mainnet BitcoinConfig Source: https://docs.21.dev/data/documentation/bitcoin/bitcoinconfig Instantiates a BitcoinConfig for the mainnet. Use this factory method to start building configurations for the Bitcoin main network. ```swift BitcoinConfig.mainnet() ``` -------------------------------- ### Create Regtest BitcoinConfig Source: https://docs.21.dev/data/documentation/bitcoin/bitcoinconfig Instantiates a BitcoinConfig for the regtest network. Use this factory method to start building configurations for the Bitcoin regtest environment. ```swift BitcoinConfig.regtest() ``` -------------------------------- ### Build a Validated Bitcoin Configuration Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Use BitcoinConfig to assemble a network-aware, validated configuration. Start with a network factory method, then chain options. The data directory must exist before startup. ```swift import Bitcoin import Foundation // Demo credentials — username "111", password "222". // `passwordHMAC` is the hex HMAC-SHA256 of the password keyed by the salt. // Generate your own with Bitcoin Core's helper: // python3 share/rpcauth/rpcauth.py let auth = RPCAuth( username: "111", salt: "14c1e13a71b7d6a4dab6c9d8f107bb5b", passwordHMAC: "73b9fbbd71dbbb1476efa6da7b37dde5111153a17ccb5fdef79537d276fd03d4" ) let dataDirectory = URL.temporaryDirectory.appending(path: "bitcoin-regtest") try FileManager.default.createDirectory(at: dataDirectory, withIntermediateDirectories: true) let config = BitcoinConfig .regtest() .rpcAuth(auth) .server() .dataDir(dataDirectory.path(percentEncoded: false)) ``` -------------------------------- ### Daemon Lifecycle Management Source: https://docs.21.dev/data/documentation/bitcoin/llms.txt The Daemon class manages the lifecycle of an embedded `bitcoind` instance, providing methods to bootstrap and start the daemon. ```APIDOC ## Daemon ### Description Manages the lifecycle of an embedded `bitcoind` instance. ### Methods - `bootstrap(cookiefile:port:timeout:)` - **Description**: Bootstraps the `bitcoind` daemon using a cookie file for authentication. - **Parameters**: - `cookiefile` (string) - Path to the cookie authentication file. - `port` (integer) - The port to connect to. - `timeout` (integer) - The connection timeout in seconds. - `bootstrap(url:username:password:timeout:)` - **Description**: Bootstraps the `bitcoind` daemon using provided credentials. - **Parameters**: - `url` (string) - The URL of the `bitcoind` RPC endpoint. - `username` (string) - The username for authentication. - `password` (string) - The password for authentication. - `timeout` (integer) - The connection timeout in seconds. - `start(with:)` - **Description**: Starts the `bitcoind` daemon. - **Parameters**: - `with` (BitcoinConfig) - Configuration options for starting the daemon. ``` -------------------------------- ### Instantiate and Use BTCAmount Source: https://docs.21.dev/data/documentation/bitcoin/btcamount Demonstrates how to create a BTCAmount from satoshis and access its BTC and satoshi values. Also shows creating an amount from BTC decimal. ```swift let amount = BTCAmount(satoshis: 100_000_000) // 1 BTC print(amount.btc) // 1 print(amount) // "1 BTC" let fee = BTCAmount(btc: Decimal(string: "0.0001")!) print(fee.satoshis) // 10000 ``` -------------------------------- ### Initialize RPCClient Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Construct an RPCClient with the daemon's URL and credentials. This initializer sets up an auto-detecting transport. ```swift let client = RPCClient( url: URL(string: "http://127.0.0.1:18443")!, username: "111", password: "222" ) ``` -------------------------------- ### createwallet Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Creates a new wallet. This command initializes a new wallet with specified options. ```APIDOC ## POST /bitcoin/rpcclient/createwallet ### Description Creates a new wallet. This command initializes a new wallet with specified options. ### Method POST ### Endpoint /bitcoin/rpcclient/createwallet ### Parameters #### Query Parameters - **name** (string) - Required - The name of the new wallet. - **disableprivatekeys** (boolean) - Optional - Whether to disable private keys. Defaults to false. - **blank** (boolean) - Optional - Whether to create a blank wallet (no seed). Defaults to false. - **passphrase** (string) - Optional - The passphrase to encrypt the wallet with. - **avoidreuse** (boolean) - Optional - Whether to avoid reusing addresses. Defaults to false. - **descriptors** (boolean) - Optional - Whether to enable descriptor wallets. Defaults to false. - **loadonstartup** (boolean) - Optional - Whether to load the wallet on startup. Defaults to false. ### Request Example ```json { "name": "my_new_wallet", "disableprivatekeys": false, "blank": false, "passphrase": "my_secure_passphrase", "descriptors": true, "loadonstartup": true } ``` ### Response #### Success Response (200) - **result** (object) - An object confirming the wallet creation. - **name** (string) - The name of the created wallet. - **warning** (string) - Any warnings generated during wallet creation. #### Response Example ```json { "result": { "name": "my_new_wallet", "warning": "" } } ``` ``` -------------------------------- ### Creating and Using UnixTimestamp Source: https://docs.21.dev/data/documentation/bitcoin/unixtimestamp Demonstrates how to create a UnixTimestamp from seconds and access its Date and ISO 8601 formatted string representation. ```swift let ts = UnixTimestamp(seconds: 1_700_000_000) print(ts.date) // 2023-11-14 22:13:20 +0000 print(ts.description) // ISO 8601 formatted string ``` -------------------------------- ### LoggingConnection Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Establishes a subscription to the kernel's internal logging stream. ```APIDOC ## LoggingConnection ### Description Subscription to the kernel's internal logging stream. ``` -------------------------------- ### Bootstrap the Direct RPC Bridge Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Bootstrap the direct RPC bridge by calling `bootstrap(cookieFile:port:timeout:)` before issuing any RPCClient requests. This enables in-process dispatch for non-wallet RPCs. ```swift // Same `dataDirectory` passed to `.dataDir()` above. let cookieFile = dataDirectory.appending(path: "regtest/.cookie") try await Daemon.bootstrap(cookieFile: cookieFile, port: 18443) ``` -------------------------------- ### RPCClient Initialization Source: https://docs.21.dev/data/documentation/bitcoin/rpcclient Initializes the RPCClient. Transport selection can be explicit or automatic, falling back to HTTP if the direct bridge is not available. ```APIDOC ## `init(transport:)` ### Description Initializes the RPCClient with an explicit transport. ### Parameters #### Path Parameters - **transport** (RPCClientTransport) - Required - The transport to use for communication. ## `init(url:username:password:)` ### Description Initializes the RPCClient with a URL, username, and password. Automatically selects the transport, preferring the direct bridge if available. ### Parameters #### Path Parameters - **url** (URL) - Required - The URL of the Bitcoin node. - **username** (String) - Required - The username for authentication. - **password** (String) - Required - The password for authentication. ``` -------------------------------- ### Bootstrap Direct RPC Bridge (Cookie Auth) Source: https://docs.21.dev/data/documentation/bitcoin/daemon Bootstraps the direct RPC bridge using cookie authentication. Requires the path to the `.cookie` file and the RPC port. Ensure the cookie file exists and is accessible. ```swift let cookieFile = dataDir.appending(path: ".cookie") try await Daemon.bootstrap(cookieFile: cookieFile, port: 18443) ``` -------------------------------- ### RPCClient Methods Source: https://docs.21.dev/data/documentation/bitcoin/llms.txt The RPCClient class provides methods to interact with the Bitcoin Core JSON-RPC API. These methods allow for calling arbitrary RPC commands, sending commands that expect a result, sending commands that do not expect a result, and sending commands that may return null. ```APIDOC ## RPCClient ### Description Provides methods to interact with the Bitcoin Core JSON-RPC API. ### Methods - `call(_:params:)` - **Description**: Calls an arbitrary RPC command. - **Parameters**: - `_` (string) - The RPC command name. - `params` (array) - An array of parameters for the RPC command. - `send(_:params:)` - **Description**: Sends an RPC command and expects a result. - **Parameters**: - `_` (string) - The RPC command name. - `params` (array) - An array of parameters for the RPC command. - `sendVoid(_:params:)` - **Description**: Sends an RPC command that does not expect a result. - **Parameters**: - `_` (string) - The RPC command name. - `params` (array) - An array of parameters for the RPC command. - `sendNullable(_:params:)` - **Description**: Sends an RPC command that may return null. - **Parameters**: - `_` (string) - The RPC command name. - `params` (array) - An array of parameters for the RPC command. - `submitBlock(hexdata:)` - **Description**: Submits a block to the network. - **Parameters**: - `hexdata` (string) - The block data in hexadecimal format. - `scantxoutset(descriptors:)` - **Description**: Scans the transaction output set. - **Parameters**: - `descriptors` (array) - An array of descriptors to scan for. ``` -------------------------------- ### Bootstrap Direct RPC Bridge (Explicit Credentials) Source: https://docs.21.dev/data/documentation/bitcoin/daemon Bootstraps the direct RPC bridge using explicit username and password credentials. Requires a valid RPC URL, username, and password. Ensure the provided credentials and URL are correct. ```swift try await Daemon.bootstrap( url: URL(string: "http://127.0.0.1:8332")!, username: "user", password: "pass" ) ``` -------------------------------- ### Add Bitcoin Product with Swift Package Manager Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Add the Bitcoin package and depend on the Bitcoin product from your target in Package.swift. Ensure C++ interoperability is enabled for the dependent target. ```swift // Package.swift dependencies: [ .package( url: "https://github.com/21-DOT-DEV/swift-bitcoinkernel.git", branch: "main" ), ], targets: [ .target( name: "MyBitcoinApp", dependencies: [ .product(name: "Bitcoin", package: "swift-bitcoinkernel"), ], swiftSettings: [ .interoperabilityMode(.Cxx), ] ) ] ``` -------------------------------- ### dumptxoutset Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Dumps the UTXO set to a file. This command is useful for creating a backup or snapshot of the current unspent transaction output set. ```APIDOC ## POST /bitcoin/rpcclient/dumptxoutset ### Description Dumps the UTXO set to a file. This command is useful for creating a backup or snapshot of the current unspent transaction output set. ### Method POST ### Endpoint /bitcoin/rpcclient/dumptxoutset ### Parameters #### Query Parameters - **filepath** (string) - Required - The path to the file where the UTXO set will be dumped. ### Request Example ```json { "filepath": "/path/to/utxo_set.dat" } ``` ### Response #### Success Response (200) - **result** (object) - An object containing information about the dumped UTXO set. - **height** (integer) - The block height at which the UTXO set was dumped. - **hash** (string) - The hash of the UTXO set. - **txouts** (integer) - The number of UTXOs dumped. - **bytes** (integer) - The size of the dumped file in bytes. #### Response Example ```json { "result": { "height": 789000, "hash": "...", "txouts": 1000000, "bytes": 50000000 } } ``` ``` -------------------------------- ### backupwallet Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Backs up the wallet to a specified destination file. This is a crucial operation for ensuring the safety of your Bitcoin funds. ```APIDOC ## POST /bitcoin/rpcclient/backupwallet ### Description Backs up the wallet to a specified destination file. This is a crucial operation for ensuring the safety of your Bitcoin funds. ### Method POST ### Endpoint /bitcoin/rpcclient/backupwallet ### Parameters #### Query Parameters - **wallet** (string) - Optional - The name of the wallet to backup. Defaults to the default wallet. - **destination** (string) - Required - The path to the destination file where the wallet backup will be saved. ### Request Example ```json { "destination": "/path/to/backup/wallet.dat" } ``` ### Response #### Success Response (200) - **result** (string) - A message indicating the success of the wallet backup operation. #### Response Example ```json { "result": "Wallet backup successful to /path/to/backup/wallet.dat" } ``` ``` -------------------------------- ### BTCAmount Initialization Source: https://docs.21.dev/data/documentation/bitcoin/llms.txt The BTCAmount struct represents a Bitcoin amount with satoshi storage and BTC-decimal coding, providing an initializer for creating amounts from BTC values. ```APIDOC ## BTCAmount ### Description Bitcoin amount with satoshi storage and BTC-decimal coding. ### Methods - `init(btc:)` - **Description**: Initializes a BTCAmount from a BTC value. - **Parameters**: - `btc` (Decimal) - The amount in BTC. ``` -------------------------------- ### BitcoinConfig CLI Argument Builder Source: https://docs.21.dev/data/documentation/bitcoin/llms.txt The BitcoinConfig class provides a fluent interface for building command-line arguments for Bitcoin Core. ```APIDOC ## BitcoinConfig ### Description Fluent CLI argument builder for Bitcoin Core. ### Methods - `testnet()` - **Description**: Configures the daemon to run on the testnet. - `prune(_:)` - **Description**: Enables pruning of the blockchain data. - **Parameters**: - `_` (integer) - The target size in MB for pruned data. - `validate()` - **Description**: Validates the blockchain data. ``` -------------------------------- ### Context Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt The root object for every validation operation, representing the Kernel runtime context. Key methods are `init(options:)` and `interrupt()`. ```APIDOC ## Context ### Description Kernel runtime context; root object for every validation operation. ### Methods - `init(options:)` - `interrupt()` ``` -------------------------------- ### ContextOptions Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Configuration options for the Context. Allows setting chain parameters, notifications, and validation interfaces. Methods include `setChainParams(_:)`, `setNotifications(_:)`, and `setValidationInterface(_:)`. ```APIDOC ## ContextOptions ### Description Context configuration. ### Methods - `setChainParams(_:)` - `setNotifications(_:)` - `setValidationInterface(_:)` ``` -------------------------------- ### ScriptPubkey Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Represents an output locking script. ```APIDOC ## ScriptPubkey ### Description Output locking script. ``` -------------------------------- ### createwalletdescriptor Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Creates a wallet descriptor. This command is used to generate a descriptor for a wallet, which can be used for various purposes like address derivation. ```APIDOC ## POST /bitcoin/rpcclient/createwalletdescriptor ### Description Creates a wallet descriptor. This command is used to generate a descriptor for a wallet, which can be used for various purposes like address derivation. ### Method POST ### Endpoint /bitcoin/rpcclient/createwalletdescriptor ### Parameters #### Query Parameters - **wallet** (string) - Optional - The name of the wallet. Defaults to the default wallet. - **addresstype** (string) - Optional - The type of address to generate ('legacy', 'p2sh-segwit', 'bech32'). Defaults to 'bech32'. - **options** (object) - Optional - An object containing options for descriptor creation. - **mnemonic** (string) - Optional - The mnemonic phrase for the wallet. - **passphrase** (string) - Optional - The passphrase for the wallet. - **seed_creation_time** (integer) - Optional - The timestamp for seed creation. - **descriptors** (boolean) - Optional - Whether to enable descriptor wallets. Defaults to false. ### Request Example ```json { "wallet": "my_wallet", "addresstype": "bech32", "options": { "descriptors": true } } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the wallet descriptor details. - **descriptor** (string) - The generated wallet descriptor. - **success** (boolean) - Indicates if the descriptor was created successfully. #### Response Example ```json { "result": { "descriptor": "wpkh(...)#...", "success": true } } ``` ``` -------------------------------- ### estimatesmartfee Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Estimates a smart fee for transactions. This command provides a fee recommendation based on network congestion and desired confirmation time. ```APIDOC ## POST /bitcoin/rpcclient/estimatesmartfee ### Description Estimates a smart fee for transactions. This command provides a fee recommendation based on network congestion and desired confirmation time. ### Method POST ### Endpoint /bitcoin/rpcclient/estimatesmartfee ### Parameters #### Query Parameters - **conftarget** (integer) - Required - The confirmation target in blocks. - **mode** (string) - Optional - The mode for fee estimation (' ECONOMICAL', 'CONSERVATIVE'). Defaults to 'CONSERVATIVE'. ### Request Example ```json { "conftarget": 6, "mode": "ECONOMICAL" } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the smart fee estimation. - **feerate** (number) - The estimated fee rate in BTC/kvB. - **blocks** (integer) - The number of blocks the fee rate is estimated for. - **errors** (array) - An array of errors encountered during estimation, if any. #### Response Example ```json { "result": { "feerate": 0.00004, "blocks": 6, "errors": [] } } ``` ``` -------------------------------- ### Make a Typed RPC Call Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Issue a typed RPC call to the running daemon, such as getBlockchainInfo. Ensure your credentials match the daemon's configuration. ```swift let info: BlockchainInfo = try await client.getBlockchainInfo() print("Chain: \(info.chain)") // regtest print("Blocks: \(info.blocks)") // 0 ``` -------------------------------- ### ChainstateManagerOptions Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Configuration options for ChainstateManager. Allows setting worker threads and wiping specific databases. Methods include `init(context:datadirectory:blocksdirectory:)`, `setWorkerThreads(_:)`, and `setWipeDBs(blocktreedb:chainstatedb:)`. ```APIDOC ## ChainstateManagerOptions ### Description Configuration options for ChainstateManager. ### Methods - `init(context:datadirectory:blocksdirectory:)` - `setWorkerThreads(_:)` - `setWipeDBs(blocktreedb:chainstatedb:)` ``` -------------------------------- ### getaddressinfo Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Returns information about a specific Bitcoin address. This command provides details such as the address type, script, and whether it's associated with the wallet. ```APIDOC ## POST /bitcoin/rpcclient/getaddressinfo ### Description Returns information about a specific Bitcoin address. This command provides details such as the address type, script, and whether it's associated with the wallet. ### Method POST ### Endpoint /bitcoin/rpcclient/getaddressinfo ### Parameters #### Query Parameters - **wallet** (string) - Optional - The name of the wallet to check against. Defaults to the default wallet. - **address** (string) - Required - The Bitcoin address to query. ### Request Example ```json { "address": "bitcoin_address" } ``` ### Response #### Success Response (200) - **result** (object) - An object containing information about the address. - **address** (string) - The Bitcoin address. - **scriptPubKey** (string) - The script public key associated with the address. - **ismine** (boolean) - Whether the address belongs to the wallet. - **isscript** (boolean) - Whether the address is a script address. - **iswitness** (boolean) - Whether the address is a witness address. - **witness_version** (integer) - The witness version if it's a witness address. - **pubkey** (string) - The public key if available. - **label** (string) - The label associated with the address. #### Response Example ```json { "result": { "address": "1...", "scriptPubKey": "...", "ismine": true, "isscript": false, "iswitness": false, "label": "my_address" } } ``` ``` -------------------------------- ### createmultisig Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Creates a multi-signature address. This command is used to generate a P2SH or P2WSH address that requires multiple signatures to spend funds. ```APIDOC ## POST /bitcoin/rpcclient/createmultisig ### Description Creates a multi-signature address. This command is used to generate a P2SH or P2WSH address that requires multiple signatures to spend funds. ### Method POST ### Endpoint /bitcoin/rpcclient/createmultisig ### Parameters #### Query Parameters - **nrequired** (integer) - Required - The number of signatures required to spend funds. - **keys** (array) - Required - An array of public keys or addresses involved in the multi-signature setup. - **addresstype** (string) - Optional - The type of address to create ('legacy', 'p2sh-segwit', 'bech32'). Defaults to 'legacy'. ### Request Example ```json { "nrequired": 2, "keys": [ "pubkey1", "pubkey2", "pubkey3" ], "addresstype": "p2sh-segwit" } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the multi-signature address details. - **address** (string) - The generated multi-signature address. - **redeemScript** (string) - The redeem script for the multi-signature address (if applicable). - **scriptPubKey** (string) - The script public key for the multi-signature address. #### Response Example ```json { "result": { "address": "3...", "redeemScript": "...", "scriptPubKey": "..." } } ``` ``` -------------------------------- ### Warning Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt An enumeration of possible warnings issued by the kernel. ```APIDOC ## Warning ### Description Kernel warning enumeration. ``` -------------------------------- ### generatetoaddress Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Generate blocks up to a specified address. This command is used for mining blocks and sending the rewards to a given address. ```APIDOC ## POST /bitcoin/rpcclient/generatetoaddress ### Description Generate blocks up to a specified address. This command is used for mining blocks and sending the rewards to a given address. ### Method POST ### Endpoint /bitcoin/rpcclient/generatetoaddress ### Parameters #### Query Parameters - **nblocks** (integer) - Required - The number of blocks to generate. - **address** (string) - Required - The address to send the block rewards to. - **maxtries** (integer) - Optional - The maximum number of nonce tries per block. Defaults to 1000000. ### Request Example ```json { "nblocks": 5, "address": "mining_address" } ``` ### Response #### Success Response (200) - **result** (array) - An array of block hashes that were generated. #### Response Example ```json { "result": [ "block_hash_1", "block_hash_2" ] } ``` ``` -------------------------------- ### EsploraBlockSource Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt A block source that connects to any Esplora-compatible HTTP endpoint. Provides methods like `bestTip()`, `block(for:)`, `blockHash(atHeight:)`, and `blockHeader(for:)`. ```APIDOC ## EsploraBlockSource ### Description Block source backed by any Esplora-compatible HTTP endpoint. ### Methods - `bestTip()` - `block(for:)` - `blockHash(atHeight:)` - `blockHeader(for:)` ``` -------------------------------- ### ChainstateManager Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Validates blocks, maintains the block index and UTXO set, and exposes the active chain. Key methods include `processBlock(_:)`, `processBlockHeader(_:state:)`, `importBlocks(from:)`, `readBlock(at:)`, `readBlockSpentOutputs(at:)`, `blockTreeEntry(byHash:)`, `bestEntry`, and `activeChain`. ```APIDOC ## ChainstateManager ### Description Validates blocks, maintains the block index and UTXO set, and exposes the active chain. ### Methods - `processBlock(_:)` - `processBlockHeader(_:state:)` - `importBlocks(from:)` - `readBlock(at:)` - `readBlockSpentOutputs(at:)` - `blockTreeEntry(byHash:)` - `bestEntry` - `activeChain` ``` -------------------------------- ### WalletInfo Structure Definition Source: https://docs.21.dev/data/documentation/bitcoin/walletinfo Defines the structure for WalletInfo, used to represent wallet state information from `getwalletinfo`. ```swift struct WalletInfo ``` -------------------------------- ### BlockHeader Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Represents the 80-byte block header, containing proof-of-work commitment fields. ```APIDOC ## BlockHeader ### Description 80-byte block header — proof-of-work commitment fields. ``` -------------------------------- ### ChainParameters Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Defines consensus rules, genesis block, subsidy schedule, and soft-fork activation heights for various Bitcoin networks (mainnet, testnet, signet, regtest). ```APIDOC ## ChainParameters ### Description Consensus rules, genesis block, subsidy schedule, and soft-fork activation heights for mainnet/testnet/signet/regtest. ``` -------------------------------- ### RPCClient Class Definition Source: https://docs.21.dev/data/documentation/bitcoin/rpcclient Defines the RPCClient class, which serves as the primary interface for interacting with the Bitcoin JSON-RPC API. ```swift final class RPCClient ``` -------------------------------- ### createpsbt Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Creates a Partially Signed Bitcoin Transaction (PSBT). This command is used to construct a new transaction that can be signed later. ```APIDOC ## POST /bitcoin/rpcclient/createpsbt ### Description Creates a Partially Signed Bitcoin Transaction (PSBT). This command is used to construct a new transaction that can be signed later. ### Method POST ### Endpoint /bitcoin/rpcclient/createpsbt ### Parameters #### Query Parameters - **inputs** (array) - Optional - An array of input objects specifying UTXOs to spend. - **txid** (string) - Required - The transaction ID of the UTXO. - **vout** (integer) - Required - The output index of the UTXO. - **sequence** (integer) - Optional - The sequence number for the input. - **outputs** (object) - Optional - An object specifying the outputs of the transaction. - **address** (string) - Required - The recipient address. - **amount** (number) - Required - The amount to send. - **locktime** (integer) - Optional - The locktime for the transaction. Defaults to 0. - **replaceable** (boolean) - Optional - Whether the transaction is replaceable (RBF). Defaults to true. ### Request Example ```json { "inputs": [ { "txid": "previous_txid", "vout": 0 } ], "outputs": { "recipient_address": 0.0001 }, "locktime": 0, "replaceable": true } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the created PSBT. - **psbt** (string) - The Base64-encoded PSBT. #### Response Example ```json { "result": { "psbt": "paste_base64_encoded_psbt_here" } } ``` ``` -------------------------------- ### generateblock Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Generates a block. This command is used for mining a new block with specified coinbase output and transactions. ```APIDOC ## POST /bitcoin/rpcclient/generateblock ### Description Generates a block. This command is used for mining a new block with specified coinbase output and transactions. ### Method POST ### Endpoint /bitcoin/rpcclient/generateblock ### Parameters #### Query Parameters - **output** (string) - Optional - The address to send the block subsidy and transaction fees to. If not specified, the default address is used. - **transactions** (array) - Optional - An array of hexadecimal transaction strings to include in the block. ### Request Example ```json { "output": "mining_address", "transactions": [ "hex_transaction_1", "hex_transaction_2" ] } ``` ### Response #### Success Response (200) - **result** (string) - The hash of the newly generated block. #### Response Example ```json { "result": "new_block_hash" } ``` ``` -------------------------------- ### encryptwallet Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Encrypts the wallet with a passphrase. This command protects your wallet by requiring a passphrase for access. ```APIDOC ## POST /bitcoin/rpcclient/encryptwallet ### Description Encrypts the wallet with a passphrase. This command protects your wallet by requiring a passphrase for access. ### Method POST ### Endpoint /bitcoin/rpcclient/encryptwallet ### Parameters #### Query Parameters - **wallet** (string) - Optional - The name of the wallet to encrypt. Defaults to the default wallet. - **passphrase** (string) - Required - The passphrase to encrypt the wallet with. ### Request Example ```json { "passphrase": "my_secure_passphrase" } ``` ### Response #### Success Response (200) - **result** (string) - A message indicating the success of the wallet encryption. #### Response Example ```json { "result": "Wallet encrypted successfully." } ``` ``` -------------------------------- ### call Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Calls an arbitrary RPC method on the Bitcoin node. This is a general-purpose method for executing any available RPC command. ```APIDOC ## POST /bitcoin/rpcclient/call ### Description Calls an arbitrary RPC method on the Bitcoin node. This is a general-purpose method for executing any available RPC command. ### Method POST ### Endpoint /bitcoin/rpcclient/call ### Parameters #### Query Parameters - **method** (string) - Required - The name of the RPC method to call. - **params** (array) - Optional - An array of parameters to pass to the RPC method. ### Request Example ```json { "method": "getblockchaininfo", "params": [] } ``` ### Response #### Success Response (200) - **result** (any) - The result returned by the RPC method. #### Response Example ```json { "result": { "chain": "main", "blocks": 789000, "headers": 789000, "bestblockhash": "0000000000000000000abc...", "difficulty": 12345678901234567890, "time": 1678886400, "median_time": 1678886000, "verificationprogress": 0.9999999999999999, "chainwork": "0000000000000000000abc...", "pruned": false, "softforks": { ... }, "bip9_softforks": { ... }, "warnings": "" } } ``` ``` -------------------------------- ### TransactionOutput Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Represents a single transaction output, specifying the value and the scriptPubkey. ```APIDOC ## TransactionOutput ### Description Single transaction output — value, scriptPubkey. ``` -------------------------------- ### SynchronizationState Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Represents the various states of chain synchronization progress. ```APIDOC ## SynchronizationState ### Description Chain sync progress states. ``` -------------------------------- ### BTCAmount Structure Definition Source: https://docs.21.dev/data/documentation/bitcoin/btcamount Defines the BTCAmount structure for representing Bitcoin amounts. ```swift struct BTCAmount ``` -------------------------------- ### Chain Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Provides a view of the active chain, with a method `entry(atHeight:)` to retrieve chain entries by height. ```APIDOC ## Chain ### Description Active chain view. ### Methods - `entry(atHeight:)` ``` -------------------------------- ### getaddednodeinfo Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Returns information about nodes that have been added to the node list. This command provides details about manually added peers. ```APIDOC ## POST /bitcoin/rpcclient/getaddednodeinfo ### Description Returns information about nodes that have been added to the node list. This command provides details about manually added peers. ### Method POST ### Endpoint /bitcoin/rpcclient/getaddednodeinfo ### Parameters #### Query Parameters - **node** (string) - Optional - If provided, only return information about this specific node. Otherwise, return information for all added nodes. ### Request Example ```json { "node": "192.168.1.100:8333" } ``` ### Response #### Success Response (200) - **result** (array) - An array of objects, where each object contains information about an added node. - **addednode** (string) - The network address of the added node. - **connected** (boolean) - Whether the client is currently connected to the node. - **addresses** (array) - An array of network addresses associated with the node. #### Response Example ```json { "result": [ { "addednode": "192.168.1.100:8333", "connected": true, "addresses": [ { "address": "192.168.1.100:8333", "connected": "inbound" } ] } ] } ``` ``` -------------------------------- ### RPC Categories Source: https://docs.21.dev/data/documentation/bitcoin/rpcclient RPC methods are organized into extensions based on Bitcoin Core's RPC categories. ```APIDOC ## RPC Method Categories RPC methods are organized into extensions that correspond to Bitcoin Core's RPC categories: - **Blockchain RPCs**: `RPCClient+Blockchain.swift` - **Control RPCs**: `RPCClient+Control.swift` - **Generating RPCs**: `RPCClient+Generating.swift` - **Mining RPCs**: `RPCClient+Mining.swift` - **Raw Transactions RPCs**: `RPCClient+RawTransactions.swift` - **Util RPCs**: `RPCClient+Util.swift` - **Network RPCs**: `RPCClient+Network.swift` - **Wallet RPCs**: `RPCClient+Wallet.swift` This structure covers all RPCs for Bitcoin Core v31.x. ``` -------------------------------- ### analyzepsbt Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Analyzes a Partially Signed Bitcoin Transaction (PSBT). This command provides detailed information about the inputs, outputs, and other fields within a PSBT. ```APIDOC ## POST /bitcoin/rpcclient/analyzepsbt ### Description Analyzes a Partially Signed Bitcoin Transaction (PSBT). This command provides detailed information about the inputs, outputs, and other fields within a PSBT. ### Method POST ### Endpoint /bitcoin/rpcclient/analyzepsbt ### Parameters #### Query Parameters - **psbt** (string) - Required - The Base64-encoded PSBT string. ### Request Example ```json { "psbt": "paste_base64_encoded_psbt_here" } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the analysis of the PSBT, including details about inputs, outputs, and overall validity. #### Response Example ```json { "result": { "description": "Analyzed PSBT details...", "error": null, "inputs": [...], "outputs": [...] } } ``` ``` -------------------------------- ### PeerInfo Structure Definition Source: https://docs.21.dev/data/documentation/bitcoin/peerinfo Defines the basic structure of PeerInfo in Bitcoin Core. ```c++ struct PeerInfo ``` -------------------------------- ### NotificationCallbacks Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt Defines callbacks for block and chain events. ```APIDOC ## NotificationCallbacks ### Description Block- and chain-event callbacks. ``` -------------------------------- ### BitcoinConfig Structure Definition Source: https://docs.21.dev/data/documentation/bitcoin/bitcoinconfig Defines the BitcoinConfig structure, which acts as a type-safe, fluent builder for Bitcoin Core CLI arguments. It uses phantom typing to infer the network type. ```swift struct BitcoinConfig where N : BitcoinNetwork ``` -------------------------------- ### RPCParam Source: https://docs.21.dev/data/documentation/bitcoin/llms.txt RPCParam is a typed wrapper for JSON-RPC parameters, designed to handle heterogeneous parameter lists. ```APIDOC ## RPCParam ### Description Typed JSON-RPC parameter wrapper for heterogeneous parameter lists. ``` -------------------------------- ### createrawtransaction Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Creates a raw transaction spending inputs to outputs. This command is used to construct a transaction without signing it. ```APIDOC ## POST /bitcoin/rpcclient/createrawtransaction ### Description Creates a raw transaction spending inputs to outputs. This command is used to construct a transaction without signing it. ### Method POST ### Endpoint /bitcoin/rpcclient/createrawtransaction ### Parameters #### Query Parameters - **inputs** (array) - Required - An array of input objects specifying UTXOs to spend. - **txid** (string) - Required - The transaction ID of the UTXO. - **vout** (integer) - Required - The output index of the UTXO. - **sequence** (integer) - Optional - The sequence number for the input. - **outputs** (object) - Required - An object specifying the outputs of the transaction. - **address** (string) - Required - The recipient address. - **amount** (number) - Required - The amount to send. - **locktime** (integer) - Optional - The locktime for the transaction. Defaults to 0. - **replaceable** (boolean) - Optional - Whether the transaction is replaceable (RBF). Defaults to true. ### Request Example ```json { "inputs": [ { "txid": "previous_txid", "vout": 0 } ], "outputs": { "recipient_address": 0.0001 }, "locktime": 0, "replaceable": true } ``` ### Response #### Success Response (200) - **result** (string) - The raw hexadecimal transaction string. #### Response Example ```json { "result": "raw_hex_transaction" } ``` ``` -------------------------------- ### generatetodescriptor Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Generate blocks up to a specified descriptor. This command is used for mining blocks and sending the rewards to addresses derived from a descriptor. ```APIDOC ## POST /bitcoin/rpcclient/generatetodescriptor ### Description Generate blocks up to a specified descriptor. This command is used for mining blocks and sending the rewards to addresses derived from a descriptor. ### Method POST ### Endpoint /bitcoin/rpcclient/generatetodescriptor ### Parameters #### Query Parameters - **nblocks** (integer) - Required - The number of blocks to generate. - **descriptor** (string) - Required - The wallet descriptor to derive addresses from. - **maxtries** (integer) - Optional - The maximum number of nonce tries per block. Defaults to 1000000. ### Request Example ```json { "nblocks": 5, "descriptor": "wpkh(02.../0/*)" } ``` ### Response #### Success Response (200) - **result** (array) - An array of block hashes that were generated. #### Response Example ```json { "result": [ "block_hash_1", "block_hash_2" ] } ``` ``` -------------------------------- ### deriveaddresses Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Derives addresses from a descriptor. This command generates addresses based on a provided wallet descriptor. ```APIDOC ## POST /bitcoin/rpcclient/deriveaddresses ### Description Derives addresses from a descriptor. This command generates addresses based on a provided wallet descriptor. ### Method POST ### Endpoint /bitcoin/rpcclient/deriveaddresses ### Parameters #### Query Parameters - **descriptor** (string) - Required - The wallet descriptor string. - **range** (array) - Optional - A range of output indices to derive addresses from. Defaults to [0, 1000]. ### Request Example ```json { "descriptor": "wpkh(02.../0/*)", "range": [0, 10] } ``` ### Response #### Success Response (200) - **result** (array) - An array of derived addresses. #### Response Example ```json { "result": [ "bc1q...", "bc1q..." ] } ``` ``` -------------------------------- ### Shut Down Bitcoin Daemon Source: https://docs.21.dev/data/documentation/bitcoin/gettingstarted Send the stop RPC to signal the daemon to begin shutdown and then wait for the daemon thread to fully exit. Skipping the join can lead to inconsistent store states. ```swift _ = try await client.stop() Daemon.waitUntilStopped() ``` -------------------------------- ### UnixTimestamp Structure Definition Source: https://docs.21.dev/data/documentation/bitcoin/unixtimestamp Defines the UnixTimestamp structure used in Bitcoin Core. ```swift struct UnixTimestamp ``` -------------------------------- ### estimaterawfee Source: https://docs.21.dev/data/documentation/bitcoin/llms-full.txt Estimates the fee for a raw transaction. This command helps determine an appropriate fee rate based on network conditions. ```APIDOC ## POST /bitcoin/rpcclient/estimaterawfee ### Description Estimates the fee for a raw transaction. This command helps determine an appropriate fee rate based on network conditions. ### Method POST ### Endpoint /bitcoin/rpcclient/estimaterawfee ### Parameters #### Query Parameters - **conftarget** (integer) - Required - The confirmation target in blocks. - **threshold** (number) - Optional - The maximum fee rate in BTC/kvB that the client will return. ### Request Example ```json { "conftarget": 6, "threshold": 0.0001 } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the estimated fee rate. - **feerate** (number) - The estimated fee rate in BTC/kvB. - **errors** (array) - An array of errors encountered during estimation, if any. #### Response Example ```json { "result": { "feerate": 0.00005, "errors": [] } } ``` ``` -------------------------------- ### TransactionOutpoint Source: https://docs.21.dev/data/documentation/bitcoinkernel/llms.txt A reference to a prior transaction output, identified by a transaction ID (txid) and an output index (vout). ```APIDOC ## TransactionOutpoint ### Description Reference to a prior transaction output — txid + vout. ``` -------------------------------- ### JSONRPCService Class Declaration Source: https://docs.21.dev/data/documentation/bitcoin/jsonrpcservice Declares the JSONRPCService class. This class is part of the Bitcoin framework and is used for sending JSON-RPC requests. ```swift class JSONRPCService ```