|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Union, Dict, Any, TYPE_CHECKING |
| 3 | +from typing import Optional |
| 4 | +from ..http_client import HttpClient, default_http_client |
| 5 | +from ..constants import Network |
| 6 | +from .whatsonchain import WhatsOnChainBroadcaster |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from ..transaction import Transaction |
| 10 | + |
| 11 | + |
| 12 | +class BroadcastResponse: |
| 13 | + def __init__(self, status: str, txid: str, message: str): |
| 14 | + self.status = status |
| 15 | + self.txid = txid |
| 16 | + self.message = message |
| 17 | + |
| 18 | + |
| 19 | +class BroadcastFailure: |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + status: str, |
| 23 | + code: str, |
| 24 | + description: str, |
| 25 | + txid: str = None, |
| 26 | + more: Dict[str, Any] = None, |
| 27 | + ): |
| 28 | + self.status = status |
| 29 | + self.code = code |
| 30 | + self.txid = txid |
| 31 | + self.description = description |
| 32 | + self.more = more |
| 33 | + |
| 34 | + |
| 35 | +class Broadcaster(ABC): |
| 36 | + def __init__(self): |
| 37 | + self.URL = None |
| 38 | + |
| 39 | + @abstractmethod |
| 40 | + async def broadcast( |
| 41 | + self, transaction: 'Transaction' |
| 42 | + ) -> Union[BroadcastResponse, BroadcastFailure]: |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +def is_broadcast_response(r: Union[BroadcastResponse, BroadcastFailure]) -> bool: |
| 47 | + return r.status == "success" |
| 48 | + |
| 49 | + |
| 50 | +def is_broadcast_failure(r: Union[BroadcastResponse, BroadcastFailure]) -> bool: |
| 51 | + return r.status == "error" |
| 52 | + |
| 53 | + |
| 54 | +class BroadcasterInterface: |
| 55 | + """Abstract broadcaster interface. |
| 56 | +
|
| 57 | + Implementations should return a dict with either: |
| 58 | + {"accepted": True, "txid": "..."} |
| 59 | + or {"accepted": False, "code": "network|client", "error": "..."} |
| 60 | + """ |
| 61 | + |
| 62 | + def broadcast(self, tx_hex: str, *, api_key: Optional[str] = None, timeout: int = 10) -> Dict[str, Any]: # noqa: D401 |
| 63 | + raise NotImplementedError |
| 64 | + |
| 65 | + |
| 66 | +class MAPIClientBroadcaster(BroadcasterInterface): |
| 67 | + """mAPI (Merchant API) broadcaster for BSV miners.""" |
| 68 | + def __init__(self, *, api_url: str, api_key: Optional[str] = None, network: str = "main"): |
| 69 | + self.api_url = api_url |
| 70 | + self.api_key = api_key or "" |
| 71 | + self.network = network |
| 72 | + |
| 73 | + def broadcast(self, tx_hex: str, *, api_key: Optional[str] = None, timeout: int = 10) -> Dict[str, Any]: |
| 74 | + url = self.api_url |
| 75 | + key = api_key or self.api_key |
| 76 | + headers = {"Content-Type": "application/json"} |
| 77 | + if key: |
| 78 | + headers["Authorization"] = key |
| 79 | + return self._post_with_retries(url, headers, tx_hex, timeout) |
| 80 | + |
| 81 | + def _post_with_retries(self, url, headers, tx_hex, timeout): |
| 82 | + import requests |
| 83 | + last_err: Optional[Exception] = None |
| 84 | + for attempt in range(3): |
| 85 | + try: |
| 86 | + resp = requests.post(url, json={"rawtx": tx_hex}, headers=headers, timeout=timeout) |
| 87 | + if resp.status_code >= 500: |
| 88 | + raise RuntimeError(f"mAPI server error {resp.status_code}") |
| 89 | + resp.raise_for_status() |
| 90 | + data = resp.json() or {} |
| 91 | + txid = data.get("txid") or data.get("payload", {}).get("txid") or "" |
| 92 | + if data.get("returnResult") == "success" or data.get("payload", {}).get("returnResult") == "success": |
| 93 | + return {"accepted": True, "txid": txid} |
| 94 | + return {"accepted": False, "error": data.get("resultDescription", "broadcast failed"), "txid": txid} |
| 95 | + except Exception as e: |
| 96 | + last_err = e |
| 97 | + try: |
| 98 | + time.sleep(0.25 * (2 ** attempt)) |
| 99 | + except Exception: |
| 100 | + pass |
| 101 | + msg = str(last_err or "broadcast failed") |
| 102 | + code = "network" if "server error" in msg or "timeout" in msg.lower() else "client" |
| 103 | + return {"accepted": False, "code": code, "error": f"mAPI broadcast failed: {msg}"} |
| 104 | + |
| 105 | +class CustomNodeBroadcaster(BroadcasterInterface): |
| 106 | + """Custom node broadcaster (e.g., direct to bitcoind REST).""" |
| 107 | + def __init__(self, *, api_url: str, api_key: Optional[str] = None): |
| 108 | + self.api_url = api_url |
| 109 | + self.api_key = api_key or "" |
| 110 | + |
| 111 | + def broadcast(self, tx_hex: str, *, api_key: Optional[str] = None, timeout: int = 10) -> Dict[str, Any]: |
| 112 | + import requests |
| 113 | + key = api_key or self.api_key |
| 114 | + headers = {"Content-Type": "application/json"} |
| 115 | + if key: |
| 116 | + headers["Authorization"] = key |
| 117 | + url = self.api_url |
| 118 | + last_err: Optional[Exception] = None |
| 119 | + for attempt in range(3): |
| 120 | + try: |
| 121 | + resp = requests.post(url, json={"hex": tx_hex}, headers=headers, timeout=timeout) |
| 122 | + if resp.status_code >= 500: |
| 123 | + raise RuntimeError(f"custom node server error {resp.status_code}") |
| 124 | + resp.raise_for_status() |
| 125 | + data = resp.json() or {} |
| 126 | + txid = data.get("txid") or data.get("result") or "" |
| 127 | + if txid: |
| 128 | + return {"accepted": True, "txid": txid} |
| 129 | + return {"accepted": False, "error": data.get("error", "broadcast failed"), "txid": txid} |
| 130 | + except Exception as e: |
| 131 | + last_err = e |
| 132 | + try: |
| 133 | + time.sleep(0.25 * (2 ** attempt)) |
| 134 | + except Exception: |
| 135 | + pass |
| 136 | + msg = str(last_err or "broadcast failed") |
| 137 | + code = "network" if "server error" in msg or "timeout" in msg.lower() else "client" |
| 138 | + return {"accepted": False, "code": code, "error": f"Custom node broadcast failed: {msg}"} |
| 139 | + |
| 140 | + |
| 141 | +def default_broadcaster(network: Union[Network, str] = Network.MAINNET, http_client: HttpClient = None) -> Broadcaster: |
| 142 | + return WhatsOnChainBroadcaster(network=network, http_client=http_client) |
| 143 | + |
| 144 | +__all__ = [ |
| 145 | + "BroadcastResponse", |
| 146 | + "BroadcastFailure", |
| 147 | + "Broadcaster", |
| 148 | + "is_broadcast_response", |
| 149 | + "is_broadcast_failure", |
| 150 | +] |
0 commit comments