GithubHelp home page GithubHelp logo

denpamusic / php-bitcoinrpc Goto Github PK

View Code? Open in Web Editor NEW
284.0 22.0 102.0 345 KB

Fully unit-tested Bitcoin JSON-RPC client based on GuzzleHttp.

License: MIT License

PHP 100.00%
bitcoin guzzlehttp json-rpc cryptocurrency api api-client

php-bitcoinrpc's Introduction

Simple Bitcoin JSON-RPC client based on GuzzleHttp

Latest Stable Version License ci Code Climate Code Coverage

Installation

Run php composer.phar require denpa/php-bitcoinrpc in your project directory or add following lines to composer.json

"require": {
    "denpa/php-bitcoinrpc": "^2.2"
}

and run php composer.phar install.

Requirements

PHP 8.0 or higher
For PHP 5.6 to 7.0 use php-bitcoinrpc v2.0.x.
For PHP 7.0 to 7.4 use php-bitcoinrpc v2.0.x.

Usage

Create new object with url as parameter

/**
 * 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/');

or use array to define your bitcoind settings

/**
 * 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
]);

Then call methods defined in Bitcoin Core API Documentation with magic:

/**
 * 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);

To send asynchronous request, add Async to method name:

$bitcoind->getBlockAsync(
    '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',
    function ($response) {
        // success
    },
    function ($exception) {
        // error
    }
);

You can also send requests using request method:

/**
 * 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();

or requestAsync method for asynchronous calls:

$bitcoind->requestAsync(
    'getBlock',
    '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',
    function ($response) {
        // success
    },
    function ($exception) {
        // error
    }
);

Multi-Wallet RPC

You can use wallet($name) function to do a Multi-Wallet RPC call:

/**
 * Get wallet2.dat balance.
 */
$balance = $bitcoind->wallet('wallet2.dat')->getbalance();

echo $balance->get(); // 0.10000000

Exceptions

  • Denpa\Bitcoin\Exceptions\BadConfigurationException - thrown on bad client configuration.
  • Denpa\Bitcoin\Exceptions\BadRemoteCallException - thrown on getting error message from daemon.
  • Denpa\Bitcoin\Exceptions\ConnectionException - thrown on daemon connection errors (e. g. timeouts)

Helpers

Package provides following helpers to assist with value handling.

to_bitcoin()

Converts value in satoshi to bitcoin.

echo Denpa\Bitcoin\to_bitcoin(100000); // 0.00100000

to_satoshi()

Converts value in bitcoin to satoshi.

echo Denpa\Bitcoin\to_satoshi(0.001); // 100000

to_ubtc()

Converts value in bitcoin to ubtc/bits.

echo Denpa\Bitcoin\to_ubtc(0.001); // 1000.0000

to_mbtc()

Converts value in bitcoin to mbtc.

echo Denpa\Bitcoin\to_mbtc(0.001); // 1.0000

to_fixed()

Trims float value to precision without rounding.

echo Denpa\Bitcoin\to_fixed(0.1236, 3); // 0.123

License

This product is distributed under MIT license.

Donations

If you like this project, please consider donating:
BTC: 3L6dqSBNgdpZan78KJtzoXEk9DN3sgEQJu
Bech32: bc1qyj8v6l70c4mjgq7hujywlg6le09kx09nq8d350

❤Thanks for your support!❤

php-bitcoinrpc's People

Contributors

denpamusic avatar doc0x1 avatar gitter-badger avatar m-shahbaz avatar mtdlaurynas avatar partyka1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-bitcoinrpc's Issues

How library works

Does this library work without Bitcoin core...

And can I create wallet, send BTC to wallet, receive BTC using this library?

Should not use set_exception_handler

set_exception_handler([ExceptionHandler::getInstance(), 'handle']);

Using set_exception_handler can override existings handler and can be a big problem for application that already use it.
For it has shutdown the NewRelic error reporting !

I suggest either to not use it or, to use it right before a call and call restore_exception_handler after the call (a successfull call or an error one).

I will have to find a way to change that. If i can will propose you a pullrequest

Batch support

Is there support for batch requests? I could not find any info about it.

It would be nice if we could do something like this:

