Package: python-monerorpc
python-monerorpcDISCLAIMER: The repository that should be worked on is located at themonero-ecosystem.python-monerorpcis an improved version of python-jsonrpc for Monero (monerod rpc,monero-wallet-rpc).python-monerorpcwas originally forked frompython-bitcoinrpc.It includes the following generic improvements:HTTP connections persist for the life of theAuthServiceProxyobject usingrequests.Sessionsends protocol 'jsonrpc', per JSON-RPC 2.0sends proper, incrementing 'id'uses standard Python json libcan optionally log all RPC calls and resultsJSON-2.0 batch support (mimicking batch)JSON-2.0 batch doesn't seem to work with monero.The batch functionality is mimicked and just requests the given methods one after another.The result is a list of dictionaries.It also includes some more specific details:sends Digest HTTP authentication headersparses all JSON numbers that look like floats as Decimal,
and serializes Decimal values to JSON-RPC connections.What does it do?python-monerorpccommunicates with monero over RPC.That includes:monerod rpcas well asmonero-wallet-rpc.python-monerorpctakes over the actual HTTP request containing all the necessary headers.Compared to similar projects:monero-pythonmonero-pythonThe module implements a json RPC backend (monerod rpc,monero-wallet-rpc).It implements implementations around this backend (accounts, wallets, transactions, etc. )It offers helpful utilities like a monero wallet address validator.A practical difference:Should a RPC method change or a new one should be added,monero-pythonwould have to adapt its backend and the implementations around it, while withpython-monerorpcyou just have to modify the property or use a new method like:rpc_connection.getbalance()# -> rpc_connection.get_balance()rpc_connection.new_method()ErrorsTheJSONRPCExceptionis thrown in the event of an error.One exception to that rule is when receiving aJSONDecodeErrorwhen converting the response to JSON.
In this case aValueErrorincluding the HTTP response is raised.This error was not handled before and directly raised aJSONDecodeError. SinceJSONDecodeErrorinherits fromValueErrornothing really changes. You should handleValueErrorin addition to justJSONRPCExceptionwhen working withpython-monerorpc.TODO:
An improved error handling.Provide detailed information.Separate into several causes like connection error, conversion error, etc.Installation:From PyPITo installpython-monerorpcfrom PyPI usingpipyou just need to:$ pip install python-monerorpcFrom Source$ python setup.py install --userNote: This will only installmonerorpc. If you also want to installjsonrpcto preserve
backwards compatibility, you have to replacemonerorpcwithjsonrpcinsetup.pyand run it again.Examples:Example usagemonerod(get info):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCException# initialisation, rpc_user and rpc_password are set as flags in the cli commandrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18081/json_rpc'.format(rpc_user,rpc_password))info=rpc_connection.get_info()print(info)# rpc_user and rpc_password can also be left out (testing, develop, not recommended)rpc_connection=AuthServiceProxy(service_url='http://127.0.0.1:18081/json_rpc')Example usagemonerod(special characters in RPC password).This is also the recommended way to use passwords containing special characters likesome_password#-+.When both ways are used (username/password in the URL and passed as arguments), the arguments' values will be predominant.frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCException# When leaving rpc_user and rpc_password in the URL,# you can still pass those values as separate paramaters.rpc_connection=AuthServiceProxy(service_url='http://127.0.0.1:18081/json_rpc',username=rpc_user,password=rpc_password)# Or use both ways.rpc_connection=AuthServiceProxy(service_url='http://{0}@127.0.0.1:18081/json_rpc'.format(rpc_user),password=rpc_password)Example usagemonerod(get network type):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCExceptionrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18081/json_rpc'.format(rpc_user,rpc_password))result=Nonenetwork_type=Nonetry:result=rpc_connection.get_info()except(requests.HTTPError,requests.ConnectionError,JSONRPCException)ase:logger.error('RPC Error on getting address'+str(e))logger.exception(e)# Check network typenetwork_type=result.get('nettype')ifnotnetwork_type:raiseValueError('Error with:{0}'.format(result))print(network_type)Example usagemonerod(on get block hash):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCExceptionrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18081/json_rpc'.format(rpc_user,rpc_password))params=[2]hash=rpc.on_get_block_hash(params)print(hash)Example usagemonero-wallet-rpc(get balance):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCException# initialisation, rpc_user and rpc_password are set as flags in the cli commandrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18083/json_rpc'.format(rpc_user,rpc_password))balance=rpc_connection.get_balance()print(balance)Example usagemonero-wallet-rpc(make transfer):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCException# initialisation, rpc_user and rpc_password are set as flags in the cli commandrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18083/json_rpc'.format(rpc_user,rpc_password))destinations={"destinations":[{"address":"some_address","amount":1}],"mixin":10}result=rpc_connection.transfer(destinations)print(result)Example usagemonero-wallet-rpc(batch):frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCExceptionimportpprint# initialisation, rpc_user and rpc_password are set as flags in the cli commandrpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18083/json_rpc'.format(rpc_user,rpc_password))# some example batchparams={"account_index":0,"address_indices":[0,1]}result=rpc.batch_([["get_balance"],["get_balance",params]])pprint.pprint(result)# make transfer and get balance in a batchdestinations={"destinations":[{"address":"some_address","amount":1}],"mixin":10}result=rpc.batch_([["transfer",destinations],["get_balance"]])pprint.pprint(result)Logging:Logging all RPC calls to stderr:frommonerorpc.authproxyimportAuthServiceProxy,JSONRPCExceptionimportlogginglogging.basicConfig()logging.getLogger("MoneroRPC").setLevel(logging.DEBUG)rpc_connection=AuthServiceProxy(service_url='http://{0}:{1}@127.0.0.1:18081/json_rpc'.format(rpc_user,rpc_password))print(rpc_connection.get_info())Produces output on stderr like:DEBUG:MoneroRPC:-1->get_info[]DEBUG:MoneroRPC:<-1-{u'result':{u'incoming_connections_count':0,...etc}Errors:Possible errors and error codes:no codeReturns theerrorcontained in the RPC response.-341could not establish a connection, original error: {}including the original exception message-342missing HTTP response from server-343missing JSON-RPC result-344received HTTP status code {}including HTTP status code other than200Testing and creatingrequirements.txtYou won't ever need this probably - This is helpful when developing.pip-toolsis used to createrequirements.txt.There isrequirements.inwhere dependencies are set and pinned.To create therequirements.txt, runupdate_requirements.shwhich basically just callspip-compile.Note:There also isbuild_requirements.txtwhich only containspip-tools. I found, when working with virtual environments, it is necessary to installpip-toolsinside the virtual environment as well. Otherwisepip-syncwould install outside the virtual environment.A test and development environment can be created like this:# Create a virtual environment 'venv'.python-mvenvvenv# Activate the virtual environment 'venv'../venv/bin/activate# Install 'pip-tools'.pipinstall--upgrade-rbuild_requirements.txt# Install dependencies.pip-syncrequirements.txt...# Deactivate the virtual environment 'venv'.deactivateRun unit tests usingpytest:# virtualenv activated (see above)pytest-s-v--covmonerorpc/tests.pyRun unit tests on all supported python versions:tox-qRun unit tests on a subset of the supported python versions:tox-q-epy36,py37Note:The chosen python versions have to be installed on your system.AuthorsNorman Moeschter-Schenck-Initial work-normoesSee also the list ofcontributorswho participated in this project.