php-bitcoinrpc

repository·2.2.x·Indexed 42 days ago

https://github.com/denpamusic/php-bitcoinrpc

A PHP client for interacting with Bitcoin Core via JSON-RPC, built on GuzzleHttp. It provides a fluent interface for calling RPC methods, support for asynchronous requests, multi-wallet scoping, and helper functions for Bitcoin unit conversion. Supports PHP 8.0+ (v2.2), PHP 7.0-7.4 (v2.1.x), and PHP 5.6-7.0 (v2.0.x).

Tokens
4.5K
Snippets
16
Records
18
Agent score
54%

What's inside php-bitcoinrpc

  1. Manipulate and query RPC responses

    2.2.x

    Responses from the client are returned as objects that support various data access patterns and helper methods for navigating JSON structures.

    Data Access

    • Method call as function: $block('hash')->get() retrieves the value of the 'hash' key.
    • Array access: $block['height'] retrieves the value of the 'height' key.
    • Dot notation: $block->get('tx.0') retrieves the first element of the 'tx' array.
    • $block->count('key'): Returns the count of elements in a key.
    • $block->has('key'): Checks if a key exists and is NOT null.
    • $block->exists('key'): Checks if a key exists (can be null).
    • $block->contains($value): Checks if the response contains a specific value.
    • $block->values(): Returns an array of all values.
    • $block->keys(): Returns an array of all keys.
    • $block->first('key') / $block->last('key'): Gets the first or last element of a specific key.
    • $block->random(count, 'key'): Returns a random element or multiple random elements from a key.
    $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
  2. Install php-bitcoinrpc via Composer

    2.2.x

    Install the package using Composer by running the following command in your project directory:

    php composer.phar require denpa/php-bitcoinrpc

    Alternatively, add the following line to your composer.json file and run php composer.phar install:

    "require": {
        "denpa/php-bitcoinrpc": "^2.2"
    }
    php composer.phar require denpa/php-bitcoinrpc
  3. Initialize the Bitcoin Client

    2.2.x

    The Denpa\Bitcoin\Client class is the primary entrypoint for interacting with a Bitcoin RPC server. You can initialize it by passing either an associative array of configuration options or a single DSN string (which will be parsed via split_url).

    When initialized, the client automatically configures a Guzzle HTTP client with the appropriate DSN, authentication, CA certificates, and timeouts defined in your configuration.

    use Denpa\Bitcoin\Client;
    
    // Using a DSN string
    $client = new Client('http://user:password@127.0.0.1:8332');
    
    // Using a configuration array
    $client = new Client([
        'dsn'    => 'http://user:password@127.0.0.1:8332',
        'timeout' => 5.0,
    ]);
  4. Handle Bitcoin RPC Exceptions

    2.2.x

    The following exceptions may be thrown during operation:

    • Denpa\Bitcoin\Exceptions\BadConfigurationException: Thrown when the client configuration is invalid.
    • Denpa\Bitcoin\Exceptions\BadRemoteCallException: Thrown when the daemon returns an error message.
    • Denpa\Bitcoin\Exceptions\ConnectionException: Thrown on connection errors (e.g., timeouts).
  5. Perform asynchronous RPC calls

    2.2.x

    You can perform non-blocking requests in two ways:

    Using magic methods with Async suffix

    Append Async to the method name and provide a success callback and an error callback.

    Using the requestAsync method

    Pass the method name as a string followed by arguments, then provide success and error callbacks.

    // Magic method approach
    $bitcoind->getBlockAsync(
        'hash',
        function ($response) { /* success */ },
        function ($exception) { /* error */ }
    );
    
    // requestAsync approach
    $bitcoind->requestAsync(
        'getBlock',
        'hash',
        function ($response) { /* success */ },
        function ($exception) { /* error */ }
    );
    $bitcoind->getBlockAsync(
        '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',
        function ($response) {
            // success
        },
        function ($exception) {
            // error
        }
    );
  6. Execute Multi-Wallet RPC calls

    2.2.x

    To interact with a specific wallet in a multi-wallet setup, use the wallet($name) method. This returns a client instance scoped to that wallet.

    // Get balance for a specific wallet file
    $balance = $bitcoind->wallet('wallet2.dat')->getbalance();
    
    echo $balance->get(); // e.g., 0.10000000
    $balance = $bitcoind->wallet('wallet2.dat')->getbalance();
    
    echo $balance->get(); // 0.10000000
  7. Initialize the BitcoinClient

    2.2.x

    You can initialize a Denpa\Bitcoin\Client using either a connection URL string or a configuration array.

    Using a URL string

    Pass the full RPC URL (including credentials) as a parameter.

    Using a configuration array

    Provide an associative array with the following keys:

    • scheme: (optional, default http) The protocol.
    • host: (optional, default localhost) The RPC host.
    • port: (optional, default 8332) The RPC port.
    • user: (required) The RPC username.
    • password: (required) The RPC password.
    • ca: (optional) Path to CA certificate for https.
    • preserve_case: (optional) If true, method names are sent as defined instead of being lowercased.
    use Denpa\Bitcoin\Client as BitcoinClient;
    
    // Option 1: URL string
    $bitcoind = new BitcoinClient('http://rpcuser:rpcpassword@localhost:8332/');
    
    // Option 2: Configuration array
    $bitcoind = new BitcoinClient([
        'scheme'        => 'http',
        'host'          => 'localhost',
        'port'          => 8332,
        'user'          => 'rpcuser',
        'password'      => 'rpcpassword',
        'ca'            => '/etc/ssl/ca-cert.pem',
        'preserve_case' => false,
    ]);
  8. Configure the Bitcoin RPC connection with Config

    2.2.x

    The Denpa\Bitcoin\Config class manages connection settings and credentials for the Bitcoin JSON-RPC client. You can instantiate it with an array of configuration options. It supports merging new settings into the existing configuration.

    Configuration Keys

    KeyDefaultDescription
    scheme'http'The protocol scheme (e.g., http or https).
    host'127.0.0.1'The hostname or IP address of the Bitcoin node.
    port8332The RPC port number.
    usernullThe RPC username.
    passwordnullThe RPC password. Note: You can also use the key pass as an alias for password.
    canullPath to a Certificate Authority (CA) file. getCa() will only return this value if the file exists on disk.
    timeoutfalseConnection timeout setting.
    preserve_casefalseWhether to preserve case in responses.

    Key Methods

    • set(array $config): Merges new configuration values into the current instance. Returns $this for chaining. Supports pass as an alias for password to maintain compatibility with laravel-bitcoinrpc.
    • getDsn(): Returns the Data Source Name string in the format scheme://host:port.
    • getAuth(): Returns an array containing [user, password] for authentication purposes.
    • getCa(): Returns the CA file path if it is set and is a valid file; otherwise returns null.
    use Denpa\Bitcoin\Config;
    
    // Basic configuration
    $config = new Config([
        'host'     => '192.168.1.100',
        'port'     => 8332,
        'user'     => 'my_user',
        'pass'     => 'my_password', // 'pass' is aliased to 'password'
    ]);
    
    // Chaining configuration updates
    $config->set([
        'scheme' => 'https',
        'ca'     => '/path/to/cert.pem'
    ]);
    
    // Accessing connection details
    echo $config->getDsn(); // Outputs: https://192.168.1.100:8332
  9. Use Bitcoin value conversion helpers

    2.2.x

    The package provides several global helper functions to convert between different Bitcoin unit representations.

    • Denpa\Bitcoin\to_bitcoin(int $satoshi): Converts satoshis to bitcoin.
    • Denpa\Bitcoin\to_satoshi(float $bitcoin): Converts bitcoin to satoshis.
    • Denpa\Bitcoin\to_ubtc(float $bitcoin): Converts bitcoin to ubtc/bits.
    • Denpa\Bitcoin\to_mbtc(float $bitcoin): Converts bitcoin to mbtc.
    • Denpa\Bitcoin\to_fixed(float $value, int $precision): Trims a float value to a specific precision without rounding.
    echo Denpa\Bitcoin\to_bitcoin(100000); // 0.00100000
    echo Denpa\Bitcoin\to_satoshi(0.001);   // 100000
    echo Denpa\Bitcoin\to_ubtc(0.001);    // 1000.0000
    echo Denpa\Bitcoin\to_mbtc(0.001);    // 1.0000
    echo Denpa\Bitcoin\to_fixed(0.1236, 3); // 0.123
  10. Handle Bitcoin RPC errors with BadRemoteCallException

    2.2.x

    When a Bitcoin JSON-RPC call fails or the remote node returns an error, the library throws a BadRemoteCallException. This exception is a subclass of ClientException and contains the full Response object from the failed call.

    You can catch this exception to access the specific error message, error code, and the original response object to inspect the failure details.

    try {
        $client->getblockchaininfo();
    } catch (\Denpa\Bitcoin\Exceptions\BadRemoteCallException $e) {
        // Access the error message and code via standard Exception methods
        $message = $e->getMessage();
        $code = $e->getCode();
    
        // Access the full response object for deeper inspection
        $response = $e->getResponse();
    }