$block = $bitcoind->getBlockHash([100, 101]');

and

$block = $bitcoind->getBlock(['000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f, '00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048']');

setaccount can only be used with own address

I am experimenting a coin and get to stage of sending from individual to another. I found out using "sentfrom" require to specify the account which i did not specify initially while generating the address, so to rectify this i want the system to automatically fix the account users to their addresses using "setaccount"
$bimcoind->setaccount(strval($addr),strval($id));
the error report says Denpa\Bitcoin\Exceptions\BadRemoteCallException: setaccount can only be used with own address
How do can i rectify or go about setting the account user to individual addresses.
I need help.

How can I send BTC to another Address

Sorry for my ignorance but how can I send bitcoins to another address?
I'm trying

$send = $BTC->request('sendtoaddress', '*************************************************** 0.06');

Any example or not is possible?

Thanks ;D and good job.

composer fails due to new Guzzle 7.0.1 with Laravel 7

Describe the bug
The latest Laravel version comes with Guzzle 7.0.1 See Guzzle 7 Released
Running composer fails with:
Your requirements could not be resolved to an installable set of packages.

To Reproduce
Run
composer require denpa/php-bitcoinrpc
with a fresh Laravel 7 installation

Expected behavior
Dependency should be met

Logs
composer require denpa/php-bitcoinrpc
Using version ^2.1 for denpa/php-bitcoinrpc
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for guzzlehttp/guzzle (locked at 7.0.1, required as ^7.0) -> satisfiable by guzzlehttp/guzzle[7.0.1].
- denpa/php-bitcoinrpc 2.1.x-dev requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.5.x-dev].
- denpa/php-bitcoinrpc 2.2.x-dev requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.5.x-dev].
- denpa/php-bitcoinrpc v2.1.0 requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.5.x-dev].
- denpa/php-bitcoinrpc v2.1.1 requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.5.x-dev].
- denpa/php-bitcoinrpc v2.1.2 requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.5.x-dev].
- Conclusion: don't install guzzlehttp/guzzle 6.5.x-dev
- Installation request for denpa/php-bitcoinrpc ^2.1 -> satisfiable by denpa/php-bitcoinrpc[2.1.x-dev, 2.2.x-dev, v2.1.0, v2.1.1, v2.1.2].

Installation failed, reverting ./composer.json to its original content.

Environment
Describe your runtime environment:

Laravel Framework 7.25.0
PHP 7.3.11 (cli) (built: Jun 5 2020 23:50:40) ( NTS )

withdrawal Requests

I have a system in which users buy packages and buy plans ETC, on they can make withdrawal requests on the basis of their earning, can I make their withdrawal requests automatically on the basis their request

Linux 500 Internal Server Error when attempting to make request

I have bitcoind open, tested and works with bitcoin-cli. Currently, when I do “bitcoind->getwalletinfo()->result();”, or rather any request at all, it will return an internal server error (500). I just moved the files which previously works on a windows computer to a linux VPS, installed a fresh version of thisibrary using linux Composer and made sure all the files were in the correct directories. Pls help ;-;

Method adrressbylabel response answer all directions

Describe the bug
when I invoke the method adrressbylabel, I hope only to receive the address with that label, however it returns all

To Reproduce
adrressbylabel
Feel free to omit any sensitive information.

Expected behavior
I hope only to receive the address with that label.

Cryptocurrency

  • Software: Bitcoin Core v0.17.0
  • Network: mainnet

Environment

  • PHP: 7.0
  • Apache Server
  • Windows server

Danger! Re-sends RPC call on failure

