Electrum RPC with Python — Trust a stranger (or SPV verify)

0 3
Avatar for cashdev
4 years ago

Running your own full node is not always the best option, so a full nodes RPC interface is not exactly readily available.

You can still interact with the Bitcoin Cash blockchain using public Electrum servers.

Here is a code snippet using the bitcoincash Python library that fetches the block header of block 613880.

$ cat test.py
from bitcoincash.electrum import Electrum
from bitcoincash.core import CBlockHeader, x
import asyncio

async def electrum_stuff():
    cli = Electrum()
    await cli.connect()

    header_hex = await cli.RPC('blockchain.block.header', 613880)

    header = CBlockHeader.deserialize(x(header_hex))
    print(f"Received header: {header}")

    await cli.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(electrum_stuff())
loop.close()

And when ran:

$ python3 test.py 
Received header: CBlockHeader(545259520, 
    lx(000000000000000002e937da590fdc4325da13c250f26a73343d635913467019), 
    lx(f9acfe3f0e98fc321123f787e21e17984998f46866d30244328bf7552051d57a), 
    1576668009, 0x18030793, 0x34e3adb0)

Full list of Electrum RPC methods are documented by ElectrumX.

In this code snippet, we're trusting the server to provide us with correct the information. That may be fine for your use case. Or perhaps you or a friend are running your own electrum server, which you trust.

Electrum servers still provide enough data to give you SPV security, so you don't have to trust the public server. You can verify. Should I write articles about SPV verifying blockchain data? Comment below.

Sponsors of cashdev
empty
empty
empty

1
$ 0.00
Avatar for cashdev
4 years ago

Comments