Giter Site home page Giter Site logo

python-bitcoinrpc's Introduction

python-bitcoinrpc

AuthServiceProxy is an improved version of python-jsonrpc.

It includes the following generic improvements:

  • HTTP connections persist for the life of the AuthServiceProxy object
  • sends protocol 'version', per JSON-RPC 1.1
  • sends proper, incrementing 'id'
  • uses standard Python json lib
  • can optionally log all RPC calls and results
  • JSON-2.0 batch support

It also includes the following bitcoin-specific details:

  • sends Basic HTTP authentication headers
  • parses all JSON numbers that look like floats as Decimal, and serializes Decimal values to JSON-RPC connections.

Installation

  1. change the first line of setup.py to point to the directory of your installation of python 2.*
  2. run setup.py

Note: This will only install bitcoinrpc. If you also want to install jsonrpc to preserve backwards compatibility, you have to replace 'bitcoinrpc' with 'jsonrpc' in setup.py and run it again.

Or simply install the library using pip:

pip install python-bitcoinrpc

Example

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))
best_block_hash = rpc_connection.getbestblockhash()
print(rpc_connection.getblock(best_block_hash))

# batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
commands = [ [ "getblockhash", height] for height in range(100) ]
block_hashes = rpc_connection.batch_(commands)
blocks = rpc_connection.batch_([ [ "getblock", h ] for h in block_hashes ])
block_times = [ block["time"] for block in blocks ]
print(block_times)

Logging all RPC calls to stderr

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import logging

logging.basicConfig()
logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)

rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))
print(rpc_connection.getinfo())

Produces output on stderr like

DEBUG:BitcoinRPC:-1-> getinfo [] DEBUG:BitcoinRPC:<-1- {"connections": 8, ...etc }

Socket timeouts under heavy load

Pass the timeout argument to prevent "socket timed out" exceptions:

rpc_connection = AuthServiceProxy(
    "http://%s:%s@%s:%s"%(rpc_user, rpc_password, rpc_host, rpc_port),
    timeout=120)

python-bitcoinrpc's People

Contributors

alecalve avatar arnuschky avatar devurandom avatar eggpool avatar ethers avatar gavinandresen avatar jgarzik avatar kaniini avatar laanwj avatar loader-bsd avatar luke-jr avatar matmaer avatar mrvdb avatar nikcub avatar ouillie avatar serafintech avatar thebluematt avatar tigernd 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-bitcoinrpc's Issues

how to install?

$ python setup.py 
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: no commands supplied

Readme doesn't really tell me what I have to do.

[SOLVED] Cannot import python-bitcoinrpc

I am unable to import the package bitcoinrpc.

I have installed it in python2 and python3 using python3 -m pip python-bitcoinrpc/python -m pip python-bitcoinrpc AND by cloning the repo and editing the python environment in setup.py to my python2 and 3 path. Even after that I get the following errors:

Python2: ImportError: No module named authproxy
Python3: ModuleNotFoundError: No module named 'bitcoinrpc.authproxy'; 'bitcoinrpc' is not a package

Following is my code:

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_user = "xxx"
rpc_password = "xxx"
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))

print(rpc_connection.get_info())

I have searched as much as i could but, cannot find anyting except for this bitcoin stackexchange question without an answer.

Is the setup broken or am I missing something?

Any help is appreciated. Thank you!

authentication in example outdated?

Authentication in the example did not work for me:
# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))

Instead I followed this source:
https://github.com/bitcoin/bitcoin/blob/master/doc/JSON-RPC-interface.md#json-rpc-interface

Secure authentication: By default, Bitcoin Core generates unique login credentials each time it restarts and puts them into a file readable only by the user that started Bitcoin Core, allowing any of that user's RPC clients with read access to the file to login automatically. The file is .cookie in the Bitcoin Core configuration directory, and using these credentials is the preferred RPC authentication method. If you need to generate static login credentials for your programs, you can use the script in the share/rpcauth directory in the Bitcoin Core source tree. As a final fallback, you can directly use manually-chosen rpcuser and rpcpassword configuration parameters---but you must ensure that you choose a strong and unique passphrase (and still don't use insecure networks, as mentioned above).

The cookie-method worked for me. With the this mehtod, the example would look like this::
#The file .cookie in the Bitcoin Core configuration directory specifies your login credentials each time bitcoin core is started
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%("__cookie__", "yourpassword")

RPC connection note closed