I almost deployed with this library and did a final test and found a problem. Guzzle returned this error (for no discernible reason, but thats not the point of this report): Recv failure: Connection was reset (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

The problem is that this library for some reason re-sent the transaction a second later during the same function call, so it double-sent the coins AND threw an error to top it all off.

You can reproduce this yourself I've wasted too much time already... Just force that error to occur when sending coins and see what happens.

Command orders are important, whereas it shouldn't be on non-static usages.

       $free = $this->getWallet("emptyWallet");
        $address = $free->request("getnewaddress")->get();
        $amount = $free->request("getbalance")->get();
        $main = $this->getWallet("mainWallet");

        var_dump($main->request("sendtoaddress", $address, $amount, "payment", "user", true, false, null, 'CONSERVATIVE')->get());

when you do this is works, but if you declare $main before $free variable, it mixes up things. This means it is bound to some static variables on backend. So, if you do write the code in the following order;

      $main = $this->getWallet("mainWallet");
      $free = $this->getWallet("emptyWallet");

        $address = $free->request("getnewaddress")->get();
        $amount = $free->request("getbalance")->get();


        var_dump($main->request("sendtoaddress", $address, $amount, "payment", "user", true, false, null, 'CONSERVATIVE')->get());

It will give you "Insufficent Funds" error, as it will try to use the last active wallet's balance. "getWallet" function should not be static variable bound. Normally if you save it in memory on $main variable, when you use $main variable, it should point to the state of its declaration no matter which variable you change afterwards, as long as you don't change the main variable.

If it is working as non-static library, it should be completely compatible with it.

To reproduce this problem,
Just create two wallets, one of them should be empty. Put the empty wallet to $free variable section and the other to the $main. The second code group I sent will give you "Insufficent Funds" error no matter how much you have on the main wallet.

ListTransactions

Fatal error: Uncaught Denpa\Bitcoin\Exceptions\BadRemoteCallException: Method not found in /var/www/html/bot/vendor/denpa/php-bitcoinrpc/src/Exceptions/Handler.php:70 Stack trace: #0 /var/www/html/bot/vendor/denpa/php-bitcoinrpc/src/Exceptions/Handler.php(107): Denpa\Bitcoin\Exceptions\Handler->requestExceptionHandler(Object(GuzzleHttp\Exception\ClientException)) #1 /var/www/html/bot/vendor/denpa/php-bitcoinrpc/src/Client.php(161): Denpa\Bitcoin\Exceptions\Handler->handle(Object(GuzzleHttp\Exception\ClientException)) #2 /var/www/html/bot/vendor/denpa/php-bitcoinrpc/src/Client.php(227): Denpa\Bitcoin\Client->request('listransactions') #3 /var/www/html/bot/index.php(19): Denpa\Bitcoin\Client->__call('listransactions', Array) #4 {main} thrown in /var/www/html/bot/vendor/denpa/php-bitcoinrpc/src/Exceptions/Handler.php on line 70

This is what I'm getting trying to run $bitcoind->listransactions();
Tried to use parameters like $bitcoind->listransactions('*',10); etc - got the same.

You referred to https://bitcoin.org/en/developer-reference#bitcoin-core-apis in the description. Are there any other functions which are not working?

Cryptocurrency

  • Software: Bitcoin Core v0.18.0
  • Network: mainnet

Environment

  • PHP: 7.3
  • Apache/2.4.18
  • Ubuntu 16.04

Supporting wallet passphrase in configs

Issue
I've encrypted my wallet with a passphrase. Running commands after this change needs using passphrase before calling methods, but I did not find anywhere to set such key.

My solution:
I suggest having a new option in configs to allow communicate with wallet using passphrase if it is set.

In simple

Hi
I am php developer I want send bitcoin form self wallet to another. Dothis package cab help me?

sendmany fails when passing valid json string

When I prep a valid json string and pass it to sendmany, I get told it's not a valid json object:
https://developer.bitcoin.org/reference/rpc/sendmany.html

Denpa\Bitcoin\Exceptions\BadRemoteCallException
JSON value is not an object as expected

Here are some testnet addresses and amounts:

$payments = '{"tb1q87nfvuezn53pv5c6fwzz5tm9mp3dga9dajzel2":0.00014664,"tb1q87nfvuezn53pv5c6fwzz5tm9mp3dga9dajzel2":0.00048881,"tb1qmcnn8mxhdxa742nzdpcz0kzrdqtg7m0xvkes8t":0.0002444,"tb1qgc5vlfnt7fhnx5ly9yjt8zte8jppre0fa68xjl":0.00019776}';

Addresses to deduct fees from:

$addresses = '["tb1q87nfvuezn53pv5c6fwzz5tm9mp3dga9dajzel2","tb1q87nfvuezn53pv5c6fwzz5tm9mp3dga9dajzel2","tb1qmcnn8mxhdxa742nzdpcz0kzrdqtg7m0xvkes8t","tb1qgc5vlfnt7fhnx5ly9yjt8zte8jppre0fa68xjl"]';

I'm calling:

    $send = $this->jsonrpc->sendmany(
        "",
        $payments,
        1,
        "My Comment",
        $addresses
    )->get();

And getting the error described above.

I'm expecting a TXID returned from the BTC node

Logs
If applicable, attach log files.
Feel free to omit any sensitive information.

  • Software: Bitcoin Core v0.17.0
  • Network: testnet

Environment
Describe your runtime environment:

  • PHP: 7.4
  • Web Server : Apahce 2,4
  • System: Ubuntu 20 LTS

I've tried creating an array and json_encode() etc.. all fails.
Seems I need to explicitly send an object, but JSON is just a string.

bitcoin.conf options

hi, i'm not able to connect to my node (prune),maybe i haven't my .conf whith right options:
prune=550
rpcuser=xxxxxxxxxxxxx
rpcpassword=xxxxxxxxxxxxxxx
maxconnections=24
server=1
testnet=0
rpcconnect=127.0.0.1
daemon=1
Do i need to change anything? Thanks

$bitcoind->sendToAddress and next steps

Hello.

Tell me what to do next-after using $bitcoind-> Sendtoaddress in the case of using 3 networks:

  • regtest
  • testnet
  • mainnet

Now I used this method (sendToAddress) in the regtest, I received the transaction Id. And then what to do - how to make sure that the transaction has confirmations? I understand correctly what I need to use with the createrawtransaction, then signrawtransactionwithwallet, and then sendrawtransaction? Or something else? How can I do this with your library?

Could you write in steps - what needs to be done.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.