├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── bitcoinrpc ├── .gitignore ├── __init__.py └── authproxy.py ├── jsonrpc ├── __init__.py ├── authproxy.py ├── json.py └── proxy.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | 3 | MANIFEST 4 | dist/ 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | GNU LESSER GENERAL PUBLIC LICENSE 3 | 4 | Version 2.1, February 1999 5 | 6 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 7 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 8 | Everyone is permitted to copy and distribute verbatim copies 9 | of this license document, but changing it is not allowed. 10 | 11 | [This is the first released version of the Lesser GPL. It also counts 12 | as the successor of the GNU Library Public License, version 2, hence 13 | the version number 2.1.] 14 | 15 | Preamble 16 | 17 | The licenses for most software are designed to take away your freedom to share 18 | and change it. By contrast, the GNU General Public Licenses are intended to 19 | guarantee your freedom to share and change free software--to make sure the 20 | software is free for all its users. 21 | 22 | This license, the Lesser General Public License, applies to some specially 23 | designated software packages--typically libraries--of the Free Software 24 | Foundation and other authors who decide to use it. You can use it too, but we 25 | suggest you first think carefully about whether this license or the ordinary 26 | General Public License is the better strategy to use in any particular case, 27 | based on the explanations below. 28 | 29 | When we speak of free software, we are referring to freedom of use, not price. 30 | Our General Public Licenses are designed to make sure that you have the 31 | freedom to distribute copies of free software (and charge for this service if 32 | you wish); that you receive source code or can get it if you want it; that you 33 | can change the software and use pieces of it in new free programs; and that 34 | you are informed that you can do these things. 35 | 36 | To protect your rights, we need to make restrictions that forbid distributors 37 | to deny you these rights or to ask you to surrender these rights. These 38 | restrictions translate to certain responsibilities for you if you distribute 39 | copies of the library or if you modify it. 40 | 41 | For example, if you distribute copies of the library, whether gratis or for a 42 | fee, you must give the recipients all the rights that we gave you. You must 43 | make sure that they, too, receive or can get the source code. If you link 44 | other code with the library, you must provide complete object files to the 45 | recipients, so that they can relink them with the library after making changes 46 | to the library and recompiling it. And you must show them these terms so they 47 | know their rights. 48 | 49 | We protect your rights with a two-step method: (1) we copyright the library, 50 | and (2) we offer you this license, which gives you legal permission to copy, 51 | distribute and/or modify the library. 52 | 53 | To protect each distributor, we want to make it very clear that there is no 54 | warranty for the free library. Also, if the library is modified by someone 55 | else and passed on, the recipients should know that what they have is not the 56 | original version, so that the original author's reputation will not be 57 | affected by problems that might be introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of any free 60 | program. We wish to make sure that a company cannot effectively restrict the 61 | users of a free program by obtaining a restrictive license from a patent 62 | holder. Therefore, we insist that any patent license obtained for a version of 63 | the library must be consistent with the full freedom of use specified in this 64 | license. 65 | 66 | Most GNU software, including some libraries, is covered by the ordinary GNU 67 | General Public License. This license, the GNU Lesser General Public License, 68 | applies to certain designated libraries, and is quite different from the 69 | ordinary General Public License. We use this license for certain libraries in 70 | order to permit linking those libraries into non-free programs. 71 | 72 | When a program is linked with a library, whether statically or using a shared 73 | library, the combination of the two is legally speaking a combined work, a 74 | derivative of the original library. The ordinary General Public License 75 | therefore permits such linking only if the entire combination fits its 76 | criteria of freedom. The Lesser General Public License permits more lax 77 | criteria for linking other code with the library. 78 | 79 | We call this license the "Lesser" General Public License because it does Less 80 | to protect the user's freedom than the ordinary General Public License. It 81 | also provides other free software developers Less of an advantage over 82 | competing non-free programs. These disadvantages are the reason we use the 83 | ordinary General Public License for many libraries. However, the Lesser 84 | license provides advantages in certain special circumstances. 85 | 86 | For example, on rare occasions, there may be a special need to encourage the 87 | widest possible use of a certain library, so that it becomes a de-facto 88 | standard. To achieve this, non-free programs must be allowed to use the 89 | library. A more frequent case is that a free library does the same job as 90 | widely used non-free libraries. In this case, there is little to gain by 91 | limiting the free library to free software only, so we use the Lesser General 92 | Public License. 93 | 94 | In other cases, permission to use a particular library in non-free programs 95 | enables a greater number of people to use a large body of free software. For 96 | example, permission to use the GNU C Library in non-free programs enables many 97 | more people to use the whole GNU operating system, as well as its variant, the 98 | GNU/Linux operating system. 99 | 100 | Although the Lesser General Public License is Less protective of the users' 101 | freedom, it does ensure that the user of a program that is linked with the 102 | Library has the freedom and the wherewithal to run that program using a 103 | modified version of the Library. 104 | 105 | The precise terms and conditions for copying, distribution and modification 106 | follow. Pay close attention to the difference between a "work based on the 107 | library" and a "work that uses the library". The former contains code derived 108 | from the library, whereas the latter must be combined with the library in 109 | order to run. 110 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 111 | 112 | 0. This License Agreement applies to any software library or other program 113 | which contains a notice placed by the copyright holder or other authorized 114 | party saying it may be distributed under the terms of this Lesser General 115 | Public License (also called "this License"). Each licensee is addressed as 116 | "you". 117 | 118 | A "library" means a collection of software functions and/or data prepared so 119 | as to be conveniently linked with application programs (which use some of 120 | those functions and data) to form executables. 121 | 122 | The "Library", below, refers to any such software library or work which has 123 | been distributed under these terms. A "work based on the Library" means either 124 | the Library or any derivative work under copyright law: that is to say, a work 125 | containing the Library or a portion of it, either verbatim or with 126 | modifications and/or translated straightforwardly into another language. 127 | (Hereinafter, translation is included without limitation in the term 128 | "modification".) 129 | 130 | "Source code" for a work means the preferred form of the work for making 131 | modifications to it. For a library, complete source code means all the source 132 | code for all modules it contains, plus any associated interface definition 133 | files, plus the scripts used to control compilation and installation of the 134 | library. 135 | 136 | Activities other than copying, distribution and modification are not covered 137 | by this License; they are outside its scope. The act of running a program 138 | using the Library is not restricted, and output from such a program is covered 139 | only if its contents constitute a work based on the Library (independent of 140 | the use of the Library in a tool for writing it). Whether that is true depends 141 | on what the Library does and what the program that uses the Library does. 142 | 143 | 1. You may copy and distribute verbatim copies of the Library's complete 144 | source code as you receive it, in any medium, provided that you conspicuously 145 | and appropriately publish on each copy an appropriate copyright notice and 146 | disclaimer of warranty; keep intact all the notices that refer to this License 147 | and to the absence of any warranty; and distribute a copy of this License 148 | along with the Library. 149 | 150 | You may charge a fee for the physical act of transferring a copy, and you may 151 | at your option offer warranty protection in exchange for a fee. 152 | 153 | 2. You may modify your copy or copies of the Library or any portion of it, 154 | thus forming a work based on the Library, and copy and distribute such 155 | modifications or work under the terms of Section 1 above, provided that you 156 | also meet all of these conditions: 157 | 158 | a) The modified work must itself be a software library. 159 | b) You must cause the files modified to carry prominent notices stating 160 | that you changed the files and the date of any change. 161 | c) You must cause the whole of the work to be licensed at no charge to all 162 | third parties under the terms of this License. 163 | d) If a facility in the modified Library refers to a function or a table 164 | of data to be supplied by an application program that uses the facility, other 165 | than as an argument passed when the facility is invoked, then you must make a 166 | good faith effort to ensure that, in the event an application does not supply 167 | such function or table, the facility still operates, and performs whatever 168 | part of its purpose remains meaningful. 169 | 170 | (For example, a function in a library to compute square roots has a 171 | purpose that is entirely well-defined independent of the application. 172 | Therefore, Subsection 2d requires that any application-supplied function or 173 | table used by this function must be optional: if the application does not 174 | supply it, the square root function must still compute square roots.) 175 | 176 | These requirements apply to the modified work as a whole. If identifiable 177 | sections of that work are not derived from the Library, and can be reasonably 178 | considered independent and separate works in themselves, then this License, 179 | and its terms, do not apply to those sections when you distribute them as 180 | separate works. But when you distribute the same sections as part of a whole 181 | which is a work based on the Library, the distribution of the whole must be on 182 | the terms of this License, whose permissions for other licensees extend to the 183 | entire whole, and thus to each and every part regardless of who wrote it. 184 | 185 | Thus, it is not the intent of this section to claim rights or contest your 186 | rights to work written entirely by you; rather, the intent is to exercise the 187 | right to control the distribution of derivative or collective works based on 188 | the Library. 189 | 190 | In addition, mere aggregation of another work not based on the Library with 191 | the Library (or with a work based on the Library) on a volume of a storage or 192 | distribution medium does not bring the other work under the scope of this 193 | License. 194 | 195 | 3. You may opt to apply the terms of the ordinary GNU General Public License 196 | instead of this License to a given copy of the Library. To do this, you must 197 | alter all the notices that refer to this License, so that they refer to the 198 | ordinary GNU General Public License, version 2, instead of to this License. 199 | (If a newer version than version 2 of the ordinary GNU General Public License 200 | has appeared, then you can specify that version instead if you wish.) Do not 201 | make any other change in these notices. 202 | 203 | Once this change is made in a given copy, it is irreversible for that copy, so 204 | the ordinary GNU General Public License applies to all subsequent copies and 205 | derivative works made from that copy. 206 | 207 | This option is useful when you wish to copy part of the code of the Library 208 | into a program that is not a library. 209 | 210 | 4. You may copy and distribute the Library (or a portion or derivative of it, 211 | under Section 2) in object code or executable form under the terms of Sections 212 | 1 and 2 above provided that you accompany it with the complete corresponding 213 | machine-readable source code, which must be distributed under the terms of 214 | Sections 1 and 2 above on a medium customarily used for software interchange. 215 | 216 | If distribution of object code is made by offering access to copy from a 217 | designated place, then offering equivalent access to copy the source code from 218 | the same place satisfies the requirement to distribute the source code, even 219 | though third parties are not compelled to copy the source along with the 220 | object code. 221 | 222 | 5. A program that contains no derivative of any portion of the Library, but is 223 | designed to work with the Library by being compiled or linked with it, is 224 | called a "work that uses the Library". Such a work, in isolation, is not a 225 | derivative work of the Library, and therefore falls outside the scope of this 226 | License. 227 | 228 | However, linking a "work that uses the Library" with the Library creates an 229 | executable that is a derivative of the Library (because it contains portions 230 | of the Library), rather than a "work that uses the library". The executable is 231 | therefore covered by this License. Section 6 states terms for distribution of 232 | such executables. 233 | 234 | When a "work that uses the Library" uses material from a header file that is 235 | part of the Library, the object code for the work may be a derivative work of 236 | the Library even though the source code is not. Whether this is true is 237 | especially significant if the work can be linked without the Library, or if 238 | the work is itself a library. The threshold for this to be true is not 239 | precisely defined by law. 240 | 241 | If such an object file uses only numerical parameters, data structure layouts 242 | and accessors, and small macros and small inline functions (ten lines or less 243 | in length), then the use of the object file is unrestricted, regardless of 244 | whether it is legally a derivative work. (Executables containing this object 245 | code plus portions of the Library will still fall under Section 6.) 246 | 247 | Otherwise, if the work is a derivative of the Library, you may distribute the 248 | object code for the work under the terms of Section 6. Any executables 249 | containing that work also fall under Section 6, whether or not they are linked 250 | directly with the Library itself. 251 | 252 | 6. As an exception to the Sections above, you may also combine or link a "work 253 | that uses the Library" with the Library to produce a work containing portions 254 | of the Library, and distribute that work under terms of your choice, provided 255 | that the terms permit modification of the work for the customer's own use and 256 | reverse engineering for debugging such modifications. 257 | 258 | You must give prominent notice with each copy of the work that the Library is 259 | used in it and that the Library and its use are covered by this License. You 260 | must supply a copy of this License. If the work during execution displays 261 | copyright notices, you must include the copyright notice for the Library among 262 | them, as well as a reference directing the user to the copy of this License. 263 | Also, you must do one of these things: 264 | 265 | a) Accompany the work with the complete corresponding machine-readable 266 | source code for the Library including whatever changes were used in the work 267 | (which must be distributed under Sections 1 and 2 above); and, if the work is 268 | an executable linked with the Library, with the complete machine-readable 269 | "work that uses the Library", as object code and/or source code, so that the 270 | user can modify the Library and then relink to produce a modified executable 271 | containing the modified Library. (It is understood that the user who changes 272 | the contents of definitions files in the Library will not necessarily be able 273 | to recompile the application to use the modified definitions.) 274 | b) Use a suitable shared library mechanism for linking with the Library. A 275 | suitable mechanism is one that (1) uses at run time a copy of the library 276 | already present on the user's computer system, rather than copying library 277 | functions into the executable, and (2) will operate properly with a modified 278 | version of the library, if the user installs one, as long as the modified 279 | version is interface-compatible with the version that the work was made with. 280 | c) Accompany the work with a written offer, valid for at least three 281 | years, to give the same user the materials specified in Subsection 6a, above, 282 | for a charge no more than the cost of performing this distribution. 283 | d) If distribution of the work is made by offering access to copy from a 284 | designated place, offer equivalent access to copy the above specified 285 | materials from the same place. 286 | e) Verify that the user has already received a copy of these materials or 287 | that you have already sent this user a copy. 288 | 289 | For an executable, the required form of the "work that uses the Library" must 290 | include any data and utility programs needed for reproducing the executable 291 | from it. However, as a special exception, the materials to be distributed need 292 | not include anything that is normally distributed (in either source or binary 293 | form) with the major components (compiler, kernel, and so on) of the operating 294 | system on which the executable runs, unless that component itself accompanies 295 | the executable. 296 | 297 | It may happen that this requirement contradicts the license restrictions of 298 | other proprietary libraries that do not normally accompany the operating 299 | system. Such a contradiction means you cannot use both them and the Library 300 | together in an executable that you distribute. 301 | 302 | 7. You may place library facilities that are a work based on the Library 303 | side-by-side in a single library together with other library facilities not 304 | covered by this License, and distribute such a combined library, provided that 305 | the separate distribution of the work based on the Library and of the other 306 | library facilities is otherwise permitted, and provided that you do these two 307 | things: 308 | 309 | a) Accompany the combined library with a copy of the same work based on 310 | the Library, uncombined with any other library facilities. This must be 311 | distributed under the terms of the Sections above. 312 | b) Give prominent notice with the combined library of the fact that part 313 | of it is a work based on the Library, and explaining where to find the 314 | accompanying uncombined form of the same work. 315 | 316 | 8. You may not copy, modify, sublicense, link with, or distribute the Library 317 | except as expressly provided under this License. Any attempt otherwise to 318 | copy, modify, sublicense, link with, or distribute the Library is void, and 319 | will automatically terminate your rights under this License. However, parties 320 | who have received copies, or rights, from you under this License will not have 321 | their licenses terminated so long as such parties remain in full compliance. 322 | 323 | 9. You are not required to accept this License, since you have not signed it. 324 | However, nothing else grants you permission to modify or distribute the 325 | Library or its derivative works. These actions are prohibited by law if you do 326 | not accept this License. Therefore, by modifying or distributing the Library 327 | (or any work based on the Library), you indicate your acceptance of this 328 | License to do so, and all its terms and conditions for copying, distributing 329 | or modifying the Library or works based on it. 330 | 331 | 10. Each time you redistribute the Library (or any work based on the Library), 332 | the recipient automatically receives a license from the original licensor to 333 | copy, distribute, link with or modify the Library subject to these terms and 334 | conditions. You may not impose any further restrictions on the recipients' 335 | exercise of the rights granted herein. You are not responsible for enforcing 336 | compliance by third parties with this License. 337 | 338 | 11. If, as a consequence of a court judgment or allegation of patent 339 | infringement or for any other reason (not limited to patent issues), 340 | conditions are imposed on you (whether by court order, agreement or otherwise) 341 | that contradict the conditions of this License, they do not excuse you from 342 | the conditions of this License. If you cannot distribute so as to satisfy 343 | simultaneously your obligations under this License and any other pertinent 344 | obligations, then as a consequence you may not distribute the Library at all. 345 | For example, if a patent license would not permit royalty-free redistribution 346 | of the Library by all those who receive copies directly or indirectly through 347 | you, then the only way you could satisfy both it and this License would be to 348 | refrain entirely from distribution of the Library. 349 | 350 | If any portion of this section is held invalid or unenforceable under any 351 | particular circumstance, the balance of the section is intended to apply, and 352 | the section as a whole is intended to apply in other circumstances. 353 | 354 | It is not the purpose of this section to induce you to infringe any patents or 355 | other property right claims or to contest validity of any such claims; this 356 | section has the sole purpose of protecting the integrity of the free software 357 | distribution system which is implemented by public license practices. Many 358 | people have made generous contributions to the wide range of software 359 | distributed through that system in reliance on consistent application of that 360 | system; it is up to the author/donor to decide if he or she is willing to 361 | distribute software through any other system and a licensee cannot impose that 362 | choice. 363 | 364 | This section is intended to make thoroughly clear what is believed to be a 365 | consequence of the rest of this License. 366 | 367 | 12. If the distribution and/or use of the Library is restricted in certain 368 | countries either by patents or by copyrighted interfaces, the original 369 | copyright holder who places the Library under this License may add an explicit 370 | geographical distribution limitation excluding those countries, so that 371 | distribution is permitted only in or among countries not thus excluded. In 372 | such case, this License incorporates the limitation as if written in the body 373 | of this License. 374 | 375 | 13. The Free Software Foundation may publish revised and/or new versions of 376 | the Lesser General Public License from time to time. Such new versions will be 377 | similar in spirit to the present version, but may differ in detail to address 378 | new problems or concerns. 379 | 380 | Each version is given a distinguishing version number. If the Library 381 | specifies a version number of this License which applies to it and "any later 382 | version", you have the option of following the terms and conditions either of 383 | that version or of any later version published by the Free Software 384 | Foundation. If the Library does not specify a license version number, you may 385 | choose any version ever published by the Free Software Foundation. 386 | 387 | 14. If you wish to incorporate parts of the Library into other free programs 388 | whose distribution conditions are incompatible with these, write to the author 389 | to ask for permission. For software which is copyrighted by the Free Software 390 | Foundation, write to the Free Software Foundation; we sometimes make 391 | exceptions for this. Our decision will be guided by the two goals of 392 | preserving the free status of all derivatives of our free software and of 393 | promoting the sharing and reuse of software generally. 394 | 395 | NO WARRANTY 396 | 397 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR 398 | THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE 399 | STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE 400 | LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, 401 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 402 | FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 403 | PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, 404 | YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 405 | 406 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL 407 | ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 408 | THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 409 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE 410 | OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR 411 | DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR 412 | A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH 413 | HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 414 | END OF TERMS AND CONDITIONS 415 | How to Apply These Terms to Your New Libraries 416 | 417 | If you develop a new library, and you want it to be of the greatest possible 418 | use to the public, we recommend making it free software that everyone can 419 | redistribute and change. You can do so by permitting redistribution under 420 | these terms (or, alternatively, under the terms of the ordinary General Public 421 | License). 422 | 423 | To apply these terms, attach the following notices to the library. It is 424 | safest to attach them to the start of each source file to most effectively 425 | convey the exclusion of warranty; and each file should have at least the 426 | "copyright" line and a pointer to where the full notice is found. 427 | 428 | one line to give the library's name and an idea of what it does. 429 | Copyright (C) year name of author 430 | 431 | This library is free software; you can redistribute it and/or 432 | modify it under the terms of the GNU Lesser General Public 433 | License as published by the Free Software Foundation; either 434 | version 2.1 of the License, or (at your option) any later version. 435 | 436 | This library is distributed in the hope that it will be useful, 437 | but WITHOUT ANY WARRANTY; without even the implied warranty of 438 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 439 | Lesser General Public License for more details. 440 | 441 | You should have received a copy of the GNU Lesser General Public 442 | License along with this library; if not, write to the Free Software 443 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 444 | 445 | Also add information on how to contact you by electronic and paper mail. 446 | 447 | You should also get your employer (if you work as a programmer) or your 448 | school, if any, to sign a "copyright disclaimer" for the library, if 449 | necessary. Here is a sample; alter the names: 450 | 451 | Yoyodyne, Inc., hereby disclaims all copyright interest in 452 | the library `Frob' (a library for tweaking knobs) written 453 | by James Random Hacker. 454 | 455 | signature of Ty Coon, 1 April 1990 456 | Ty Coon, President of Vice 457 | 458 | That's all there is to it! 459 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include LICENSE 3 | include MANIFEST.in 4 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================= 2 | python-bitcoinrpc 3 | ================= 4 | 5 | AuthServiceProxy is an improved version of python-jsonrpc. 6 | 7 | It includes the following generic improvements: 8 | 9 | * HTTP connections persist for the life of the AuthServiceProxy object 10 | * sends protocol 'version', per JSON-RPC 1.1 11 | * sends proper, incrementing 'id' 12 | * uses standard Python json lib 13 | * can optionally log all RPC calls and results 14 | * JSON-2.0 batch support 15 | 16 | It also includes the following bitcoin-specific details: 17 | 18 | * sends Basic HTTP authentication headers 19 | * parses all JSON numbers that look like floats as Decimal, 20 | and serializes Decimal values to JSON-RPC connections. 21 | 22 | Installation 23 | ============ 24 | 25 | 1. change the first line of setup.py to point to the directory of your installation of python 2.* 26 | 2. run setup.py 27 | 28 | Note: This will only install bitcoinrpc. If you also want to install jsonrpc to preserve 29 | backwards compatibility, you have to replace 'bitcoinrpc' with 'jsonrpc' in setup.py and run it again. 30 | 31 | Or simply install the library using pip:: 32 | 33 | pip install python-bitcoinrpc 34 | 35 | Example 36 | ======= 37 | .. code:: python 38 | 39 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 40 | 41 | # rpc_user and rpc_password are set in the bitcoin.conf file 42 | rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:8332"%(rpc_user, rpc_password)) 43 | best_block_hash = rpc_connection.getbestblockhash() 44 | print(rpc_connection.getblock(best_block_hash)) 45 | 46 | # batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips: 47 | commands = [ [ "getblockhash", height] for height in range(100) ] 48 | block_hashes = rpc_connection.batch_(commands) 49 | blocks = rpc_connection.batch_([ [ "getblock", h ] for h in block_hashes ]) 50 | block_times = [ block["time"] for block in blocks ] 51 | print(block_times) 52 | 53 | Logging all RPC calls to stderr 54 | =============================== 55 | .. code:: python 56 | 57 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 58 | import logging 59 | 60 | logging.basicConfig() 61 | logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG) 62 | 63 | rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:8332"%(rpc_user, rpc_password)) 64 | print(rpc_connection.getinfo()) 65 | 66 | Produces output on stderr like 67 | 68 | DEBUG:BitcoinRPC:-1-> getinfo [] 69 | DEBUG:BitcoinRPC:<-1- {"connections": 8, ...etc } 70 | 71 | Socket timeouts under heavy load 72 | ================================ 73 | Pass the timeout argument to prevent "socket timed out" exceptions: 74 | 75 | .. code:: python 76 | 77 | rpc_connection = AuthServiceProxy( 78 | "http://%s:%s@%s:%s"%(rpc_user, rpc_password, rpc_host, rpc_port), 79 | timeout=120) 80 | -------------------------------------------------------------------------------- /bitcoinrpc/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | 3 | -------------------------------------------------------------------------------- /bitcoinrpc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jgarzik/python-bitcoinrpc/c5527bcdd0b1d98dd9d785729f52337f5bb44a16/bitcoinrpc/__init__.py -------------------------------------------------------------------------------- /bitcoinrpc/authproxy.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Copyright 2011 Jeff Garzik 4 | 5 | AuthServiceProxy has the following improvements over python-jsonrpc's 6 | ServiceProxy class: 7 | 8 | - HTTP connections persist for the life of the AuthServiceProxy object 9 | (if server supports HTTP/1.1) 10 | - sends protocol 'version', per JSON-RPC 1.1 11 | - sends proper, incrementing 'id' 12 | - sends Basic HTTP authentication headers 13 | - parses all JSON numbers that look like floats as Decimal 14 | - uses standard Python json lib 15 | 16 | Previous copyright, from python-jsonrpc/jsonrpc/proxy.py: 17 | 18 | Copyright (c) 2007 Jan-Klaas Kollhof 19 | 20 | This file is part of jsonrpc. 21 | 22 | jsonrpc is free software; you can redistribute it and/or modify 23 | it under the terms of the GNU Lesser General Public License as published by 24 | the Free Software Foundation; either version 2.1 of the License, or 25 | (at your option) any later version. 26 | 27 | This software is distributed in the hope that it will be useful, 28 | but WITHOUT ANY WARRANTY; without even the implied warranty of 29 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 30 | GNU Lesser General Public License for more details. 31 | 32 | You should have received a copy of the GNU Lesser General Public License 33 | along with this software; if not, write to the Free Software 34 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 35 | """ 36 | 37 | try: 38 | import http.client as httplib 39 | except ImportError: 40 | import httplib 41 | import base64 42 | import decimal 43 | import json 44 | import logging 45 | try: 46 | import urllib.parse as urlparse 47 | except ImportError: 48 | import urlparse 49 | 50 | USER_AGENT = "AuthServiceProxy/0.1" 51 | 52 | HTTP_TIMEOUT = 30 53 | 54 | log = logging.getLogger("BitcoinRPC") 55 | 56 | class JSONRPCException(Exception): 57 | def __init__(self, rpc_error): 58 | parent_args = [] 59 | try: 60 | parent_args.append(rpc_error['message']) 61 | except: 62 | pass 63 | Exception.__init__(self, *parent_args) 64 | self.error = rpc_error 65 | self.code = rpc_error['code'] if 'code' in rpc_error else None 66 | self.message = rpc_error['message'] if 'message' in rpc_error else None 67 | 68 | def __str__(self): 69 | return '%d: %s' % (self.code, self.message) 70 | 71 | def __repr__(self): 72 | return '<%s \'%s\'>' % (self.__class__.__name__, self) 73 | 74 | 75 | def EncodeDecimal(o): 76 | if isinstance(o, decimal.Decimal): 77 | return float(round(o, 8)) 78 | raise TypeError(repr(o) + " is not JSON serializable") 79 | 80 | class AuthServiceProxy(object): 81 | __id_count = 0 82 | 83 | def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, 84 | connection=None, ssl_context=None): 85 | self.__service_url = service_url 86 | self.__service_name = service_name 87 | self.__url = urlparse.urlparse(service_url) 88 | if self.__url.port is None: 89 | port = 80 90 | else: 91 | port = self.__url.port 92 | (user, passwd) = (self.__url.username, self.__url.password) 93 | try: 94 | user = user.encode('utf8') 95 | except AttributeError: 96 | pass 97 | try: 98 | passwd = passwd.encode('utf8') 99 | except AttributeError: 100 | pass 101 | authpair = user + b':' + passwd 102 | self.__auth_header = b'Basic ' + base64.b64encode(authpair) 103 | 104 | self.__timeout = timeout 105 | 106 | if connection: 107 | # Callables re-use the connection of the original proxy 108 | self.__conn = connection 109 | elif self.__url.scheme == 'https': 110 | self.__conn = httplib.HTTPSConnection(self.__url.hostname, port, 111 | timeout=timeout, context=ssl_context) 112 | else: 113 | self.__conn = httplib.HTTPConnection(self.__url.hostname, port, 114 | timeout=timeout) 115 | 116 | def __getattr__(self, name): 117 | if name.startswith('__') and name.endswith('__'): 118 | # Python internal stuff 119 | raise AttributeError 120 | if self.__service_name is not None: 121 | name = "%s.%s" % (self.__service_name, name) 122 | return AuthServiceProxy(self.__service_url, name, self.__timeout, self.__conn) 123 | 124 | def __call__(self, *args): 125 | AuthServiceProxy.__id_count += 1 126 | 127 | log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self.__service_name, 128 | json.dumps(args, default=EncodeDecimal))) 129 | postdata = json.dumps({'version': '1.1', 130 | 'method': self.__service_name, 131 | 'params': args, 132 | 'id': AuthServiceProxy.__id_count}, default=EncodeDecimal) 133 | self.__conn.request('POST', self.__url.path, postdata, 134 | {'Host': self.__url.hostname, 135 | 'User-Agent': USER_AGENT, 136 | 'Authorization': self.__auth_header, 137 | 'Content-type': 'application/json'}) 138 | self.__conn.sock.settimeout(self.__timeout) 139 | 140 | response = self._get_response() 141 | if response.get('error') is not None: 142 | raise JSONRPCException(response['error']) 143 | elif 'result' not in response: 144 | raise JSONRPCException({ 145 | 'code': -343, 'message': 'missing JSON-RPC result'}) 146 | 147 | return response['result'] 148 | 149 | def batch_(self, rpc_calls): 150 | """Batch RPC call. 151 | Pass array of arrays: [ [ "method", params... ], ... ] 152 | Returns array of results. 153 | """ 154 | batch_data = [] 155 | for rpc_call in rpc_calls: 156 | AuthServiceProxy.__id_count += 1 157 | m = rpc_call.pop(0) 158 | batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) 159 | 160 | postdata = json.dumps(batch_data, default=EncodeDecimal) 161 | log.debug("--> "+postdata) 162 | self.__conn.request('POST', self.__url.path, postdata, 163 | {'Host': self.__url.hostname, 164 | 'User-Agent': USER_AGENT, 165 | 'Authorization': self.__auth_header, 166 | 'Content-type': 'application/json'}) 167 | results = [] 168 | responses = self._get_response() 169 | if isinstance(responses, (dict,)): 170 | if ('error' in responses) and (responses['error'] is not None): 171 | raise JSONRPCException(responses['error']) 172 | raise JSONRPCException({ 173 | 'code': -32700, 'message': 'Parse error'}) 174 | for response in responses: 175 | if response['error'] is not None: 176 | raise JSONRPCException(response['error']) 177 | elif 'result' not in response: 178 | raise JSONRPCException({ 179 | 'code': -343, 'message': 'missing JSON-RPC result'}) 180 | else: 181 | results.append(response['result']) 182 | return results 183 | 184 | def _get_response(self): 185 | http_response = self.__conn.getresponse() 186 | if http_response is None: 187 | raise JSONRPCException({ 188 | 'code': -342, 'message': 'missing HTTP response from server'}) 189 | 190 | content_type = http_response.getheader('Content-Type') 191 | if not content_type.startswith('application/json'): 192 | raise JSONRPCException({ 193 | 'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)}) 194 | 195 | responsedata = http_response.read().decode('utf8') 196 | response = json.loads(responsedata, parse_float=decimal.Decimal) 197 | if "error" in response and response["error"] is None: 198 | log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal))) 199 | else: 200 | log.debug("<-- "+responsedata) 201 | return response 202 | -------------------------------------------------------------------------------- /jsonrpc/__init__.py: -------------------------------------------------------------------------------- 1 | from .json import loads, dumps, JSONEncodeException, JSONDecodeException 2 | from jsonrpc.proxy import ServiceProxy, JSONRPCException 3 | -------------------------------------------------------------------------------- /jsonrpc/authproxy.py: -------------------------------------------------------------------------------- 1 | from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException 2 | 3 | __all__ = ['AuthServiceProxy', 'JSONRPCException'] 4 | -------------------------------------------------------------------------------- /jsonrpc/json.py: -------------------------------------------------------------------------------- 1 | _json = __import__('json') 2 | loads = _json.loads 3 | dumps = _json.dumps 4 | if hasattr(_json, 'JSONEncodeException'): 5 | JSONEncodeException = _json.JSONEncodeException 6 | JSONDecodeException = _json.JSONDecodeException 7 | else: 8 | JSONEncodeException = TypeError 9 | JSONDecodeException = ValueError 10 | -------------------------------------------------------------------------------- /jsonrpc/proxy.py: -------------------------------------------------------------------------------- 1 | from bitcoinrpc.authproxy import AuthServiceProxy as ServiceProxy, JSONRPCException 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | setup( 6 | name='python-bitcoinrpc', 7 | version='1.0', 8 | description='Enhanced version of python-jsonrpc for use with Bitcoin', 9 | long_description=open('README.rst').read(), 10 | author='Jeff Garzik', 11 | author_email='', 12 | maintainer='Jeff Garzik', 13 | maintainer_email='', 14 | url='http://www.github.com/jgarzik/python-bitcoinrpc', 15 | packages=['bitcoinrpc'], 16 | classifiers=[ 17 | 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent' 18 | ] 19 | ) 20 | --------------------------------------------------------------------------------