Skip to content

Commit 7373df8

Browse files
committed
Add block_index & coinbase filler script
1 parent 18727db commit 7373df8

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

scripts/add_coinbase_to_txs.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import asyncio
2+
import json
3+
import pathlib
4+
import typing
5+
import sys
6+
7+
sys.path.append(str(pathlib.Path(__file__).parent.parent))
8+
9+
from sqlalchemy import func, select, update
10+
11+
from app.database import sessionmanager
12+
from app.settings import get_settings
13+
from app.parser import make_request
14+
from app.models import Transaction
15+
16+
settings: typing.Any = get_settings()
17+
18+
19+
async def main():
20+
sessionmanager.init(settings.database.endpoint)
21+
22+
async with sessionmanager.session() as session:
23+
24+
total = (
25+
await session.scalar(
26+
select(func.count(Transaction.id)).filter(
27+
(Transaction.coinbase == None) | (Transaction.block_index == None)
28+
)
29+
)
30+
or 0
31+
)
32+
limit = 100
33+
34+
query = (
35+
select(Transaction.id, Transaction.txid)
36+
.filter((Transaction.coinbase == None) | (Transaction.block_index == None))
37+
.limit(limit)
38+
)
39+
40+
processed = 0
41+
42+
while txs := (await session.execute(query)).all():
43+
updates: list[dict[str, typing.Any]] = []
44+
45+
for dbid, txid in txs:
46+
transaction_result = await make_request(
47+
settings.blockchain.endpoint,
48+
[
49+
{
50+
"id": str(dbid),
51+
"method": "getrawtransaction",
52+
"params": [txid, True],
53+
}
54+
],
55+
)
56+
tx = transaction_result[0]["result"]
57+
58+
block_response = await make_request(
59+
settings.blockchain.endpoint,
60+
[
61+
{
62+
"id": tx["blockhash"],
63+
"method": "getblock",
64+
"params": [tx["blockhash"]],
65+
}
66+
],
67+
)
68+
block = block_response[0]["result"]
69+
70+
block_index = block["tx"].index(txid)
71+
updates.append(
72+
{
73+
"id": dbid,
74+
"block_index": block_index,
75+
"coinbase": block_index == 0,
76+
}
77+
)
78+
79+
await session.execute(
80+
update(Transaction),
81+
updates,
82+
execution_options={"synchronize_session": False},
83+
)
84+
await session.commit()
85+
processed += limit
86+
print(
87+
f"Progress: {processed}/{total} ({(processed/total)*100:.2f})",
88+
end="\r",
89+
flush=True,
90+
)
91+
92+
print("\nDone")
93+
94+
95+
if __name__ == "__main__":
96+
asyncio.run(main())

0 commit comments

Comments
 (0)