You know about the Ethereum network and you want to interact with it.
We will be interacting with the Ethereum network through a node which we will run on our computer. We will communicate with our node through a convenient python module which uses the JSON-RPC API of the node.
The first thing we will do is install our Ethereum node software. I recommend go-ethereum (https://github.com/ethereum/go-ethereum).
If you are an Arch Linux user simply run in the terminal:
$ sudo pacman -S geth
Now we need to run geth with two important flags:
$ geth --syncmode light --rpc.
--syncmode light
will opt for something called light client protocol (https://github.com/ethereum/wiki/wiki/Light-client-protocol) which as far as we are concerned makes the blockchain data stored on your computer less than 1GB and allows you to interact with the Ethereum network in about an hour after starting geth.
The --rpc
flag will tell the node to listen for HTTP requests on 127.0.0.1:8545
by default.
After about 10 minutes after starting geth it should be synchronizing. You should see output looking like this in the terminal where you ran geth:
INFO [10-29|20:07:38.808] Imported new block headers count=192 elapsed=267.578ms number=8598911 hash=c26e75…3d440c age=1mo1w6h
The age mentioned in the log will be going down until geth is cought up with the current state of the blockchain:
INFO [10-29|20:48:34.941] Imported new block headers count=75 elapsed=84.598ms number=8835914 hash=4aff9d…0175e3 age=1m21s
INFO [10-29|20:48:34.947] Imported new block headers count=1 elapsed=5.083ms number=8835915 hash=78184d…db2010 age=1m14s
INFO [10-29|20:48:34.952] Imported new block headers count=1 elapsed=4.989ms number=8835916 hash=1ed6a4…2cbf1b
If you see something like this we can start querying the latest blockchain data. For that we will use web3.py — a python library (https://web3py.readthedocs.io/en/stable/index.html). Install it using pip:
$ pip install --user web3
Now open the python REPL:
$ python
and type the following commands:
import web3
w3 = web3.Web3(web3.HTTPProvider("http://localhost:8545"))
b = w3.eth.getBlock('latest')
print(b.difficulty, len(b.transactions))
In the first line we imported the module. In the second one we created an instance of web3.Web3 that is a wrapper of the JSON-RPC API. We connected to our node through port 8545, on which it is listening due to the --rpc
flag. We then requested the latest block and got back an object describing it.
On the fourth line we printed the blocks difficulty and the number of transactions it contains. The example output should be:
2413349365164497 10
For all the things you can do with the JSON-RPC API consult the specification (https://github.com/ethereum/wiki/wiki/JSON-RPC#json-rpc-api). Most methods mentioned there should be accessible through a web.Web3 instance. Just substitute the underscores _
for dots .
.
You got your feet wet now dive deeper.