Code Monkey home page Code Monkey logo

ethjsonrpc's Introduction

ethjsonrpc

Python client for Ethereum using the JSON-RPC interface

  • complete: implements all 62 JSON-RPC methods plus several client-specific methods
  • provides a high-level interface to create contracts on the blockchain and to call contract methods

Important note

The API is not yet stable, so please use caution when upgrading.

Installation

You may need additional libraries and tools before installing ethjsonrpc.

On Ubuntu 20.04:

$ sudo apt install python2-minimal
$ sudo apt install gcc
$ sudo apt install virtualenv  # optional but recommended
$ sudo apt install libpython2-dev
$ sudo apt install libssl-dev

On Ubuntu 16.04:

$ sudo apt install python-minimal
$ sudo apt install gcc
$ sudo apt install virtualenv  # optional but recommended
$ sudo apt install libpython-dev
$ sudo apt install libssl-dev

On Ubuntu 14.04:

$ sudo apt-get install python-virtualenv  # optional but recommended
$ sudo apt-get install libpython-dev
$ sudo apt-get install libssl-dev

To install ethjsonrpc:

$ pip install ethjsonrpc

Make sure to have a node running an Ethereum client (such as geth) for the library to connect to.

Example

>>> from ethjsonrpc import EthJsonRpc  # to use Parity-specific methods, import ParityEthJsonRpc
>>> c = EthJsonRpc('127.0.0.1', 8545)
>>> c.net_version()
u'1'
>>> c.web3_clientVersion()
u'Geth/v1.3.3/linux/go1.5.1'
>>> c.eth_gasPrice()
50000000000
>>> c.eth_blockNumber()
828948

High-level functionality

These examples assume the following simple Solidity contract:

contract Example {

    string s;

    function set_s(string new_s) {
        s = new_s;
    }

    function get_s() returns (string) {
        return s;
    }
}

Compile it like this:

$ solc --binary stdout example.sol

Setup

>>> compiled = '606060405261020f806100136000396000f30060606040526000357c01000000000000000000000000000000000000000000000000000000009004806375d74f3914610044578063e7aab290146100bd57610042565b005b61004f600450610191565b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600302600f01f150905090810190601f1680156100af5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61010d6004803590602001906004018035906020019191908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050905061010f565b005b806000600050908051906020019082805482825590600052602060002090601f01602090048101928215610160579182015b8281111561015f578251826000505591602001919060010190610141565b5b50905061018b919061016d565b80821115610187576000818150600090555060010161016d565b5090565b50505b50565b60206040519081016040528060008152602001506000600050805480601f0160208091040260200160405190810160405280929190818152602001828054801561020057820191906000526020600020905b8154815290600101906020018083116101e357829003601f168201915b5050505050905061020c565b9056'
>>> from ethjsonrpc import EthJsonRpc  # to use Parity-specific methods, import ParityEthJsonRpc
>>> c = EthJsonRpc('127.0.0.1', 8545)

Creating a contract on the blockchain

>>> # continued from above
>>> contract_tx = c.create_contract(c.eth_coinbase(), compiled, gas=300000)
>>> # wait here for the contract to be created when a new block is mined
>>> contract_addr = c.get_contract_address(contract_tx)
>>> contract_addr
u'0x24988147f2f2300450103d8c42c43182cf226857'

Calling a contract function with a transaction (storing data)

>>> # continued from above
>>> tx = c.call_with_transaction(c.eth_coinbase(), contract_addr, 'set_s(string)', ['Hello, world'])
>>> tx
u'0x15bde63d79466e3db5169a913bb2069130ca387033d2ff2e29f4dfbef1bc6e0d'

Calling a contract function on the local blockchain (reading data)

>>> # continued from above
>>> results = c.call(contract_addr, 'get_s()', [], ['string'])
>>> results
['Hello, world']

Additional examples

Please see test.py for additional examples.

Implemented JSON-RPC methods

  • web3_clientVersion
  • web3_sha3
  • net_version
  • net_listening
  • net_peerCount
  • eth_protocolVersion
  • eth_syncing
  • eth_coinbase
  • eth_mining
  • eth_hashrate
  • eth_gasPrice
  • eth_accounts
  • eth_blockNumber
  • eth_getBalance
  • eth_getStorageAt
  • eth_getTransactionCount
  • eth_getBlockTransactionCountByHash
  • eth_getBlockTransactionCountByNumber
  • eth_getUncleCountByBlockHash
  • eth_getUncleCountByBlockNumber
  • eth_getCode
  • eth_sign
  • eth_sendTransaction
  • eth_sendRawTransaction
  • eth_call
  • eth_estimateGas
  • eth_getBlockByHash
  • eth_getBlockByNumber
  • eth_getTransactionByHash
  • eth_getTransactionByBlockHashAndIndex
  • eth_getTransactionByBlockNumberAndIndex
  • eth_getTransactionReceipt
  • eth_getUncleByBlockHashAndIndex
  • eth_getUncleByBlockNumberAndIndex
  • eth_getCompilers
  • eth_compileSolidity
  • eth_compileLLL
  • eth_compileSerpent
  • eth_newFilter
  • eth_newBlockFilter
  • eth_newPendingTransactionFilter
  • eth_uninstallFilter
  • eth_getFilterChanges
  • eth_getFilterLogs
  • eth_getLogs
  • eth_getWork
  • eth_submitWork
  • eth_submitHashrate
  • db_putString
  • db_getString
  • db_putHex
  • db_getHex
  • shh_version
  • shh_post
  • shh_newIdentity
  • shh_hasIdentity
  • shh_newGroup
  • shh_addToGroup
  • shh_newFilter
  • shh_uninstallFilter
  • shh_getFilterChanges
  • shh_getMessages

