This repository was archived by the owner on Nov 25, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathSCASH Transfer.py
More file actions
662 lines (616 loc) · 26.1 KB
/
Copy pathSCASH Transfer.py
File metadata and controls
662 lines (616 loc) · 26.1 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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
import requests
from bs4 import BeautifulSoup
import re
import sys
import sqlite3
import os
from datetime import datetime
import time
import subprocess
import shutil
import traceback
import subprocess
import ast
import importlib
from config import BLOCK_HEIGHT, THRESHOLD, BASE_URL, SHOW_RESULT, SCAN_INTERVAL, DB_FILE, SCAN_TRUE
def init_db():
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# 區塊表:block_height 主鍵,txids 為 JSON 字串
c.execute('''CREATE TABLE IF NOT EXISTS block (
block_height INTEGER PRIMARY KEY,
txids TEXT
)''')
# 交易表:每一筆 address/amount/transfer_time 都是一列
c.execute('''CREATE TABLE IF NOT EXISTS tx (
txid TEXT,
block_height INTEGER,
address TEXT,
amount REAL,
transfer_time TEXT,
PRIMARY KEY (txid, address),
FOREIGN KEY (block_height) REFERENCES block(block_height)
)''')
# 地址餘額表
c.execute('''CREATE TABLE IF NOT EXISTS scash_address_balances (
address TEXT PRIMARY KEY,
balance REAL,
scan_time TEXT,
update_time TEXT,
update_count INTEGER,
change_str TEXT
)''')
conn.commit()
def fetch_html(url, retries=10, retry_interval=3):
for attempt in range(1, retries + 1):
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
resp.encoding = 'utf-8'
return BeautifulSoup(resp.text, 'html.parser')
except requests.RequestException as e:
print(f"HTTP 請求失敗: {e} (第 {attempt} 次)")
if attempt < retries:
time.sleep(retry_interval)
else:
sys.exit(1)
def get_timestamp(soup):
time_div = soup.find("div", class_="fw-bold", string="Time")
if not time_div:
print("找不到時間區塊")
return None
parent_div = time_div.find_parent("div", class_="ms-2 me-auto")
if not parent_div:
print("找不到時間父區塊")
return None
text = parent_div.get_text(separator=" ", strip=True)
return text.replace("Time", "", 1).strip()
def get_total_output_amount(soup):
elem = soup.find(string=re.compile("Total amount in all outputs"))
if not elem:
print("無法找到總輸出金額")
raise Exception("無法找到總輸出金額")
parent = elem.find_parent("li")
div = parent.find("div", class_="ms-2 me-auto") if parent else None
if not div:
print("無法找到金額區塊")
raise Exception("無法找到金額區塊")
match = re.search(r"([\d'\.]+)\s*SCASH",
div.get_text(separator=" ", strip=True))
if not match:
print("無法解析 SCASH 數值")
raise Exception("無法解析 SCASH 數值")
return float(match.group(1).replace("'", ""))
def find_txids_by_amount(soup, total_amount):
"""
優先找整數位相同的轉帳txid,再找所有大於閾值的轉帳txid,回傳所有txid(不重複,優先順序)。
"""
list_items = [
li for li in soup.find_all("li", class_="list-group-item")
if not (
(div := li.find("div", class_="text-truncate")) and
div.get_text(strip=True).startswith("1.")
)
]
txids = []
seen = set()
# 1. 優先找整數位相同的轉帳
total_int = int(total_amount)
for li in list_items:
badge = li.find(
"span", class_=lambda x: x and "badge" in x and "bg-primary" in x)
if not badge:
continue
match = re.search(r"([\d\.]+)\s*SCASH", badge.get_text(strip=True))
if not match:
continue
amount = float(match.group(1))
if abs(amount - 50) < 1e-6:
continue
if int(amount) == total_int and amount >= THRESHOLD:
txid_a = li.find("a", href=re.compile(r"^/tx/"))
if txid_a:
txid = txid_a.get_text(strip=True)
if txid not in seen:
txids.append(txid)
seen.add(txid)
# 2. 其他大於閾值的轉帳
for li in list_items:
badge = li.find(
"span", class_=lambda x: x and "badge" in x and "bg-primary" in x)
if not badge:
continue
match = re.search(r"([\d\.]+)\s*SCASH", badge.get_text(strip=True))
if not match:
continue
amount = float(match.group(1))
if abs(amount - 50) < 1e-6:
continue
if amount >= THRESHOLD:
a_tag = li.find("a", href=re.compile(r"^/tx/"))
if a_tag:
txid = a_tag.get_text(strip=True)
if txid not in seen:
txids.append(txid)
seen.add(txid)
if not txids:
print(f"找不到任何大於閾值 {THRESHOLD} SCASH 的轉帳")
return txids
def get_tx_outputs(txid):
tx_url = f"{BASE_URL}/tx/{txid}"
tx_soup = fetch_html(tx_url)
outputs = []
total_outputs_li = tx_soup.find(
"div", class_="fw-bold", string=re.compile(r"Total outputs"))
if total_outputs_li:
parent_li = total_outputs_li.find_parent("li")
if parent_li:
amount_div = parent_li.find("div", class_="ms-2 me-auto")
if amount_div:
match = re.search(
r"([\d'\.]+)\s*SCASH", amount_div.get_text(separator=" ", strip=True))
if match and float(match.group(1).replace("'", "")) >= THRESHOLD:
for item in tx_soup.find_all("li", class_="list-group-item"):
addr_a = item.find(
"a", href=re.compile(r"^/\?&search=scash1"))
if addr_a:
address = re.search(
r"search=(scash1[0-9a-zA-Z]+)", addr_a['href'])
full_address = address.group(
1) if address else addr_a.get_text(strip=True)
amount_span = item.find(
"span", class_="text-muted")
if amount_span:
amount_match = re.search(
r"([\d'\.]+)\s*SCASH", amount_span.get_text(strip=True))
if amount_match:
amount = float(
amount_match.group(1).replace("'", ""))
outputs.append((full_address, amount))
return outputs
def get_address_balance(address):
url = f"{BASE_URL}/?search={address}&utxolookup=1"
soup = fetch_html(url)
total_div = soup.find("div", class_="totalamount")
if not total_div:
print("找不到總餘額區塊")
return None
match = re.search(
r"Total unspent SCASH:\s*([\d\.]+)", total_div.get_text())
if not match:
print("無法解析總餘額")
return None
return float(match.group(1))
def write_transfer_db(rows):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
for row in rows:
c.execute('''INSERT INTO scash_transfer_records (block_height, txid, address, amount, transfer_time)
VALUES (?, ?, ?, ?, ?)''', row)
conn.commit()
def write_address_balance_db(address, balance, conn=None):
if balance < THRESHOLD:
return
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
close_conn = False
if conn is None:
conn = sqlite3.connect(DB_FILE)
close_conn = True
c = conn.cursor()
c.execute('SELECT balance, scan_time, update_time, update_count FROM scash_address_balances WHERE address=?', (address,))
row = c.fetchone()
if row:
last_balance, scan_time, update_time, update_count = row
diff = balance - last_balance if last_balance is not None else 0
if abs(diff) > 1e-8:
# diff > 0 顯示 +,diff < 0 顯示 -
if diff > 0:
change_str = f"+{diff:.8f}"
else:
change_str = f"{diff:.8f}"
update_time = now_str
update_count = (update_count or 0) + 1
c.execute('''UPDATE scash_address_balances SET balance=?, update_time=?, update_count=?, change_str=? WHERE address=?''',
(balance, update_time, update_count, change_str, address))
else:
# 新增
c.execute('''INSERT INTO scash_address_balances (address, balance, scan_time, update_time, update_count, change_str)
VALUES (?, ?, ?, ?, ?, ?)''',
(address, balance, now_str, '', 0, ''))
if close_conn:
conn.commit()
conn.close()
# 自動查詢所有已知地址餘額並自動更新
def auto_update_all_address_balances():
print("\n自動查詢所有地址餘額...")
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute(
'SELECT address, balance, update_count FROM scash_address_balances')
rows = c.fetchall()
total = len(rows)
updated_count = 0
for idx, (address, old_balance, old_update_count) in enumerate(rows, 1):
new_balance = get_address_balance(address)
if new_balance is not None and abs(new_balance - old_balance) > 1e-8:
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
diff = new_balance - old_balance
change_str = f"+{diff:.8f}" if diff > 0 else f"{diff:.8f}"
new_update_count = (old_update_count or 0) + 1
c.execute('''UPDATE scash_address_balances SET balance=?, update_time=?, update_count=?, change_str=? WHERE address=?''',
(new_balance, now_str, new_update_count, change_str, address))
updated_count += 1
# 只顯示進度條
bar_len = 30
filled_len = int(bar_len * idx // total)
bar = '█' * filled_len + '-' * (bar_len - filled_len)
print(f"\r[{bar}] {idx}/{total} 已查詢...", end='')
sys.stdout.flush()
print() # 換行
conn.commit()
print(f"\n共更新 {updated_count} 個地址餘額。\n")
run_export_dashboard_data()
def record_address_balance(address, address_balance_set, conn=None):
"""查詢並記錄唯一地址餘額。"""
if address_balance_set is not None and address not in address_balance_set:
balance = get_address_balance(address)
if balance is not None and balance >= THRESHOLD:
address_balance_set.add(address)
write_address_balance_db(address, balance, conn)
def run_export_dashboard_data():
while True:
try:
subprocess.run(
[sys.executable, 'export_dashboard_data.py'], check=True)
# 移動 dashboard_data.js 到 assets 目錄
src = os.path.join(os.path.dirname(__file__), 'dashboard_data.js')
dst_dir = os.path.join(os.path.dirname(__file__), 'assets')
dst = os.path.join(dst_dir, 'dashboard_data.js')
if os.path.exists(src):
# 確保目標資料夾存在
os.makedirs(dst_dir, exist_ok=True)
shutil.move(src, dst)
print(f"dashboard_data.js 已移動到 {dst}")
break
except Exception as e:
print(
f"執行 export_dashboard_data.py 發生錯誤: {e},3秒後重試... (Ctrl+C 可中止)")
try:
time.sleep(3)
except KeyboardInterrupt:
print("已中止 export_dashboard_data.py 重試。")
break
def auto_query_mode(start_height, end_height=None):
height = start_height
address_balance_set = set()
scanned_count = 0
while True:
try:
# 若有設定結束高度,查到即結束;否則永遠不會自動結束,需手動 Ctrl+C 停止
if end_height is not None and height > end_height:
print("已達結束區塊高度,結束自動查詢模式。")
break
if SHOW_RESULT:
print(f"\n查詢區塊高度: {height}")
else:
print(f"查詢區塊高度: {height}", end='\r')
try:
result = process_and_record_block(height, address_balance_set)
except Exception as e:
# 只顯示簡訊息,不顯示 traceback
print(f"查詢區塊 {height} 發生錯誤: {e}")
result = False
if result:
height += 1
scanned_count += 1
if scanned_count % 10 == 0:
run_export_dashboard_data()
else:
print("查詢失敗或查不到,10秒後重試本區塊...")
# 根據設定決定是否自動查詢所有地址餘額
if SCAN_TRUE:
auto_update_all_address_balances() # 更新一次地址餘額
for i in range(10, 0, -1):
print(f" 等待 {i:02d} 秒後重試...", end='\r')
time.sleep(1)
print("\n重新嘗試掃描本區塊...")
except KeyboardInterrupt:
print("\n偵測到中斷 (Ctrl+C),將完成本區塊查詢與寫入後結束。")
break
except Exception as e:
print(f"查詢區塊 {height} 發生未預期錯誤: {e}")
return False
def process_and_record_block(block_height, address_balance_set):
"""查詢區塊、記錄轉帳與地址餘額,回傳True/False代表是否繼續。"""
import json
import traceback
try:
block_url = f"{BASE_URL}/?search={block_height}"
soup = fetch_html(block_url)
total_amount = get_total_output_amount(soup)
time_str = get_timestamp(soup)
if total_amount < THRESHOLD:
if SHOW_RESULT:
print(
f"總轉帳金額 {total_amount} SCASH 未達閾值 {THRESHOLD} SCASH,跳過後續查詢。")
else:
print(f"區塊高度: {block_height}", end='\r')
return True
if SHOW_RESULT:
print(f"區塊高度: {block_height}")
else:
print(f"區塊高度: {block_height}", end='\r')
txids = find_txids_by_amount(soup, total_amount)
if not txids:
if SHOW_RESULT:
print("未找到對應的 txid,無法查詢地址")
return True
# 寫入 block、tx、address_balance 都共用同一個 conn
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute('INSERT OR REPLACE INTO block (block_height, txids) VALUES (?, ?)',
(block_height, json.dumps(txids)))
for txid in txids:
if SHOW_RESULT:
print(f"轉帳 TxID: {txid}")
outputs = get_tx_outputs(txid)
for address, amount in outputs:
if amount < THRESHOLD:
continue
record_address_balance(address, address_balance_set, conn)
c.execute('''INSERT OR REPLACE INTO tx (txid, block_height, address, amount, transfer_time)
VALUES (?, ?, ?, ?, ?)''',
(txid, block_height, address, amount, time_str))
conn.commit()
return True
except Exception as e:
print(f"查詢區塊 {block_height} 發生錯誤: {e}")
traceback.print_exc()
return False
def manual_query_mode():
address_balance_set = set()
while True:
user_input = input("\n請輸入區塊高度、地址或TxID (輸入 exit 結束): ").strip()
if user_input.lower() == "exit":
break
if user_input.isdigit():
process_and_record_block(int(user_input), address_balance_set)
elif user_input.startswith("scash1"):
record_address_balance(user_input, address_balance_set, None)
process_address(user_input)
elif re.fullmatch(r"[0-9a-fA-F]{64}", user_input):
process_txid(user_input)
else:
print("輸入格式錯誤,請重新輸入。")
def process_block(block_height, address_balance_set=None):
try:
block_url = f"{BASE_URL}/?search={block_height}"
soup = fetch_html(block_url)
total_amount = get_total_output_amount(soup)
time_str = get_timestamp(soup)
if total_amount < THRESHOLD:
if SHOW_RESULT:
print(
f"總轉帳金額 {total_amount} SCASH 未達閾值 {THRESHOLD} SCASH,跳過後續查詢。")
return True
if SHOW_RESULT:
print(f"區塊高度: {block_height}")
txids = find_txids_by_amount(soup, total_amount)
if not txids:
if SHOW_RESULT:
print("未找到對應的 txid,無法查詢地址")
return True
all_rows_to_write = []
for txid in txids:
if SHOW_RESULT:
print(f"轉帳 TxID: {txid}")
outputs = get_tx_outputs(txid)
rows_to_write = []
for address, amount in outputs:
if amount < THRESHOLD:
continue
# 查詢地址餘額並記錄唯一地址
if address_balance_set is not None:
if address not in address_balance_set:
balance = get_address_balance(address)
if balance is not None and balance >= THRESHOLD:
address_balance_set.add(address)
write_address_balance_db(address, balance)
# 寫入轉帳紀錄
rows_to_write.append([
block_height, txid, address, amount, time_str
])
all_rows_to_write.extend(rows_to_write)
if all_rows_to_write:
write_transfer_db(all_rows_to_write)
else:
if SHOW_RESULT:
print("沒有符合條件的地址,未寫入任何資料。")
return True
except Exception as e:
print(f"查詢區塊 {block_height} 發生錯誤: {e}")
return False
def process_address(address):
balance = get_address_balance(address)
if SHOW_RESULT:
if balance is not None:
print(f"地址 {address} 目前持有 SCASH: {balance}")
else:
print("查詢失敗,請確認地址正確。")
def process_txid(txid):
outputs = get_tx_outputs(txid)
if SHOW_RESULT:
if not outputs:
print("此TxID無大額轉帳。")
return
print(f"TxID: {txid} 的輸出地址與金額:")
for address, amount in outputs:
print(f" 地址: {address} 金額: {amount} SCASH")
def main():
init_db()
while True:
print("\n選擇模式:")
print("1. 自動查詢模式 (可指定起始/結束區塊高度,直到手動停止)")
print("2. 手動查詢模式 (輸入區塊高度/地址/TxID)")
print("3. 設定檔設定模式 (修改 config.py 參數)")
print("4. 匯出 dashboard_data.js 檔案")
print("0. 離開")
mode = input("請輸入模式編號 (1/2/3/4/0): ").strip()
if mode == "1":
# 讀取 config.py 的 BLOCK_HEIGHT 作為預設值
try:
default_start = BLOCK_HEIGHT
except Exception:
default_start = 1
start = input(f"請輸入起始區塊高度 (預設 {default_start}): ").strip()
if not start:
start = default_start
end = input("請輸入結束區塊高度 (留空則查到失敗為止): ").strip()
start_height = int(start) if str(start).isdigit() else 1
end_height = int(end) if end.isdigit() else None
auto_query_mode(start_height, end_height)
elif mode == "2":
manual_query_mode()
elif mode == "3":
config_setting_mode()
elif mode == "4":
print("開始匯出 dashboard_data.js ...")
run_export_dashboard_data()
elif mode == "0":
print("程式結束。")
break
else:
print("輸入錯誤,請重新輸入。")
# 設定檔設定模式
def config_setting_mode():
config_path = os.path.join(os.path.dirname(__file__), 'config.py')
# 參數說明
param_desc = {
'BLOCK_HEIGHT': '查詢起始區塊高度',
'THRESHOLD': '大額轉帳的閾值(單位:SCASH)',
'BASE_URL': 'SCASH 區塊鏈的基礎 URL',
'DB_FILE': '資料儲存用 SQLite 檔案名稱',
'SHOW_RESULT': '是否顯示查詢結果',
'SCAN_INTERVAL': '自動查詢間隔秒數',
'SCAN_TRUE': '自動查詢模式是否自動更新所有地址餘額'
}
# 讀取現有設定與預設值
with open(config_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
config_vars = {}
default_vars = {}
for line in lines:
if '=' in line and not line.strip().startswith('#'):
key, val = line.split('=', 1)
key = key.strip()
val_clean = val.strip().split('#')[0].strip()
try:
config_vars[key] = ast.literal_eval(val_clean)
except Exception:
config_vars[key] = val_clean.strip('"\'')
# 預設值取等號右側第一個非註解內容
try:
default_vars[key] = ast.literal_eval(val_clean)
except Exception:
default_vars[key] = val_clean.strip('"\'')
while True:
print("\n目前設定:")
for k, v in config_vars.items():
desc = param_desc.get(k, '')
default_val = default_vars.get(k, '')
print(f"{k}: {desc}\n 當前值 = {v} (預設值: {default_val})")
print("\n可修改參數:")
for idx, k in enumerate(config_vars.keys(), 1):
desc = param_desc.get(k, '')
default_val = default_vars.get(k, '')
print(f"{idx}. {k} {desc} (預設值: {default_val})")
print("0. 儲存並返回主選單")
sel = input("請輸入要修改的參數編號 (或 0 返回): ").strip()
if sel == "0":
# 寫回 config.py
with open(config_path, 'w', encoding='utf-8') as f:
for line in lines:
if '=' in line and not line.strip().startswith('#'):
key = line.split('=', 1)[0].strip()
if key in config_vars:
comment = f" # {param_desc.get(key, '')}" if param_desc.get(
key, '') else ''
f.write(
f"{key} = {repr(config_vars[key])}{comment}\n")
else:
f.write(line)
else:
f.write(line)
print("設定已儲存,重新載入設定檔...\n")
# 重新 import config 並更新全域變數
import config as _config
importlib.reload(_config)
global BLOCK_HEIGHT, THRESHOLD, BASE_URL, SHOW_RESULT, SCAN_INTERVAL, DB_FILE, SCAN_TRUE
BLOCK_HEIGHT = _config.BLOCK_HEIGHT
THRESHOLD = _config.THRESHOLD
BASE_URL = _config.BASE_URL
SHOW_RESULT = _config.SHOW_RESULT
SCAN_INTERVAL = _config.SCAN_INTERVAL
DB_FILE = _config.DB_FILE
SCAN_TRUE = _config.SCAN_TRUE
print("設定已重新載入。返回主選單。\n")
break
try:
idx = int(sel) - 1
if idx < 0 or idx >= len(config_vars):
print("參數編號錯誤,請重新輸入。")
continue
key = list(config_vars.keys())[idx]
new_val = input(
f"請輸入新的值 ({key},目前值: {config_vars[key]}): ").strip()
if new_val == "":
print("空值,已維持原本設定。")
continue
# 嘗試自動型別轉換
try:
val = ast.literal_eval(new_val)
config_vars[key] = val
except Exception:
print("格式錯誤,已維持原本設定。")
continue
except Exception:
print("輸入錯誤,請重新輸入。")
def find_total_output_amount_until_found(block_height, retry_minutes=10):
"""
持續查找指定區塊的總輸出金額,找不到時每 retry_minutes 分鐘自動重試,直到找到或手動停止。
"""
while True:
try:
print(f"查詢區塊 {block_height} 的總輸出金額...")
block_url = f"{BASE_URL}/?search={block_height}"
soup = fetch_html(block_url)
amount = None
try:
amount = get_total_output_amount(soup)
except SystemExit:
amount = None
if amount is not None:
print(f"區塊 {block_height} 的總輸出金額為: {amount} SCASH")
return amount
else:
print(
f"無法找到區塊 {block_height} 的總輸出金額,{retry_minutes} 分鐘後自動重試...")
for i in range(retry_minutes*60, 0, -1):
print(
f" 等待 {i//60:02d}:{i%60:02d} 後重試... (Ctrl+C 可中止)", end='\r')
time.sleep(1)
print("\n重新嘗試...")
except KeyboardInterrupt:
print("\n偵測到中斷 (Ctrl+C),已停止自動查詢。")
break
except Exception as e:
print(f"查詢過程發生錯誤: {e}")
traceback.print_exc()
print(f"{retry_minutes} 分鐘後自動重試...")
for i in range(retry_minutes*60, 0, -1):
print(
f" 等待 {i//60:02d}:{i%60:02d} 後重試... (Ctrl+C 可中止)", end='\r')
time.sleep(1)
print("\n重新嘗試...")
if __name__ == "__main__":
main()