### Install PHP Bitcoin RPC Client using Composer Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Instructions for installing the php-bitcoinrpc library using Composer. This involves either a direct composer require command or adding the dependency to your composer.json file. ```php composer.phar require denpa/php-bitcoinrpc ``` ```json { "require": { "denpa/php-bitcoinrpc": "^2.2" } } ``` ```php php composer.phar install ``` -------------------------------- ### Initialize PHP Bitcoin Client with Configuration Array Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Initializes the Bitcoin RPC client using a configuration array for detailed control over connection parameters such as scheme, host, port, credentials, SSL certificate path, and timeouts. It requires the `vendor/autoload.php` file and the `Denpa\Bitcoin\Client` class. The example shows how to verify the configuration and make a test call to `getnetworkinfo`. ```php 'https', 'host' => '192.168.1.100', 'port' => 8332, 'user' => 'rpcuser', 'password' => 'rpcpassword', 'ca' => '/etc/ssl/ca-cert.pem', // optional, for HTTPS 'timeout' => 30, 'preserve_case' => false, ]); // Verify configuration $config = $bitcoind->getConfig(); echo "Connecting to: " . $config->getDsn() . "\n"; // Make a test call try { $networkInfo = $bitcoind->getnetworkinfo(); echo "Bitcoin Core version: " . $networkInfo['version'] . "\n"; echo "Protocol version: " . $networkInfo['protocolversion'] . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Access Specific Wallets in Multi-Wallet Setup (PHP) Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt This snippet demonstrates how to access and manage specific wallet files in a multi-wallet Bitcoin RPC setup. It shows how to list loaded wallets, retrieve balances from individual wallets, send transactions from a specific wallet, list transactions, and create new wallets using the Denpa Bitcoin Client. ```php listWallets(); echo "Loaded wallets: " . implode(', ', $wallets->get()) . "\n"; // Get balance from specific wallet $wallet1Balance = $bitcoind->wallet('wallet1.dat')->getBalance(); echo "Wallet1 balance: " . $wallet1Balance->get() . " BTC\n"; $wallet2Balance = $bitcoind->wallet('wallet2.dat')->getBalance(); echo "Wallet2 balance: " . $wallet2Balance->get() . " BTC\n"; // Send from specific wallet try { $txid = $bitcoind ->wallet('wallet1.dat') ->sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.001); echo "Transaction from wallet1: " . $txid->get() . "\n"; } catch (\Denpa\Bitcoin\Exceptions\BadRemoteCallException $e) { echo "Send failed: " . $e->getMessage() . "\n"; } // Get transaction list from specific wallet $transactions = $bitcoind->wallet('wallet2.dat')->listTransactions('*', 10); foreach ($transactions as $tx) { echo sprintf( "TX: %s - Amount: %s BTC - Confirmations: %d\n", $tx['txid'], $tx['amount'], $tx['confirmations'] ?? 0 ); } // Create and load new wallet try { $newWallet = $bitcoind->createWallet('wallet3.dat'); echo "New wallet created: " . $newWallet['name'] . "\n"; $newBalance = $bitcoind->wallet('wallet3.dat')->getBalance(); echo "New wallet balance: " . $newBalance->get() . " BTC\n"; } catch (Exception $e) { echo "Wallet operation failed: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Initialize PHP Bitcoin Client with URL String Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Initializes the Bitcoin RPC client using a connection URL string that includes credentials and endpoint information. It requires the `vendor/autoload.php` file and the `Denpa\Bitcoin\Client` class. The example demonstrates testing the connection with `getblockchaininfo` and includes error handling for connection and RPC call failures. ```php getblockchaininfo(); echo "Chain: " . $info['chain'] . "\n"; echo "Blocks: " . $info['blocks'] . "\n"; echo "Best block hash: " . $info['bestblockhash'] . "\n"; } catch (\Denpa\Bitcoin\Exceptions\ConnectionException $e) { echo "Connection failed: " . $e->getMessage() . "\n"; } catch (\Denpa\Bitcoin\Exceptions\BadRemoteCallException $e) { echo "RPC call failed: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Perform Multi-Wallet RPC Calls (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Explains how to perform RPC calls on specific wallets using the `wallet($name)` function. This example shows how to get the balance from a wallet named 'wallet2.dat'. ```php /** * Get wallet2.dat balance. **/ $balance = $bitcoind->wallet('wallet2.dat')->getbalance(); echo $balance->get(); // 0.10000000 ``` -------------------------------- ### Making Bitcoin RPC Calls with Magic Methods in PHP Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Demonstrates how to make Bitcoin Core RPC calls using magic methods provided by the client. These methods automatically handle method name casing and request sending. The example covers fetching block information, wallet balance, listing unspent transaction outputs, and sending Bitcoin, utilizing fluent response handling and error exceptions. ```php getBlock($blockHash); echo "Block hash: " . $block['hash'] . "\n"; echo "Block height: " . $block['height'] . "\n"; echo "Confirmations: " . $block['confirmations'] . "\n"; echo "Number of transactions: " . $block->count('tx') . "\n"; echo "First transaction: " . $block->get('tx.0') . "\n"; // Get wallet balance $balance = $bitcoind->getBalance(); echo "Wallet balance: " . $balance->get() . " BTC\n"; // List unspent transaction outputs $unspent = $bitcoind->listUnspent(6, 9999999); foreach ($unspent as $utxo) { echo sprintf( "UTXO: %s:%d - Amount: %s BTC (%d confirmations)\n", $utxo['txid'], $utxo['vout'], $utxo['amount'], $utxo['confirmations'] ); } // Send bitcoin to address try { $txid = $bitcoind->sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.001); echo "Transaction sent: " . $txid->get() . "\n"; } catch (\Denpa\Bitcoin\Exceptions\BadRemoteCallException $e) { echo "Transaction failed: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Use Request Method for Bitcoin RPC Calls (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Shows how to use the `request` method to call Bitcoin Core RPC methods by name and parameters. This provides an alternative to magic methods and offers similar response handling capabilities using `get`, array access, and other helper functions. ```php /** * Get block info. **/ $block = $bitcoind->request('getBlock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'); $block('hash'); // 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f $block['height']; // 0 (array access) $block->get('tx.0'); // 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b $block->count('tx'); // 1 $block->has('version'); // key must exist and CAN NOT be null $block->exists('version'); // key must exist and CAN be null $block->contains(0); // check if response contains value $block->values(); // get response values $block->keys(); // get response keys $block->first('tx'); // get txid of the first transaction $block->last('tx'); // get txid of the last transaction $block->random(1, 'tx'); // get random txid /** * Send transaction. **/ $result = $bitcoind->request('sendtoaddress', 'mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.06); $txid = $result->get(); ``` -------------------------------- ### Call Bitcoin RPC Methods and Handle Responses (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Illustrates how to call various Bitcoin Core RPC methods like `getBlock` and `sendToAddress` using the client object. It demonstrates accessing response data using magic methods, array access, and helper functions like `get`, `count`, `has`, `exists`, `contains`, `values`, `keys`, `first`, `last`, and `random`. ```php /** * Get block info. **/ $block = $bitcoind->getBlock('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'); $block('hash')->get(); // 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f $block['height']; // 0 (array access) $block->get('tx.0'); // 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b $block->count('tx'); // 1 $block->has('version'); // key must exist and CAN NOT be null $block->exists('version'); // key must exist and CAN be null $block->contains(0); // check if response contains value $block->values(); // array of values $block->keys(); // array of keys $block->random(1, 'tx'); // random block txid $block('tx')->random(2); // two random block txid's $block('tx')->first(); // txid of first transaction $block('tx')->last(); // txid of last transaction /** * Send transaction. **/ $result = $bitcoind->sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.1); $txid = $result->get(); /** * Get transaction amount. **/ $result = $bitcoind->listSinceBlock(); $bitcoin = $result->sum('transactions.*.amount'); $satoshi = \Denpa\Bitcoin\to_satoshi($bitcoin); ``` -------------------------------- ### Initialize Bitcoin Client with URL (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Demonstrates how to create a new Bitcoin client instance using a connection URL. Ensure the Composer autoloader is included. The URL should contain RPC user, password, and host with port. ```php /** * Don't forget to include composer autoloader by uncommenting line below * if you're not already done it anywhere else in your project. **/ // require 'vendor/autoload.php'; use Denpa\Bitcoin\Client as BitcoinClient; $bitcoind = new BitcoinClient('http://rpcuser:rpcpassword@localhost:8332/'); ``` -------------------------------- ### Initialize Bitcoin Client with Array Configuration (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Shows how to initialize the Bitcoin client using an associative array for detailed configuration. This method allows specifying scheme, host, port, user, password, and SSL CA path. The Composer autoloader must be included. ```php /** * Don't forget to include composer autoloader by uncommenting line below * if you're not already done it anywhere else in your project. **/ // require 'vendor/autoload.php'; use Denpa\Bitcoin\Client as BitcoinClient; $bitcoind = new BitcoinClient([ 'scheme' => 'http', // optional, default http 'host' => 'localhost', // optional, default localhost 'port' => 8332, // optional, default 8332 'user' => 'rpcuser', // required 'password' => 'rpcpassword', // required 'ca' => '/etc/ssl/ca-cert.pem', // optional, for use with https scheme 'preserve_case' => false, // optional, send method names as defined instead of lowercasing them ]); ``` -------------------------------- ### Make Asynchronous Bitcoin RPC Calls (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Demonstrates how to perform asynchronous RPC calls using `getBlockAsync`. This method allows providing callback functions for success and error handling, preventing blocking of the main execution flow. ```php $bitcoind->getBlockAsync( '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) { // success }, function ($exception) { // error } ); ``` -------------------------------- ### Making Bitcoin RPC Calls with request Method Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Demonstrates how to make explicit RPC calls using the `request` method in the PHP Bitcoin RPC client. This method provides granular control over RPC communication and is useful for avoiding magic methods. It requires the `denpa/bitcoin-php` library. ```php request('getBlock', $blockHash); echo "Block info:\n"; echo " Hash: " . $block('hash')->get() . "\n"; echo " Height: " . $block['height'] . "\n"; echo " Time: " . date('Y-m-d H:i:s', $block['time']) . "\n"; echo " Merkle root: " . $block->get('merkleroot') . "\n"; // Create raw transaction $inputs = [ ['txid' => 'abc123...', 'vout' => 0] ]; $outputs = [ 'mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6' => 0.001 ]; try { $rawTx = $bitcoind->request('createRawTransaction', $inputs, $outputs); echo "Raw transaction: " . $rawTx->get() . "\n"; // Sign the transaction $signedTx = $bitcoind->request('signRawTransactionWithWallet', $rawTx->get()); echo "Signed: " . ($signedTx['complete'] ? 'yes' : 'no') . "\n"; echo "Hex: " . $signedTx['hex'] . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Making Asynchronous Bitcoin RPC Calls Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Demonstrates how to perform non-blocking asynchronous RPC calls to a Bitcoin node using the PHP Bitcoin RPC client. This can be achieved using the `Async` suffix on method names or the `requestAsync` method. Callbacks are used to handle responses and exceptions. ```php getBlockAsync( '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) { echo "Async block received:\n"; echo " Height: " . $response['height'] . "\n"; echo " Transactions: " . $response->count('tx') . "\n"; }, function ($exception) { echo "Async error: " . $exception->getMessage() . "\n"; } ); // Async call with requestAsync method $bitcoind->requestAsync( 'getBlockchainInfo', [], function ($response) { echo "Chain: " . $response['chain'] . "\n"; echo "Blocks: " . $response['blocks'] . "\n"; }, function ($exception) { echo "Error: " . $exception->getMessage() . "\n"; } ); // Multiple async calls $hashes = [ '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', '00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048', ]; foreach ($hashes as $hash) { $bitcoind->getBlockAsync( $hash, function ($response) use ($hash) { echo "Block " . substr($hash, 0, 8) . "... has " . $response->count('tx') . " transactions\n"; } ); } // Wait for all async calls to complete $bitcoind->wait(); echo "All async calls completed\n"; ``` -------------------------------- ### Use RequestAsync Method for Asynchronous Bitcoin RPC Calls (PHP) Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Demonstrates the `requestAsync` method for making asynchronous RPC calls by specifying the method name and parameters. It includes callback functions for handling successful responses and exceptions, similar to `getBlockAsync`. ```php $bitcoind->requestAsync( 'getBlock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) { // success }, function ($exception) { // error } ); ``` -------------------------------- ### Bitcoin Unit Conversion Helper Functions (PHP) Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt This snippet showcases the Bitcoin unit conversion helper functions provided by the Denpa Bitcoin Client library. It demonstrates how to convert Bitcoin amounts between BTC, satoshi, mBTC, and uBTC, as well as how to format numbers to a fixed precision. ```php getBalance(); $btcAmount = $balance->get(); echo "Balance: " . $btcAmount . " BTC\n"; // Convert to satoshi $satoshi = \Denpa\Bitcoin\to_satoshi($btcAmount); echo "Balance in satoshi: " . $satoshi . " sat\n"; // Convert to mBTC (millibitcoin) $mbtc = \Denpa\Bitcoin\to_mbtc($btcAmount); echo "Balance in mBTC: " . $mbtc . " mBTC\n"; // Convert to uBTC/bits (microbitcoin) $ubtc = \Denpa\Bitcoin\to_ubtc($btcAmount); echo "Balance in bits: " . $ubtc . " bits\n"; // Convert satoshi back to bitcoin $satoshiValue = 100000; $btc = \Denpa\Bitcoin\to_bitcoin($satoshiValue); echo $satoshiValue . " satoshi = " . $btc . " BTC\n"; // Fixed precision without rounding $value = 0.123456789; $fixed = \Denpa\Bitcoin\to_fixed($value, 3); echo "Fixed precision (3 decimals): " . $fixed . "\n"; // 0.123 // Practical example: calculate transaction fee $inputAmount = 0.05; // BTC $outputAmount = 0.04998; // BTC $fee = $inputAmount - $outputAmount; $feeSatoshi = \Denpa\Bitcoin\to_satoshi($fee); echo "Transaction fee: " . $fee . " BTC (" . $feeSatoshi . " satoshi)\n"; // Display amounts in different formats $amounts = [0.001, 0.0001, 0.00000001]; foreach ($amounts as $amount) { echo "\nAmount: " . $amount . " BTC\n"; echo " = " . \Denpa\Bitcoin\to_satoshi($amount) . " satoshi\n"; echo " = " . \Denpa\Bitcoin\to_mbtc($amount) . " mBTC\n"; echo " = " . \Denpa\Bitcoin\to_ubtc($amount) . " bits\n"; } ``` -------------------------------- ### Convert Satoshi to Bitcoin in PHP Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Converts a value from satoshi to bitcoin. Accepts an integer representing satoshis and returns a string representing the value in bitcoin. ```php echo Denpa\Bitcoin\to_bitcoin(100000); // 0.00100000 ``` -------------------------------- ### PHP Bitcoin RPC Client Exception Handling Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Handles various exceptions from the Bitcoin RPC client, such as invalid configuration, connection issues, bad remote calls, and general client errors. This ensures graceful error management and debugging for applications interacting with Bitcoin nodes. ```php getMessage() . "\n"; echo "Invalid config: " . json_encode($e->getData()) . "\n"; } // Properly configured client $bitcoind = new BitcoinClient([ 'scheme' => 'http', 'host' => 'localhost', 'port' => 8332, 'user' => 'rpcuser', 'password' => 'rpcpassword', 'timeout' => 5, ]); // Handle connection errors (timeout, network issues) try { $info = $bitcoind->getBlockchainInfo(); echo "Connected successfully\n"; } catch (ConnectionException $e) { echo "Connection failed: " . $e->getMessage() . "\n"; echo "Could not reach Bitcoin node. Is it running?\n"; } // Handle bad RPC calls (wrong parameters, unknown methods) try { $block = $bitcoind->getBlock('invalid-hash'); } catch (BadRemoteCallException $e) { echo "RPC call error: " . $e->getMessage() . "\n"; $error = $e->getResponse()->error(); if ($error) { echo "Error code: " . $error['code'] . "\n"; echo "Error message: " . $error['message'] . "\n"; } } // Handle all client exceptions try { $txid = $bitcoind->sendToAddress('invalid-address', -1); } catch (ClientException $e) { echo "Client exception: " . get_class($e) . "\n"; echo "Message: " . $e->getMessage() . "\n"; } // Comprehensive error handling try { // Attempt to send transaction $txid = $bitcoind->sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.001); echo "Transaction successful: " . $txid->get() . "\n"; } catch (BadRemoteCallException $e) { // Handle RPC errors (insufficient funds, invalid address, etc.) $error = $e->getResponse()->error(); echo "Transaction failed: " . $error['message'] . "\n"; if ($error['code'] === -6) { echo "Reason: Insufficient funds\n"; } elseif ($error['code'] === -5) { echo "Reason: Invalid Bitcoin address\n"; } } catch (ConnectionException $e) { // Handle connection failures echo "Cannot connect to Bitcoin node: " . $e->getMessage() . "\n"; } catch (ClientException $e) { // Handle any other client errors echo "Unexpected error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Convert Bitcoin to Satoshi in PHP Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Converts a value from bitcoin to satoshi. Accepts a float or string representing bitcoin and returns an integer representing the value in satoshis. ```php echo Denpa\Bitcoin\to_satoshi(0.001); // 100000 ``` -------------------------------- ### Manipulating Bitcoin RPC Response Data with Collection Methods Source: https://context7.com/denpamusic/php-bitcoinrpc/llms.txt Illustrates how to access and manipulate JSON response data from Bitcoin RPC calls using the fluent Collection trait methods provided by the PHP Bitcoin RPC client. It supports dot notation, array access, and various collection operations. ```php getBlock('00000000000000000008e48b87b9c8c77d8f6c2f53e1b99a1e0d8c5a5d5f3e2b', 2); // Dot notation access $firstTx = $block->get('tx.0'); echo "First transaction ID: " . $firstTx['txid'] . "\n"; // Array access $height = $block['height']; echo "Block height: " . $height . "\n"; // Callable access to set current key $txInfo = $block('tx.0'); echo "First TX hash: " . $txInfo->get('hash') . "\n"; // Check existence if ($block->has('version')) { echo "Version field exists and is not null\n"; } if ($block->exists('mediantime')) { echo "Mediantime field exists\n"; } // Array operations $txCount = $block->count('tx'); echo "Total transactions: " . $txCount . "\n"; $allTxIds = $block->values('tx'); echo "Transaction IDs: " . implode(', ', array_slice($allTxIds, 0, 3)) . "...\n"; // Get random transaction $randomTx = $block->random(1, 'tx'); echo "Random transaction: " . $randomTx . "\n"; // First and last $firstTxId = $block('tx')->first(); $lastTxId = $block('tx')->last(); echo "First TX: " . $firstTxId . "\n"; echo "Last TX: " . $lastTxId . "\n"; // List transactions and sum amounts $transactions = $bitcoind->listSinceBlock(); $totalAmount = $transactions->sum('transactions.*.amount'); echo "Total transaction amount: " . $totalAmount . " BTC\n"; // Flatten nested arrays with wildcard $allAmounts = $transactions->flatten('transactions.*.amount'); echo "Number of amounts: " . count($allAmounts) . "\n"; ``` -------------------------------- ### Convert Bitcoin to MBTC in PHP Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Converts a value from bitcoin to mbtc. Accepts a float or string representing bitcoin and returns a float representing the value in mbtc. ```php echo Denpa\Bitcoin\to_mbtc(0.001); // 1.0000 ``` -------------------------------- ### Trim Float to Fixed Precision in PHP Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Trims a float value to a specified precision without rounding. Accepts a float and an integer for precision, returning a string with the trimmed value. ```php echo Denpa\Bitcoin\to_fixed(0.1236, 3); // 0.123 ``` -------------------------------- ### Convert Bitcoin to UBTC (Bits) in PHP Source: https://github.com/denpamusic/php-bitcoinrpc/blob/2.2.x/README.md Converts a value from bitcoin to ubtc, also known as bits. Accepts a float or string representing bitcoin and returns a float representing the value in ubtc. ```php echo Denpa\Bitcoin\to_ubtc(0.001); // 1000.0000 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.