Friday, October 23, 2020

The power of "import electrum" as a python bitcoin scripting engine

I've been a big fan of Electrum as a wallet for a while now. Traditionally, when I wanted to do bitcoin scripting I would use either trezorlib, pycoin, or bitcoinlib. But recently I was digging a bit deeper into the Electrum source and found it to be one of the simpler python libraries to use to craft bitcoin transactions.

One of the nicer things about Electrum as a scripting engine is that you can drop the standalone app or AppImage on a system and run your scripts directly through the console. This makes doing things on r/Tails or other locked down systems much easier. To run one one of your scripts (without the event loop) simply type (assuming you correct the file path):

with open(r"myscript.py", 'r') as s: exec(s.read())

Obviously only do this with scripts you've personally authored. Never run random code on your machine especially when wallet private keys are in play.

There are already some great scripting examples in the electrum\scripts folder, but most of these use the event loop which brings in a lot of overhead. I found simple TXN processing can easily be done without spawning an full electrum thread. I'd be happy to PR the samples if there is any interest in this style from the maintainers.

Here's two examples I put together that craft a BIP65 spending transaction. It turned out to be much simpler than I imagined. I did it both in bitcoinlib and electrum. The structure is very similar and should hopefully be easier to follow. Feel free to start a r/PythonRoastMe on it.

Two things of note. I had to disable R-value grinding (nuked while loop) so that I had parity with bitcoinlib, which hasn't rolled it out yet. This is why the TXIDs differ. I also had to override the the PartialTransaction.get_preimage_script method since it makes certain multisig assumptions that don't apply to generic scripting.

Reference: * Electrum script to spend an OP_HODL P2WSH address (txid 3a461e6...78de2b6) * Electrum script to spend an OP_HODL P2SH address (txid a8110bb...3dadc93) * BitcoinLib script to spend an OP_HODL P2WSH address (txid 3a461e6...78de2b6) * BitcoinLib script to spend an OP_HODL P2SH address (txid a8110bb...3dadc93) * TXID 3a461e6...78de2b6 (P2WSH) on the blockchain * TXID a8110bb...3dadc93 (P2SH) on the blockchain * BIP-0065: OP_CHECKLOCKTIMEVERIFY (aka OP_HODL) * BIP-0141: P2WSH symantics * BIP-0016: P2SH symantics


No comments:

Post a Comment