Coder Social home page Coder Social logo

bitcoind-php's Introduction

nbobtc/bitcoind-php Travis branch Packagist Packagist Pre Release

Code Climate Code Climate SensioLabs Insight

This project is used to interact with a headless bitcoin program called bitcoind. It also contains various utility classes for working with Bitcoin as a PHP Developer.

Installation

You can install this library by using Composer. You can also view more info about this on Packagist.

composer require nbobtc/bitcoind-php

Usage

To use the project you need to just create a new instance of the class.

<?php

require __DIR__ . '/vendor/autoload.php';

$command = new \Nbobtc\Command\Command('getinfo');
$client  = new \Nbobtc\Http\Client('https://username:password@localhost:18332');

/** @var \Nbobtc\Http\Message\Response */
$response = $client->sendCommand($command);

/** @var string */
$contents = $response->getBody()->getContents();
echo $contents;

You are able to get the Request and Response objects back from the client with the correct getters: getRequest() and getResponse().

You can also parse the response however you wish to do so since the result is returned to you as a string. See below for some ideas!

Commands

Commands are created in such a way that this will support any future updates the Bitcoin API by providing you with an easy class that sets all the required information.

You are able to pass into the object the method and the parameters that are required. Here are a few examples:

// No Parameters
$command = new Command('getinfo');

// One Parameter
$command = new Command('getblock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f');

// Multiple Parameters
$command = new Command('sendfrom', array('fromaccount', 'tobitcoinaddress', 'amount'));

The second argument MUST be in the same order as on the Bitcoin API wiki page. There is no need to assign the values any keys.

Parameters

Parameters are the second argument when creating a new Command. This argument can either be a string OR an array. For example, both of these are valid.

$command = new Command('getblock', array('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'));
$command = new Command('getblock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f');

Most commands in the Bitcoin API take one parameter. If it takes MORE than one, you must pass the parameters in as an array in the ORDER you find them on that page.

Extending Commands

If, for any reason, you need to extend a command, it MUST implement CommandInterface. You can find documentation within the interface on how to implement this.

Drivers

Drivers are used by the ClientInterface for connecting to a bitcoind service and sending Requests. The return a Response. If you need to implement a new driver take a look at the DriverInterface.

cURL Driver

This is used by default and allows you a lot of options for customizing it to your needs.

You can set various cURL Options by passing them into the function addCurlOption($option, $value).

Here's an example of how to configure and use the driver.

$driver = new \Nbobtc\Http\Driver\CurlDriver();
$driver
    ->addCurlOption(CURLOPT_VERBOSE, true)
    ->addCurlOption(CURLOPT_STDERR, '/var/logs/curl.err');

$client = new \Nbobtc\Http\Client('https://username:password@localhost:18332');
$client->withDriver($driver);

Feel free to take a look at the CurlDriver source code.

Cookbook

How to enable a Keep-Alive ie Persistent Connection

This example shows how you are able to set the client up to Persistent Connection.

$client = new \Nbobtc\Http\Client('https://username:password@localhost:18332');
$client->getRequest()->withHeader('Connection', 'Keep-Alive');

How to set a CA Cert

This library provides some wonderful flexibility that will allow you to configure the client to use your own CA Cert.

$driver = new \Nbobtc\Http\Driver\CurlDriver();
$driver->addCurlOption(CURLOPT_CAINFO, '/path/to/cert');

$client = new \Nbobtc\Http\Client('https://username:password@localhost:18332');
$client->withDriver($driver);

How to Convert Output to an Array

Some like the arrays

$response = $client->sendCommand($command);
$output   = json_decode($response->getBody()->getContents(), true);

How to Convert Output to a stdClass object

Some like the objects

$response = $client->sendCommand($command);
$output   = json_decode($response->getBody()->getContents());

Testing

All testing is done using PHPUnit. You should be able to run phpunit in the root directory of this project (the directory where phpunit.xml.dist is located) and the tests will run.

If submitting a pull request or working on this library, please make sure that the tests will pass.

Change log

See CHANGELOG.md.

Contains information on releases such as what was added, changed, etc. It's good to look at to see what has changed from release to release.

Contributing

See CONTRIBUTING.md.

Various ways on contributing to this project.

Branching

master

This is the latest and greatest, it should not be used an is considered development for testing new features and functionality. This should NOT be used in a production environment.

2.x

Current production branch. All 2.x tags come off of this branch.

1.x

Deprecated, only used for bug fixes and for historical records.

License (MIT) Packagist

Copyright (C) 2012-2018 Joshua Estes

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

bitcoind-php's People

Contributors

analogic avatar deweller avatar dexx7 avatar greatwitenorth avatar joshuaestes avatar neilgarb avatar ocramius avatar sanasol avatar scr34m avatar skrajewski avatar willgriffin 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

bitcoind-php's Issues

Add require_once description pls