Hi, I have many threads in my wallet after using your code.
Is it possible to call connection.close somewhere?
Or should I use the more pythonic with?

My code is as follows:

class BaseRpcClient(BaseApiClient):

    def __init__(self):
        super(BaseRpcClient, self).__init__()
        self.api_cache = {}
        self.rpc_endpoint = None

    def get_api(self, node):
        self.rpc_endpoint = RpcMapper.get_rpc_addr(node)
        if self.rpc_endpoint not in self.api_cache:
            self.api_cache[self.rpc_endpoint] = \
                AuthServiceProxy(self.rpc_endpoint)
        self.api = self.api_cache[self.rpc_endpoint]
        return self.api

    def call_api(self, node, endpoint, *args):
        api = self.get_api(node)
        try:
            fn = getattr(api, endpoint)
            return fn(*args)
        except JSONRPCException as e:
            self.logger.error('JSON RPC ERROR HOST {} ERROR {}'
                              .format(self.rpc_endpoint, str(e)))

pip python-bitcoinrpc is not up-to-date

Specifically is missing this commit:

8c0114b

My experience:
sudo pip install python-bitcoinrpc

Then running this script:

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%("USER","PW"))
print(rpc_connection.getinfo())

simply outputs:
None

After editing /usr/local/lib/python2.7/dist-packages/bitcoinrpc/authproxy.py manually removing the "else" in line 146, the same script produces better results:

{u'connections': 10, u'errors': u'', u'blocks': 393219, u'paytxfee': Decimal('0E-8'), u'keypoololdest': 1451977259, u'walletversion': 60000, u'difficulty': Decimal('113354299801.47113037'), u'testnet': False, u'version': 110000, u'proxy': u'', u'protocolversion': 70010, u'timeoffset': -1, u'balance': Decimal('0E-8'), u'unlocked_until': 0, u'relayfee': Decimal('0.00005000'), u'keypoolsize': 101}

python-bitcoinrpc not in PyPi

This cannot be installed with pip (python package & dependency manager) since it is not in PyPi.

The ability to register the package with pypi was added in this pull request:
#7

All that should be needed is mentioned in that pull request, specifically
python setup.py register sdist upload

Remote end closed connection without response

return self.client.getblockchaininfo()
File "/root/python/walletserver/exjrpc/authproxy.py", line 140, in call
response = self._get_response()
File "/root/python/walletserver/exjrpc/authproxy.py", line 184, in _get_response
http_response = self.__conn.getresponse()
File "/usr/local/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/usr/local/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.6/http/client.py", line 266, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

when i request the bitcoin remote client firstly, it throw this exception.

socket.timeout: timed out

Under Python 3.3, Ubuntu 14.04 I use the following code:
from bitcoinrpc.authproxy import AuthServiceProxy
x = AuthServiceProxy("....")
x.rpc_calls(...)

The Bitcoin RPC version I'm using is from the latest master branch.

Anyway, here is my observation: After making at least one successful RPC call the library will randomly throw a timeout exception that looks like this:
Original exception was:
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.3/dist-packages/bitcoinrpc/authproxy.py", line 116, in call
response = self._get_response()
File "/usr/local/lib/python3.3/dist-packages/bitcoinrpc/authproxy.py", line 138, in _get_response
http_response = self.__conn.getresponse()
File "/usr/lib/python3.3/http/client.py", line 1147, in getresponse
response.begin()
File "/usr/lib/python3.3/http/client.py", line 358, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.3/http/client.py", line 320, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.3/socket.py", line 297, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out

I'm just wondering what the reason is for the timeout. It seems my Bitcoind daemon is never actually down. After the timeout occurs I can't issue any more RPC commands without the same exception but if I immediately reconnect with x = AuthServiceProxy("....") and issue the same failed RPC call it ends up working.

An obvious fix is to use a wrapper, but I'm wondering if it's a problem with this library or what reasons there are for this error.

I have confirmed the bug exists under multiple Python versions and multiple coind versions (hosted locally and remotely.) The RPC connection doesn't necessarily need to be open for a long time before the timeout occurs and there doesn't seem to be any pattern to the error.

TypeError: string indices must be integers

Hi,

Getting errors on the batch example. This is in Python 2.7.

>>> commands = [ [ "getblockhash", height] for height in range(100) ]
>>> block_hashes = rpc_connection.batch_(commands)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/bitcoinrpc/authproxy.py", line 169, in batch_
    if response['error'] is not None:
TypeError: string indices must be integers

decimal.InvalidOperation exception

