-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_block.py
More file actions
47 lines (40 loc) · 1.65 KB
/
Copy path11_block.py
File metadata and controls
47 lines (40 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# SPDX-License-Identifier: MIT
"""11 - Fetch a block and visualize it: header, transactions, and how full it is.
Reads a block from TestnetScan's public API (no node needed) and prints its header, the
first handful of transactions, and a bar showing how much of the roughly 4,000,000 weight
budget it used. Pair it with recipe 10 to decode any transaction it lists.
python 11_block.py [height] (default: the current tip)
"""
import sys
import time
import requests
from config import api
WEIGHT_LIMIT = 4_000_000
if len(sys.argv) > 1:
height = int(sys.argv[1])
else:
height = int(requests.get(api("/blocks/tip/height"), timeout=30).text)
h = requests.get(api(f"/block-height/{height}"), timeout=30).text.strip()
blk = requests.get(api(f"/block/{h}"), timeout=30).json()
txids = requests.get(api(f"/block/{h}/txids"), timeout=30).json()
when = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(blk["timestamp"]))
filled = blk["weight"] / WEIGHT_LIMIT
bar_w = 30
full = int(filled * bar_w + 0.5)
bar = "#" * full + "." * (bar_w - full)
print(f"Block {blk['height']:,}")
print(f" hash {h}")
print(f" time {when}")
print(f" txs {blk['tx_count']:,}")
print(f" size {blk['size'] / 1000:.1f} kB weight {blk['weight']:,} WU")
print(f" full [{bar}] {filled * 100:.1f}% of the {WEIGHT_LIMIT:,} WU budget")
print()
show = min(len(txids), 8)
print(f"first {show} of {blk['tx_count']:,} transactions:")
for i, t in enumerate(txids[:show]):
tag = " (coinbase)" if i == 0 else ""
print(f" {i + 1:>2}. {t}{tag}")
if len(txids) > show:
print(f" ... and {blk['tx_count'] - show:,} more")
print()
print("decode any of them: python 10_decode_tx.py <txid>")