|
| 1 | +# Python-bitcoinlib Examples |
| 2 | + |
| 3 | +The [`python-bitcoinlib`](https://github.com/petertodd/python-bitcoinlib) |
| 4 | +library allows constructing various objects from bytes. We can use this |
| 5 | +to more granularly inspect kernel objects that expose their contents as |
| 6 | +bytes, such as [`Block`](#inspecting-block-data) (`kernel_Block`) and |
| 7 | +[`TransactionOutput`](#inspecting-transactionoutput-data) |
| 8 | +(`kernel_TransactionOutput`). |
| 9 | + |
| 10 | +> [!NOTE] |
| 11 | +> The `python-bitcoinlib` library is unrelated to this project, and |
| 12 | +> information here is provided only on a best-effort basis. |
| 13 | +
|
| 14 | +## Setup |
| 15 | + |
| 16 | +First, we'll create a ChainstateManager and load the current chain tip: |
| 17 | + |
| 18 | +```py |
| 19 | +import pbk |
| 20 | +chainman = pbk.load_chainman("/tmp/bitcoin/signet/", pbk.ChainType.SIGNET) |
| 21 | +tip = chainman.get_block_index_from_tip() |
| 22 | +``` |
| 23 | + |
| 24 | +## Inspecting Block Data |
| 25 | + |
| 26 | +To analyze the block, we can use the `python-bitcoinlib` `CBlock` class: |
| 27 | + |
| 28 | +```py |
| 29 | +from bitcoin.core import CBlock |
| 30 | + |
| 31 | +block_bytes = chainman.read_block_from_disk(tip).data |
| 32 | +cblock = CBlock.deserialize(block_bytes) |
| 33 | + |
| 34 | +assert tip.block_hash.hex == cblock.GetHash().hex() |
| 35 | +print(f"Block {cblock.GetHash().hex()} has {len(cblock.vtx)} transactions and {cblock.GetWeight()} weight") |
| 36 | +print(f"The last transaction has witness data: {cblock.vtx[-1].wit.vtxinwit}") |
| 37 | +``` |
| 38 | + |
| 39 | +## Inspecting TransactionOutput data |
| 40 | + |
| 41 | +```py |
| 42 | +from bitcoin.core.script import CScript |
| 43 | +from pprint import pprint |
| 44 | + |
| 45 | +undo = chainman.read_block_undo_from_disk(tip) |
| 46 | +result = {} |
| 47 | +for i, tx in enumerate(undo.iter_transactions()): |
| 48 | + result[i] = [CScript(output.script_pubkey.data) for output in tx.iter_outputs()] |
| 49 | +print(f"Block {tip.height} has transactions spending the following previous outputs:") |
| 50 | +pprint(result) |
| 51 | +``` |
0 commit comments