I'm regularly calling getnetworkhashps(-1) to keep track of the network's estimated hash power for the current difficulty adjustment period. At the latest difficulty adjustment, around block 566,496 it temporarily peeked at "3.385206289794399E+20". Function EncodeDecimal couldn't handle numbers this big, and raised an exception:

Traceback (most recent call last):
  File "my_btc_test.py", line 19, in <module>
    networkhashps = rpc_connection.getnetworkhashps(-1)
  File "bitcoinrpc/authproxy.py", line 139, in __call__
    response = self._get_response()
  File "bitcoinrpc/authproxy.py", line 197, in _get_response
    log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
  File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "bitcoinrpc/authproxy.py", line 77, in EncodeDecimal
    return float(round(o, 8))
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

I've reproduced the error with a simple example. The following code throws the same exception demonstrating the problem:

#!/usr/bin/python3
import decimal
o = decimal.Decimal("3.385206289794399E+20")
print(float(round(o, 8)))

A possible solution

Please consider merging @luke-jr's #63, that solves the issue.

OSError: [Errno 113] No route to host

hi
i have a windows pc in my lan (i have a qt-wallet installed and running), when i try to do a getinfo call from my laptop it give me this "OSError: [Errno 113] No route to host" but it's online how can i resolve this?
i set a "server=1" parameter and rpcallowip= in bitcoin.conf

License terms are not explicit

The docstring in authproxy.py mentions that there is a "Previous copyright, from python-jsonrpc/jsonrpc/proxy.py", which refers to the "GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version."

So, I suppose I can reasonably assume that python-bitcoinrpc is at least compatible with LGPL v2.1 or later. However, this still leaves some room for unclarity; I don't think that, the way it is now, I can be 100% certain that all of python-bitcoinrpc is available under LGPL v2.1 or later.

If it is the intention of all contributors to release their contributions under LGPL v2.1 or later (I hope this is the case), then please make it explicit.

Also, as a minor note: since the docstring says "You should have received a copy of the GNU Lesser General Public License along with this software", I think you should actually include a copy of the LGPL in the source tree.

add tests?

Hi, i'm wondering why this lib do not include tests.
Probably it will be good to "mock" from answers from bitcoin client.

HD wallet

with the latest version of bitcoind hd wallets are now available, is the python-bitcoinrpc compaitable with hd walllets?

authproxy failure under python 2.7.6

File "/home/ubuntu/appengine/apps/gethtoys/lib/bitcoinrpc/authproxy.py", line 137, in call
self.__conn.sock.settimeout(self.__timeout)
AttributeError: HTTPConnection instance has no attribute 'sock'

Works fine when I comment out line 137.

What am I missing?

401 Unauthorized

