-
Notifications
You must be signed in to change notification settings - Fork 28
/
generate_data.py
executable file
·331 lines (273 loc) · 11.4 KB
/
generate_data.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python
import sys
import os
import json
import requests
from pathlib import Path
from decimal import Decimal, getcontext
getcontext().prec = 16
BITCOIN_RPC = os.getenv("BITCOIN_RPC")
USERPWD = os.getenv("USERPWD")
DEFAULT_URL = "https://bitcoin-mainnet.public.blastapi.io"
def request_rpc(method: str, params: list):
"""Makes a JSON-RPC call to a Bitcoin API endpoint.
Uses environment variables BITCOIN_RPC and USERPWD
or the default public endpoint if those variables are not set.
:return: parsed JSON result as Python object
"""
url = BITCOIN_RPC or DEFAULT_URL
auth = tuple(USERPWD.split(":")) if USERPWD else None
headers = {"content-type": "application/json"}
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": 0,
}
res = requests.post(url, auth=auth, headers=headers, json=payload)
try:
return res.json()["result"]
except Exception:
raise ConnectionError(f"Unexpected RPC response:\n{res.text}")
def fetch_chain_state(block_height: int):
"""Fetches chain state at the end of a specific block with given height.
Chain state is a just a block header extended with extra fields:
- prev_timestamps
- epoch_start_time
"""
# Chain state at height H is the state after applying block H
block_hash = request_rpc("getblockhash", [block_height])
head = request_rpc("getblockheader", [block_hash])
# In order to init prev_timestamps we need to query 10 previous headers
prev_header = head
prev_timestamps = [head["time"]]
for _ in range(10):
if prev_header["height"] == 0:
prev_timestamps.insert(0, 0)
else:
prev_header = request_rpc(
"getblockheader", [prev_header["previousblockhash"]]
)
prev_timestamps.insert(0, prev_header["time"])
head["prev_timestamps"] = prev_timestamps
# In order to init epoch start we need to query block header at epoch start
if block_height < 2016:
head["epoch_start_time"] = 1231006505
else:
head["epoch_start_time"] = get_epoch_start_time(block_height)
return head
def next_chain_state(head: dict, blocks: list):
"""Computes resulting chain state given the initial chain state
and all blocks that were applied to it.
"""
block_height = head["height"] + len(blocks)
next_head = blocks[-1]
# We need to recalculate the prev_timestamps field given the previous chain state
# and all the blocks we applied to it
prev_timestamps = head["prev_timestamps"] + list(map(lambda x: x["time"], blocks))
next_head["prev_timestamps"] = prev_timestamps[-11:]
# Update epoch start time if neccesary
if head["height"] // 2016 != block_height // 2016:
next_head["epoch_start_time"] = get_epoch_start_time(block_height)
else:
next_head["epoch_start_time"] = head["epoch_start_time"]
return next_head
def get_epoch_start_time(block_height: int) -> int:
"""Computes the corresponding epoch start time given the current block height."""
epoch_start_block_height = (block_height // 2016) * 2016
epoch_start_block_hash = request_rpc("getblockhash", [epoch_start_block_height])
epoch_start_header = request_rpc("getblockheader", [epoch_start_block_hash])
return epoch_start_header["time"]
def format_chain_state(head: dict):
"""Formats chain state according to the respective Cairo type."""
return {
"block_height": head["height"],
"total_work": str(int.from_bytes(bytes.fromhex(head["chainwork"]), "big")),
"best_block_hash": head["hash"],
"current_target": str(bits_to_target(head["bits"])),
"epoch_start_time": head["epoch_start_time"],
"prev_timestamps": head["prev_timestamps"],
}
def bits_to_target(bits: str) -> int:
"""Convert difficulty bits (compact target representation) to target.
:param bits: bits as a hex string (without 0x prefix)
:return: target as integer
"""
exponent = int.from_bytes(bytes.fromhex(bits[:2]), "big")
mantissa = int.from_bytes(bytes.fromhex(bits[2:]), "big")
if exponent == 0:
return mantissa
elif exponent <= 3:
return mantissa >> (8 * (3 - exponent))
else:
return mantissa << (8 * (exponent - 3))
def fetch_block(block_hash: str):
"""Downloads block with transactions (and referred UTXOs) from RPC given the block hash."""
block = request_rpc("getblock", [block_hash, 2])
block["data"] = {tx["txid"]: resolve_transaction(tx) for tx in block["tx"]}
return block
def resolve_transaction(transaction: dict):
"""Resolves transaction inputs and formats the content according to the Cairo type."""
return {
"version": transaction["version"],
# Skip the first 4 bytes (version) and take the next 4 bytes (marker + flag)
"is_segwit": transaction["hex"][8:12] == "0001",
"inputs": [resolve_input(input) for input in transaction["vin"]],
"outputs": [format_output(output) for output in transaction["vout"]],
"lock_time": transaction["locktime"],
}
def resolve_input(input: dict):
"""Resolves referenced UTXO and formats the transaction inputs according to the Cairo type."""
if input.get("coinbase"):
return format_coinbase_input(input)
else:
return {
"script": f'0x{input["scriptSig"]["hex"]}',
"sequence": input["sequence"],
"previous_output": resolve_outpoint(input),
"witness": [f"0x{item}" for item in input.get("txinwitness", [])],
}
def resolve_outpoint(input: dict):
"""Fetches transaction and block header for the referenced output,
formats resulting outpoint according to the Cairo type.
"""
tx = request_rpc("getrawtransaction", [input["txid"], True])
block = request_rpc("getblockheader", [tx["blockhash"]])
return {
"txid": input["txid"],
"vout": input["vout"],
"data": format_output(tx["vout"][input["vout"]]),
"block_height": block["height"],
"block_time": block["time"],
"is_coinbase": tx["vin"][0].get("coinbase") is not None,
}
def format_coinbase_input(input: dict):
"""Formats coinbase input according to the Cairo type."""
return {
"script": f'0x{input["coinbase"]}',
"sequence": input["sequence"],
"previous_output": {
"txid": "0" * 64,
"vout": 0xFFFFFFFF,
"data": {
"value": 0,
"pk_script": "0x",
"cached": False,
},
"block_height": 0,
"block_time": 0,
"is_coinbase": False,
},
"witness": [
"0x0000000000000000000000000000000000000000000000000000000000000000"
],
}
def format_output(output: dict):
"""Formats transaction output according to the Cairo type."""
value = (Decimal(str(output["value"])) * Decimal("100000000")).to_integral_value()
return {
"value": int(value),
"pk_script": f'0x{output["scriptPubKey"]["hex"]}',
"cached": False,
}
def format_block_with_transactions(block: dict):
"""Formats block with transactions according to the respective Cairo type."""
return {
"header": format_header(block),
"data": {
"variant_id": 1,
"transactions": list(block["data"].values()),
},
}
def fetch_block_header(block_hash: str):
"""Downloads block header (without trasnasction) from RPC given the block hash."""
return request_rpc("getblockheader", [block_hash])
def format_block(header: dict):
"""Formats block (without transactions) according to the respective Cairo type.
Note that transaction data uses a verbose format to include information
about the particular enum variant.
:param header: block header obtained from RPC
"""
return {
"header": format_header(header),
"data": {"variant_id": 0, "merkle_root": header["merkleroot"]},
}
def format_header(header: dict):
"""Formats header according to the respective Cairo type.
:param header: block header obtained from RPC
"""
return {
"version": header["version"],
"time": header["time"],
"bits": int.from_bytes(bytes.fromhex(header["bits"]), "big"),
"nonce": header["nonce"],
}
def generate_data(
mode: str, initial_height: int, num_blocks: int, include_expected: bool
):
"""Generates arguments for Raito program in a human readable form and the expected result.
:param mode: Validation mode:
"light" — generate block headers with Merkle root only
"full" — generate full blocks with transactions (and referenced UTXOs)
:param initial_height: The block height of the initial chain state (0 means the state after genesis)
:param num_blocks: The number of blocks to apply on top of it (has to be at least 1)
:return: tuple (arguments, expected output)
"""
chain_state = fetch_chain_state(initial_height)
next_block_hash = chain_state["nextblockhash"]
blocks = []
# UTXO set to track unspent outputs
utxo_set = {}
for _ in range(num_blocks):
if mode == "light":
block = fetch_block_header(next_block_hash)
elif mode == "full":
block = fetch_block(next_block_hash)
# Build UTXO set and mark outputs spent within the same block (span).
# Also set "cached" flag for the inputs that spend those UTXOs.
for txid, tx in block["data"].items():
for tx_input in tx["inputs"]:
outpoint = (
tx_input["previous_output"]["txid"],
tx_input["previous_output"]["vout"],
)
if outpoint in utxo_set:
tx_input["previous_output"]["cached"] = True
utxo_set[outpoint]["cached"] = True
for idx, output in enumerate(tx["outputs"]):
outpoint = (txid, idx)
utxo_set[outpoint] = output
else:
raise NotImplementedError(mode)
next_block_hash = block["nextblockhash"]
blocks.append(block)
if mode == "full":
# Do another pass to mark UTXOs spent within the same block (span) with "cached" flag.
for block in blocks:
for txid, tx in block["data"].items():
for idx, output in enumerate(tx["outputs"]):
outpoint = (txid, idx)
if outpoint in utxo_set and utxo_set[outpoint].get("cached", False):
tx["outputs"][idx]["cached"] = True
block_formatter = (
format_block if mode == "light" else format_block_with_transactions
)
result = {
"chain_state": format_chain_state(chain_state),
"blocks": list(map(block_formatter, blocks)),
}
if include_expected:
result["expected"] = format_chain_state(next_chain_state(chain_state, blocks))
return result
# Usage: generate_data.py MODE INITIAL_HEIGHT NUM_BLOCKS INCLUDE_EXPECTED OUTPUT_FILE
# Example: generate_data.py 'light' 0 10 false light_0_10.json
if __name__ == "__main__":
if len(sys.argv) != 6:
raise TypeError("Expected five arguments")
data = generate_data(
mode=sys.argv[1],
initial_height=int(sys.argv[2]),
num_blocks=int(sys.argv[3]),
include_expected=sys.argv[4].lower() == "true",
)
Path(sys.argv[5]).write_text(json.dumps(data, indent=2))