Parity-only JSON-RPC methods

To use these methods, make sure that you're

  • running Parity as your client
  • running with the --tracing on option
  • using this library's ParityEthJsonRpc client (not the vanilla EthJsonRpc client)

Methods:

  • trace_filter
  • trace_get
  • trace_transaction
  • trace_block

Reference

ethjsonrpc's People

Contributors

afdudley avatar arachnid avatar coder5876 avatar corbinbs avatar danielnovy avatar maurycyp 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

ethjsonrpc's Issues

Unable to successfully sign ethereum transaction offline using TREZORCTL ethereum_sign_tx

I am trying to complete an offline ethereum transaction with a Trezor hardware wallet using https://github.com/trezor/python-trezor but I get the following error:

Traceback (most recent call last):
File "/usr/local/bin/trezorctl", line 851, in
cli()
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 722, in call
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/decorators.py", line 27, in new_func
return f(get_current_context().obj, *args, **kwargs)
File "/usr/local/bin/trezorctl", line 687, in ethereum_sign_tx
from ethjsonrpc import EthJsonRpc
File "/usr/local/lib/python3.5/dist-packages/ethjsonrpc/init.py", line 1, in
from ethjsonrpc.client import (EthJsonRpc, ParityEthJsonRpc,
File "/usr/local/lib/python3.5/dist-packages/ethjsonrpc/client.py", line 7, in
from ethereum import utils
File "/usr/local/lib/python3.5/dist-packages/ethereum/utils.py", line 103, in
assert sha3('').encode('hex') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
AttributeError: 'bytes' object has no attribute 'encode'

I've tried on different OS / VMs but had no luck. Not sure if this is a user error, or how to work around it. Any insight would be appreciated. I am sure I am using the correct syntax but there seems to be an issue with some of the dependencies, specifically when trying to successfully run trezorctl ethereum_sign_tx .

Thanks!

Lib throws for the call `net_peerCount`

In my project, I use testrpc as the environment for my unit tests.
And ehjsonrpc throws for the call net_peerCount with this:

File "/../src/venv/lib/python3.5/site-packages/ethjsonrpc/client.py", line 175, in net_peerCount
    return hex_to_dec(self._call('net_peerCount'))
  File "/../src/venv/lib/python3.5/site-packages/ethjsonrpc/utils.py", line 10, in hex_to_dec
    return int(x, 16)
TypeError: int() can't convert non-string with explicit base

I found a quick fix
https://github.com/ConsenSys/ethjsonrpc/blob/master/ethjsonrpc/utils.py#L8

def hex_to_dec(x):
    if type(x) is int:
        return x
    return int(x, 16)

Use not freezed dependencies

Now ethjsonrpc strictly requires requests==2.9.1. I may cause problems for some projects. Do someone test it with older/newer requests?

Probably python3 issue: AttributeError: 'bytes' object has no attribute 'encode'

Traceback (most recent call last):
  File "./gethrpc.py", line 2, in <module>
    from ethjsonrpc import EthJsonRpc
  File "/usr/local/lib/python3.5/dist-packages/ethjsonrpc/__init__.py", line 1, in <module>
    from ethjsonrpc.client import (EthJsonRpc, ParityEthJsonRpc,
  File "/usr/local/lib/python3.5/dist-packages/ethjsonrpc/client.py", line 7, in <module>
    from ethereum import utils
  File "/usr/local/lib/python3.5/dist-packages/ethereum/utils.py", line 103, in <module>
    assert sha3('').encode('hex') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
AttributeError: 'bytes' object has no attribute 'encode'

cannot unmarshal hex string without 0x prefix into Go struct

I get:

ethjsonrpc.exceptions.BadResponseError: {u'jsonrpc': u'2.0', u'id': 1, u'error': {u'message': u'invalid argument 0: json: cannot unmarshal hex string without 0x prefix into Go struct field CallArgs.data of type hexutil.Bytes', u'code': -32602}}

when I try to connect to geth 1.7.2-stable-1db4ecdc

Does not work with Geth 1.6.6

Changes in the RPC implementation in Geth appear to have broken the demo- specifically, the calls to c.call() and c.call_with_transaction() return a

BadResponseError: {u'jsonrpc': u'2.0', u'id': 1, u'error': {u'message': u'invalid argument 0: missing 0x prefix for hex data', u'code': -32602}}

Geth v1.6.6, ethjsonrpc v0.3.0, python 2.7.12, Mac OS 10.11.6 (El Capitan).

The same demo worked for me in December, but I believe that changes to the RPC hooks in geth have affected this.

Remove trailing 'L' off the string returns from `hex` [Python 2.x]

Hi,

Seems hex is being used to convert integer to hex string, when ethjsonrpc constructs the RPC requests (the argument value of eth_sendTransaction specifically).

The hex in Python 2.x will represent a long with a trailing 'L':

>>> hex(1L)
'0x1L'

>>> hex(12345678901234567890)
'0xab54a98ceb1f0ad2L'

'L' isn't legal for a hex string. The odd fact is that geth RPC often accepts such false format without complaining, but not always. Here is an error message from "Geth/v1.4.0-unstable/linux/go1.5.1":

{"code":-32602,"message":"Unable to parse number"}

Removing the tailing 'L' solved the error.

While still no idea what causes the difference (the error only happens on one of the geth instances we installed), the error is real. Worth mentioning the issue here in case others are having the same problem.

It also worth a simple fix like hex(x).rstrip("L") since the hex string feeds geth PRC could indeed contain the illegal character.

Connecting with Infura support ?

Dose this library supports Infura ?
Just tried a below script to connect with Infura.
`>>> c = EthJsonRpc('https://rinkeby.infura.io/3wNHisYyMhD4B0UTAoWs')

c.net_version()
Traceback (most recent call last):
File "", line 1, in
File "ethjsonrpc/client.py", line 159, in net_version
return self._call('net_version')
File "ethjsonrpc/client.py", line 55, in _call
raise ConnectionError
ethjsonrpc.exceptions.ConnectionError
`
Kindly help.

Error send transfer

My Code ::

coin_base = c.eth_coinbase()
gas_price = ether_to_wei(0.00006)
balance =  (c.eth_getBalance(coin_base, 'latest'))
c.eth_sendTransaction(from_address=coin_base, to_address=my_addr, value=ether_to_wei(balance - gas_price),gas=1000000,gas_price=1000000)

error

raise BadResponseError(response)
ethjsonrpc.exceptions.BadResponseError: {u'jsonrpc': u'2.0', u'id': 1, u'error': {u'message': u'insufficient funds for gas * price + value', u'code': -32000}}

Integer type must have numerical suffix for uint but not for uint256

Hi!

Taking an example ERC20 contract with the following definition:

  function balanceOf(address _owner) constant returns (uint balance) {
    return balances[_owner];
  }

Executing a call() to the contract with uint var type i got this error:

>>> c.call(contract_addr, 'balanceOf(address)', ['0x00fC8E759f5941F54aD61e7716B7e5163D9CFA83'], ['uint'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ethjsonrpc/client.py", line 120, in call
    return decode_abi(result_types, response[2:].decode('hex'))
  File "/hidden_path/local/lib/python2.7/site-packages/ethereum/abi.py", line 756, in decode_abi
    proctypes = [process_type(typ) for typ in types]
  File "/hidden_path/local/lib/python2.7/site-packages/ethereum/abi.py", line 623, in process_type
    "Integer type must have numerical suffix"
AssertionError: Integer type must have numerical suffix

but passing uint256 it works like a charm

>>> c.call(contract_addr, 'balanceOf(address)', ['0x00fC8E759f5941F54aD61e7716B7e5163D9CFA83'], ['uint256'])
[10]

BTW: i'm using an already patched version of the lib for 0x prefixes

Support for default block parameters.

event_filter = c.eth_newFilter(from_block=str(fromBlock), to_block="latest", address=address, topics=topics)

Would create a filter without raising any error.

But executing logs = c.eth_getLogs(event_filter) raises "BadResponseError: {'jsonrpc': '2.0', 'id': 1, 'error': {'code': -32602, 'message': 'invalid argument 0: json: cannot unmarshal string into Go value of type filters.input'}}"

getFilterChanges and getFilterLogs seem to run fine.

fatal error C1083: Cannot open include file: 'alloca.h

This wont install, it starting installing pyethash and fails due to the following error, is it possible to install this without pyethash?

src/python/core.c(2): fatal error C1083: Cannot open include file: 'alloca.h
': No such file or directory
error: command 'E:\apps\Visual Studio 2015\VC\BIN\x86_amd64\cl.exe' fa
iled with exit status 2

I saw someone had a similar issue, how did you fix it?

update pypi please

pip install ethjsonrpc

and then

cat ...site-packages/ethjsonrpc/client.py | grep call_with_transaction

shows

def call_with_transaction(self, from_, address, sig, args, gas=None, gas_price=None):

while the newest code has the needed value parameter

def call_with_transaction(self, from_, address, sig, args, gas=None, gas_price=None, value=None):

--> https://pypi.python.org/pypi/ethjsonrpc

Thanks.

web3_sha3 not working under Python 2.7 on MacOS

Dear all,

i encountered some problem with the web3_sha3 rpc method on Mac OS with Python 2.7. Actually, line 150 in client.py does not reaturn a hex string starting with 0x. Since i assume that this is a Mac specific problem, otherwise other should have encountered it also, i would suggest to add something like:

if not data.startsWith('0x'):
data = '0x' + data

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.