File "censored", line 197, in _get_response
raise JSONRPCException({
bitcoinrpc.authproxy.JSONRPCException: -342: non-JSON HTTP response with '401 Unauthorized' from server

Module causes RuntimeError, most methods unusable

Running in Python 3.4.3 on ubuntu linux.

Setup - copied directly from the Readme:

# python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
>>> import logging
>>> logging.basicConfig()
>>> logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)
>>> rpc_connection = AuthServiceProxy("http://bobby:[email protected]:6969")

Using getinfo() causes an error:

>>> print(rpc_connection.getinfo())
DEBUG:BitcoinRPC:-1-> getinfo []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 136, in __call__
    response = self._get_response()
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 184, in _get_response
    log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
  File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 77, in EncodeDecimal
    return round(o, 8)
  File "/usr/lib/python3.4/decimal.py", line 1878, in __round__
    return self.quantize(exp)
  File "/usr/lib/python3.4/decimal.py", line 2572, in quantize
    return ans._fix(context)
  File "/usr/lib/python3.4/decimal.py", line 1686, in _fix
    return Decimal(self)
  File "/usr/lib/python3.4/decimal.py", line 589, in __new__
    if isinstance(value, str):
RuntimeError: maximum recursion depth exceeded while calling a Python object

getaddressesbyaccount works:

>>> rpc_connection.getaddressesbyaccount('')
DEBUG:BitcoinRPC:-2-> getaddressesbyaccount [""]
DEBUG:BitcoinRPC:<-2- ["<snip>"]
['<snip>']

But not getbalance:

>>> rpc_connection.getbalance('')
DEBUG:BitcoinRPC:-3-> getbalance [""]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 136, in __call__
    response = self._get_response()
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 184, in _get_response
    log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
  File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/pbot/botenv/lib/python3.4/site-packages/bitcoinrpc/authproxy.py", line 77, in EncodeDecimal
    return round(o, 8)
  File "/usr/lib/python3.4/decimal.py", line 1878, in __round__
    return self.quantize(exp)
  File "/usr/lib/python3.4/decimal.py", line 2572, in quantize
    return ans._fix(context)
  File "/usr/lib/python3.4/decimal.py", line 1686, in _fix
    return Decimal(self)
  File "/usr/lib/python3.4/decimal.py", line 589, in __new__
    if isinstance(value, str):
RuntimeError: maximum recursion depth exceeded while calling a Python object

Option to get raw json response?

Is there a clean way to have an api/option to get the raw json response (as string or better yet bytes for python3) instead of the pythonified version?

batch call parsing does not conform to JSON-RPC 2.0 standard

AuthProxy.batch_() should use ids to match responses with requests.

According to https://www.jsonrpc.org/specification: "The Response objects being returned from a batch call MAY be returned in any order within the Array. The Client SHOULD match contexts between the set of Request objects and the resulting set of Response objects based on the id member within each Object."

Now it is assumed that the server will keep the order the same.

Error using pypy

Hello, I use this component and try to run it under Pypy, but the installation package gives an error

root@ubuntu-PowerEdge-R740:~/py3.7/bin# ./pypy3.7 -m pip install bitcoinrpc
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting bitcoinrpc
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ba/02/c71fefe1073adcca555f88d1ba11565637f9f40c3b7b9ec24d4387aa3d03/bitcoinrpc-0.3.1-py3-none-any.whl (6.7 kB)
Collecting orjson>=3
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/af/14/e65dcc1d8b557343c9a76b957efe2c634ebfdf072f721865f3510d89686b/orjson-3.5.1.tar.gz (659 kB)
     |████████████████████████████████| 659 kB 65 kB/s 
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: /root/py3.7/bin/pypy3.7 /root/py3.7/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpf6jjoe6t
         cwd: /tmp/pip-install-_cfb6pak/orjson_b387ac41d56245579bf6c006d66a4e29
    Complete output (11 lines):
    aturin failed
      Caused by: Cargo metadata failed. Do you have cargo in your PATH?
      Caused by: failed to run `cargo metadata`: error: failed to run `rustc` to learn about target-specific information
    
    Caused by:
      process didn't exit successfully: `rustc - --crate-name ___ --print=file-names -Z mutable-noalias --crate-type bin --crate-type rlib --crate-type dylib --crate-type cdylib --crate-type staticlib --crate-type proc-macro --print=sysroot --print=cfg` (exit code: 1)
      --- stderr
      error: the option `Z` is only accepted on the nightly compiler
    Checking for Rust toolchain....
    Running `maturin pep517 write-dist-info --metadata-directory /tmp/pip-modern-metadata-9i6ul0_f --interpreter /root/py3.7/bin/pypy3.7 --manylinux=off --strip=on`
    Error: Command '['maturin', 'pep517', 'write-dist-info', '--metadata-directory', '/tmp/pip-modern-metadata-9i6ul0_f', '--interpreter', '/root/py3.7/bin/pypy3.7', '--manylinux=off', '--strip=on']' returned non-zero exit status 1.
    ----------------------------------------
WARNING: Discarding https://pypi.tuna.tsinghua.edu.cn/packages/af/14/e65dcc1d8b557343c9a76b957efe2c634ebfdf072f721865f3510d89686b/orjson-3.5.1.tar.gz#sha256=7d3c4179d7af8a39fa1e3b4125155e866e09b24e477c7663ef951dcb6d8ee97d (from https://pypi.tuna.tsinghua.edu.cn/simple/orjson/) (requires-python:>=3.6). Command errored out with exit status 1: /root/py3.7/bin/pypy3.7 /root/py3.7/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpf6jjoe6t Check the logs for full command output.
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/eb/ea/1d256e890db7927fe8454bced23c309184f2ce425d16b30af4182c58a05e/orjson-3.5.0.tar.gz (659 kB)
     |████████████████████████████████| 659 kB 1.4 MB/s 
  Installing build dependencies ... done

E

nvm

Question/ Feature Request

I am sorry, don't know where to ask this. Maybe it is an issue in terms of a missing entry in the readme:

How am I supposed to install this?

I downloaded the zip with wget, unpacked it and ran

sudo ./setup build
sudo ./setup install

after changing the first line of the script to #!/usr/bin/python.

There is a bitcoinrpc file in my /usr/local/lib/python2.7/dist-packages/ now, but no jsonrpc. It is not surprising that I get the following error:

File "./bitcoinTest.py", line 2, in <module> from jsonrpc import ServiceProxy ImportError: No module named jsonrpc

So it seems jsonrpc is not getting installed? How can I install jsonrpc?

Python Bitcoin-RPC Connection Error?

My node is fully sync'd and operational (I've confirmed via commands with ssh) and I'm hoping to now use python-bitcoinrpc to interact with my node. Unfortunately I didn't get very far. Here is the code I'm running:

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password)) best_block_hash = rpc_connection.getbestblockhash()