It could be a good idea for such noobies as as me to add require_once installation instructions. Its real pain in the ass to figure out how to start working with lib.

I've downloaded it through git clone. Then I've created php file and added two main (as I think) files

require_once Nt_Path::get()->scripts . '/btc/lib/Http/Client.php';

require_once Nt_Path::get()->scripts . '/btc/lib/Command/Command.php';


but it doesnt work, I assume it should be added somehow else... but how?

Im trying to use the library in pretty old zend framework, is there an easy require way of installing it?

getContents() empty

For some reason after update to 2.x-dev version getContents() always empty.

Empty here:

$command = new \Nbobtc\Command\Command($command, $options);
$response = $client->sendCommand($command);
$contents = $response->getBody()->getContents();

Work fine with __toString():

$command = new \Nbobtc\Command\Command($command, $options);
$response = $client->sendCommand($command);
$contents = $response->getBody()->__toString();

Not sure how it broken, maybe you have some ideas?
As i see nothing changed, but old code doesn't work 😣

CurlDriver::__destruct is giving me problems

I ran into problems with the curl driver.
I iterate through some addresses and fire the 'getreceivedbyaddress' command. The first address gave me the correct output but as soon as I get to the second address I get:

[ErrorException]
curl_close(): supplied resource is not a valid cURL handle resource

[ErrorException]
curl_setopt_array(): supplied resource is not a valid cURL handle resource

I commented the following line from the destructor and then everything works like a charm.
public function __destruct()
{
if (null !== self::$ch) {
// curl_close(self::$ch);
}
}
obvious I can also set self::$ch to null...

I do not understand why this is. curl_close always throws this exception after the first command. No matter when I call it. any clue?

Start using releases or tags

Given that new RPC commands were added over time which are not available in all Bitcoin Core versions, some form of categorization would be helpful.

Body is empty due to missing seek command

The php://temp stream is not read from the beginning without issuing a seek command.

There are some unexpected consequences of this behavior.

For example, calling $response->getBody()->getContents() twice will return null the second time.

incompatible with psr/http-message current version

Just installed with composer (as a vendor in a cakephp 3 project), received this error at the first try:
Fatal error: Declaration of Nbobtc\Http\Message\Message::withBody() must be compatible with Psr\Http\Message\MessageInterface::withBody(Psr\Http\Message\StreamInterface $body) in ****\vendor\nbobtc\bitcoind-php\src\Http\Message\Message.php on line 18

the psr http-message module was updated recently, maybe it was a major update. There is no streamableinterface any more as I see, but could not resolve the error by trying to make it compatible (renaming and stuff), just more errors occured..

catch exception

How to catch an exception which for example may occur when bitcoind is offline?
Wasn't able to solve this by using:

private function getAddress(){

//...prepare connection
try{
    $response = $client->sendCommand($command);
    return json_decode($response->getBody()->getContents());
}
catch(Exception $e){
    return json_encode([
        'errors' => 'server offline',
        ]);
}

Feature request: Return response in object, array or json

Currently the responses are returned as PHP objects. Example: $object->info I think it would be useful to have an option in the client to return responses as array.

I prefer responses to be returned as array. Example: $object['info']

Returning as json would be useful as well, since this is what bitcoind returns.

safe lines of code

Is there a way to safe some lines of code?
As example:

$command = new \Nbobtc\Command\Command;
$client = new \Nbobtc\Http\Client('http://***:***@localhost:18332');

$command = new $command('validateaddress', $request->input('address'));
$response = $client->sendCommand($command);
$contents = json_decode($response->getBody()->getContents());

if($contents->result->isvalid) {
    $command = new $command('getnewaddress', 'foo');
    $response = $client->sendCommand($command);
    $contents = json_decode($response->getBody()->getContents());
    print_r($response);
}

so is there a shorter way to get the result?

Weird issues around static curl resource

Example output with debugging code shows multiple CurlDrivers can cause problems - destructing one destroys the $ch, but leaves an Unknown resource there.

destruct CurlDriver #1: 0000000041738a1d000000001283de3d
/home/bitcoin/git/bitcoind-php/src/Http/Driver/CurlDriver.php:37:
resource(91) of type (curl)
 - closed curl
destruct CurlDriver #2: 0000000041738a16000000001283de3d
/home/bitcoin/git/bitcoind-php/src/Http/Driver/CurlDriver.php:37:
resource(91) of type (Unknown)

This had a pretty sinister effect on my tests - https://travis-ci.org/Bit-Wasp/bitcoin-php/builds/290376696 - HHVM notices there is a null object pointer and breaks, PHP just segfaults or runs out of memory. Some more debugging will tell me if travis's environment is interacting with something here, (or if curl can be patched to notice improper usage) but interesting that I don't seem to get the issues locally..

Submitting a test case that I see passes on 2.x branch, but fails on the latest tagged release.

Could you tag a release please? :)

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.