-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpc.php
106 lines (86 loc) · 2.77 KB
/
rpc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
class Bitcoin {
// Configuration options
private $username;
private $password;
private $host;
private $port;
private $url;
// Information and debugging
public $status;
public $error;
public $raw_response;
public $response;
private $id = 0;
function __construct($username, $password, $host = 'localhost', $port = 8332, $url = null) {
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->url = $url;
}
function __call($method, $params) {
$this->status = null;
$this->error = null;
$this->raw_response = null;
$this->response = null;
// The ID should be unique for each call
$this->id++;
// If no parameters are passed, this will be an empty array
$params = array_values($params);
// Build the request, it's ok that params might have any empty array
$request = json_encode(array(
'method' => $method,
'params' => $params,
'id' => $this->id
));
// Build the cURL session
$curl = curl_init("http://{$this->username}:{$this->password}@{$this->host}:{$this->port}/{$this->url}");
$options = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 10,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_MAXREDIRS => 10,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $request
);
curl_setopt_array($curl, $options);
// Execute the request and decode to an array
$this->raw_response = curl_exec($curl);
$this->response = json_decode($this->raw_response, TRUE);
// If the status is not 200, something is wrong
$this->status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// If there was no error, this will be an empty string
$curl_error = curl_error($curl);
curl_close($curl);
if (!empty($curl_error)) {
$this->error = $curl_error;
}
if ($this->response['error']) {
// If bitcoind returned an error, put that in $this->error
$this->error = $this->response['error']['message'];
} elseif ($this->status != 200) {
// If bitcoind didn't return a nice error message, we need to make our own
switch ($this->status) {
case 400:
$this->error = 'HTTP_BAD_REQUEST';
break;
case 401:
$this->error = 'HTTP_UNAUTHORIZED';
break;
case 403:
$this->error = 'HTTP_FORBIDDEN';
break;
case 404:
$this->error = 'HTTP_NOT_FOUND';
break;
}
}
if ($this->error) {
return FALSE;
}
return $this->response['result'];
}
}