Where rpc_user and rpc_password is exactly what's in my bitcoin.conf file.

I disabled the ufw from the Raspibolt setup, but still getting the same error. My hunch is that it has to do with the port and since the Raspibolt setup is with Tor. Here is the info from my bitcoin.conf file:

server=1
txindex=1

# Network
listen=1
listenonion=1
proxy=127.0.0.1:9050
bind=127.0.0.1

# Connections
rpcuser=[rpcuser]
rpcpassword=[rpcpassword]
zmqpubrawblock=tcp://127.0.0.1:28332
zmqpubrawtx=tcp://127.0.0.1:28333


# Raspberry Pi optimizations
maxconnections=40
maxuploadtarget=5000

# Initial block download optimizations
dbcache=2000
blocksonly=1

I've been tweaking the address and port but still receive same error. Obviously a bit of a novice here but hoping to learn more!

Bitcoinrpc has an error with running of eloipool

Dears,

Whenever I running a Eloipool I saw following error on log file.
so I think that error related with bitcoinrpc.

2016-04-30 04:21:11,338 BitcoinRPC DEBUG -1-> getblocktemplate [{"capabilities": ["coinbasevalue", "coinbase/append$
2016-04-30 04:21:11,365 BitcoinRPC DEBUG <-1- {"coinbasevalue": 2527191892, "capabilities": ["proposal"], "sizelimi$
2016-04-30 04:21:11,371 merkleMaker INFO New block: 000000000000000001893e44352e7cd4c7e33d8249068bee3d9ab5f47ae375b$
2016-04-30 04:21:11,372 JSONRPCServer INFO Waiting 15 seconds to longpoll
2016-04-30 04:21:11,381 BitcoinRPC DEBUG -2-> getblocktemplate [{"mode": "proposal", "data": "04000000b575e37af4b59$
2016-04-30 04:21:11,394 BitcoinRPC DEBUG <-2- null
2016-04-30 04:21:11,395 BitcoinRPC DEBUG -3-> getblocktemplate [{"capabilities": ["coinbasevalue", "coinbase/append$
2016-04-30 04:21:11,447 BitcoinRPC DEBUG <-3- {"coinbasevalue": 2527191892, "capabilities": ["proposal"], "sizelimi$
2016-04-30 04:21:11,463 BitcoinRPC DEBUG -4-> getblocktemplate [{"mode": "proposal", "data": "04000000b575e37af4b59$
2016-04-30 04:21:11,476 BitcoinRPC DEBUG <-4- null
2016-04-30 04:21:11,476 merkleMaker CRITICAL Traceback (most recent call last):
File "/eloipoolsrv/merklemaker.py", line 704, in run
self.merkleMaker_I()
File "/eloipoolsrv/merklemaker.py", line 694, in merkleMaker_I
self.merkleMaker_II()
File "/eloipoolsrv/merklemaker.py", line 660, in merkleMaker_II
return self._updateMerkleTree()
File "/eloipoolsrv/merklemaker.py", line 560, in _updateMerkleTree
self._updateMerkleTree_I()
File "/eloipoolsrv/merklemaker.py", line 546, in _updateMerkleTree_I
raise RuntimeError('Failed to create usable template')
RuntimeError: Failed to create usable template

Regards,
John Ahn

Memory error in batch mode

I am getting mempool tx from bitcoind in batch mode and sometimes getting this error:

File "/usr/local/lib/python2.7/dist-packages/bitcoinrpc/authproxy.py", line 164, in batch_
responses = self._get_response()
File "/usr/local/lib/python2.7/dist-packages/bitcoinrpc/authproxy.py", line 186, in _get_response
log.debug("<-- "+responsedata)
MemoryError

Only getting sometimes, most of the times its working properly. Will try to reproduce exactly with a script

Note: harddisk and memory space is on box is normal

New PyPi Version

There's been 3 PRs since 1.0 was released.
Could we get an official PyPi package update?
Thank you.

RPC SSL to btcd

I am trying to use bitcoind-ncurses to connect to btcd. I successfully got bitcoind-ncurses running on my box and had to make a small mod to it for it to support SSL (PRabahy/bitcoind-ncurses@d49a8c4). Even after doing that, I am having trouble getting to to connect.

I am very inexperience with python so began adding print statements to the code and believe I have the bug narrowed down to authproxy.py --> call --> self.__conn.request(...). I see that it makes the call, but never executes the print statement that I added on the next line. I assume that this means that it threw an exception.

I was suspicious of the call to httplib.HTTPSConnection(...) because it was passing None for the cert and key, but even after adding those it is still skipping my print statement.

I would love to eliminate some variables, but I am also having trouble getting bitcoind to run with RPC SSL and btcd requires RPC SSL (no option for insecure).

Cannot read block 9 transaction

Hi,

I was playing with the blochain using the python librairy 'bitcoinrpc' and bitcoin-core, however I can never read the transaction in block 9.

I even downloaded the blockchain a 2nd time thinking mine had a problem with a 2nd installation of bitcoin-core pointing to a different data directory and I still can't read block 9.

can you reproduce this problem? any idea why?

script for reading and displaying block 7, 8, 9, 10 :

from bitcoinrpc.authproxy import AuthServiceProxy
import traceback

RPC_ADDRESS="127.0.0.1:8332"
RPC_USER="u"
RPC_PASSWORD="p"

def display_block_info(rpc, block_number):
    print "-------- block {} start -------".format(block_number)
    block_hash = rpc.getblockhash(block_number)
    print "Block hash : " + block_hash
    block = rpc.getblock(block_hash)
    for tx in block[u'tx']:
        print "processing transaction " + tx
        print rpc.getrawtransaction(tx, True)
    print "-------- block {} end -------".format(block_number)
    print ""

if __name__ == "__main__":
    rpc = AuthServiceProxy("http://%s:%s@%s"%(RPC_USER, RPC_PASSWORD, RPC_ADDRESS))
    block_numbers = [7, 8, 9, 10]
    for block_number in block_numbers:
        try:
            display_block_info(rpc, block_number)
        except Exception as e:
            traceback.print_exc()
            print "-------- block {} end -------".format(block_number)
            print "")

result

-------- block 7 start -------
Block hash : 0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444
processing transaction 8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f
{u'hash': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blockhash': u'0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac', u'addresses': [u'16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM'], u'asm': u'04a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012bffffffff0100f2052a01000000434104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac00000000', u'vin': [{u'coinbase': u'04ffff001d012b', u'sequence': 4294967295L}], u'txid': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blocktime': 1231472369, u'version': 1, u'confirmations': 3677, u'time': 1231472369, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 7 end -------

-------- block 8 start -------
Block hash : 00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6
processing transaction a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3
{u'hash': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blockhash': u'00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac', u'addresses': [u'1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj'], u'asm': u'04cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012cffffffff0100f2052a01000000434104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac00000000', u'vin': [{u'coinbase': u'04ffff001d012c', u'sequence': 4294967295L}], u'txid': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blocktime': 1231472743, u'version': 1, u'confirmations': 3681, u'time': 1231472743, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 8 end -------

-------- block 9 start -------
Block hash : 000000008d9dc510f23c2657fc4f67bea30078cc05a90eb89e84cc475c080805
processing transaction 0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9
Traceback (most recent call last):
  File "blocReader.py", line 24, in <module>
    display_block_info(rpc, block_number)
  File "blocReader.py", line 15, in display_block_info
    print rpc.getrawtransaction(tx, True)
  File "c:\Python27\lib\site-packages\bitcoinrpc\authproxy.py", line 116, in __call__
    raise JSONRPCException(response['error'])
JSONRPCException
-------- block 9 end -------

-------- block 10 start -------
Block hash : 000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9
processing transaction d3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11
{u'hash': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blockhash': u'000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac', u'addresses': [u'15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy'], u'asm': u'04fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425dd OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0136ffffffff0100f2052a01000000434104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac00000000', u'vin': [{u'coinbase': u'04ffff001d0136', u'sequence': 4294967295L}], u'txid': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blocktime': 1231473952, u'version': 1, u'confirmations': 3687, u'time': 1231473952, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 10 end -------

as you can see the transaction '0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9' cannot be read using rpc.getrawtransaction(tx, True)

Thanks.

fix for __init__.py to make it work from within other packages

a quick fix to your python-bitcoinrpc code: in init.py, s/jsonrpc.//
making it look like this:

from json import loads, dumps, JSONEncodeException, JSONDecodeException
from proxy import ServiceProxy, JSONRPCException

doesn't break anything, and makes it work when you stick it inside another package and try to import it (which i do with supybot :) )

Socket timeouts under heavy load

It would be nice if the readme had an easy quickstart option to increase the socket timeout. Under heavy load this happens altogether too regularly:

File "/scratch/tmagik/gztx/bitcoinrpc/authproxy.py", line 179, in _get_response
    http_response = self.__conn.getresponse()
  File "/usr/lib/python3.4/http/client.py", line 1208, in getresponse
    response.begin()
  File "/usr/lib/python3.4/http/client.py", line 380, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.4/http/client.py", line 342, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.4/socket.py", line 374, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

Invalid IPv6 URL

Hello, I am running this in a Jupyter Notebook to test it.

Python - 2.7
My RPC server is on a AWS instance.

I get the following error on this call:
AuthServiceProxy("http://%s:%[email protected]:9009"%(rpc_user, rpc_password))

/anaconda/lib/python2.7/site-packages/bitcoinrpc/authproxy.pyc in init(self, service_url, service_name, timeout, connection)
84 self.__service_url = service_url
85 self.__service_name = service_name
---> 86 self.__url = urlparse.urlparse(service_url)
87 if self.__url.port is None:
88 port = 80

//anaconda/lib/python2.7/urlparse.pyc in urlparse(url, scheme, allow_fragments)
141 Note that we don't break the components up in smaller bits
142 (e.g. netloc is a single string) and we don't expand % escapes."""
--> 143 tuple = urlsplit(url, scheme, allow_fragments)
144 scheme, netloc, url, query, fragment = tuple
145 if scheme in uses_params and ';' in url:

//anaconda/lib/python2.7/urlparse.pyc in urlsplit(url, scheme, allow_fragments)
189 if (('[' in netloc and ']' not in netloc) or
190 (']' in netloc and '[' not in netloc)):
--> 191 raise ValueError("Invalid IPv6 URL")
192 if allow_fragments and '#' in url:
193 url, fragment = url.split('#', 1)

ValueError: Invalid IPv6 URL

How to resolve this?

Broken Pipe please help

Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/discord/client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "bal.py", line 22, in on_message
address = getAddress(account)
File "/root/zbot/tipper/tipper.py", line 21, in getAddress
return con.getaccountaddress(account)
File "/usr/local/lib/python3.6/dist-packages/bitcoinrpc/authproxy.py", line 136, in call
'Content-type': 'application/json'})
File "/usr/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.6/http/client.py", line 1065, in _send_output
self.send(chunk)
File "/usr/lib/python3.6/http/client.py", line 986, in send
self.sock.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe

Please fix the tag

Hi there,

I was trying to use pip to install your project based off the tag. I tried the following:

pip install -e git+https://github.com/jgarzik/[email protected]#egg=bitcoinrpc

This kept failing because your actual tag is v0.3-33-ge484743:

pip install -e git+https://github.com/jgarzik/[email protected]#egg=bitcoinrpc

If you type, "git tag" the tag will appear correctly, however if you run "git describe" on your repo you will see the actual tag. The tag gets into this state if you, cut a tag, and merge something into the existing, after the tag has been set. For more information please see:

https://www.kernel.org/pub/software/scm/git/docs/git-describe.html

I am a release engineer, and I encounter this every release week. :( I added this to my requriements.txt, so if you make any changes, the tag will change to 34 and thus it will break my "pip install -r requirements" command. I'm very big on sharing knowledge, so I hope you don't find this offensive. I just recently found out about this myself.

At work I am trying to get everyone to follow semantic versioning:

http://semver.org/

Perhaps you could just add a 1 at the end of your tag so it would be: 0.3.1

I love the project! Thanks so much for the great work.

Cheers,
Jon

BrokenPipeError: [Errno 32] Broken pipe

Trying to create a raw transaction on the testnet gives the following error:

  File "<pyshell#11>", line 1, in <module>
    con.createrawtransaction([{"txid":"a8fd2dacb674cec804e1cd861c9310d999d6d149fd17d5e44034ed1207860f60","vout":0}], {"myJXY5WznWSLqSoghhieCXfykkZnCz9P1U":1.79})
  File "/usr/local/lib/python3.5/dist-packages/bitcoinrpc/authproxy.py", line 136, in __call__
    'Content-type': 'application/json'})
  File "/usr/lib/python3.5/http/client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 936, in _send_output
    self.send(message_body)
  File "/usr/lib/python3.5/http/client.py", line 908, in send
    self.sock.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe
>>> 

Bug in __call__ related to bitcoind returning a bogus error

bitcoind returns an error when it actually wants to return a warning: bitcoin/bitcoin#7130
This causes a connection result with error=None as shown below. Unfortunately, python-bitcoinrpc misbehaves in this case, neither throwing an exception nor returning the result.

Two ways to fix this:

  • either throw an exception
  • or return the result

The second case works with bitcoind's weird warning behavior. It's fixed by #59

{u'error': None,
 u'id': 1,
 u'result': {u'balance': Decimal('1.69743172'),
             u'blocks': 385893,
             u'connections': 8,
             u'difficulty': Decimal('72722780642.54718018'),
             u'errors': u'Warning: This version is obsolete; upgrade required!',
             u'keypoololdest': 1423141169,
             u'keypoolsize': 10001,
             u'paytxfee': Decimal('0E-8'),
             u'protocolversion': 70002,
             u'proxy': u'',
             u'relayfee': Decimal('0.00005000'),
             u'testnet': False,
             u'timeoffset': 0,
             u'unlocked_until': 0,
             u'version': 110100,
             u'walletversion': 60000}}

bitcoinrpc.authproxy.JSONRPCException: -342: non-JSON HTTP response with '500 Internal Server Error' from server

Hi, I'm using bitcoinrpc to fetch data using multiprocessing in python (20-40 processes at a time).

I'm frequently getting these errors:

exception catched by line 107: Traceback (most recent call last):
  File "mainF_v2_4_blocks.py", line 66, in block_processing
    block_hash = rpc1.getblockhash(block_height)
  File "/home/user/btc_rpc_1/btc_rpc_venv/lib64/python3.6/site-packages/bitcoinrpc/authproxy.py", line 139, in __call__
    response = self._get_response()
  File "/home/user/btc_rpc_1/btc_rpc_venv/lib64/python3.6/site-packages/bitcoinrpc/authproxy.py", line 179, in _get_response
    http_response = self.__conn.getresponse()
  File "/usr/lib64/python3.6/http/client.py", line 1321, in getresponse
    raise ResponseNotReady(self.__state)
http.client.ResponseNotReady: Request-sent
exception catched by line 107: Traceback (most recent call last):
  File "mainF_v2_4_blocks.py", line 66, in block_processing
    block_hash = rpc1.getblockhash(block_height)
  File "/home/user/btc_rpc_1/btc_rpc_venv/lib64/python3.6/site-packages/bitcoinrpc/authproxy.py", line 136, in __call__
    'Content-type': 'application/json'})
  File "/usr/lib64/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib64/python3.6/http/client.py", line 1250, in _send_request
    self.putrequest(method, url, **skips)
  File "/usr/lib64/python3.6/http/client.py", line 1108, in putrequest
    raise CannotSendRequest(self.__state)
http.client.CannotSendRequest: Request-sent

exception catched by line 107: Traceback (most recent call last):
  File "mainF_v2_4_blocks.py", line 67, in block_processing
    block = [json.loads(json.dumps(rpc1.getblock(block_hash), use_decimal=True))]
  File "/home/user/btc_rpc_1/btc_rpc_venv/lib64/python3.6/site-packages/bitcoinrpc/authproxy.py", line 139, in __call__
    response = self._get_response()
  File "/home/user/btc_rpc_1/btc_rpc_venv/lib64/python3.6/site-packages/bitcoinrpc/authproxy.py", line 187, in _get_response
    'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)})
bitcoinrpc.authproxy.JSONRPCException: -342: non-JSON HTTP response with '500 Internal Server Error' from server

Here is timeout setting my connection string:

rpc1 = AuthServiceProxy( "http://%s:%s@%s:%s"%(rpc_user, rpc_password, rpc_host, rpc_port), timeout=86400)

and entry in bitcoin.conf:

rpcthreads=400
rpcworkqueue=1600
rpcservertimeout=7200

What can be the cause the above error? Any suggestions how to handle it? or do I need to change timeout settings?

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.