Debian Codegraph @

tests/toyserver/toyserver.py

raw symbols SCIP
1 # Copyright (C) 2026 The Electrum developers
2 # Distributed under the MIT software license, see the accompanying
3 # file LICENCE or http://www.opensource.org/licenses/mit-license.php
4
5 import asyncio
6 import collections
7 from dataclasses import dataclass
8 from functools import partial
9 from typing import Optional, Sequence, Iterable, List, Set, Callable, TypeVar
10
11 import aiorpcx
12 from aiorpcx import RPCError
13
14 from electrum import blockchain
15 from electrum.util import bfh, OrderedSet
16 from electrum.logging import Logger
17 from electrum.transaction import Transaction, TxOutput, TxInput, TxOutpoint, PartialTxOutput
18 from electrum import constants
19 from electrum.bitcoin import script_to_scripthash, COIN, COINBASE_MATURITY
20 from electrum.simple_config import SimpleConfig
21 from electrum.synchronizer import history_status
22 from electrum.wallet import Abstract_Wallet
23 from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED
24 from electrum.fee_policy import FixedFeePolicy
25
26 from .. import restore_wallet_from_text__for_unittest
27
28
29 DAEMON_ERROR = 2
30
31 REGTEST_GENESIS_HEADER = bfh("0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4adae5494dffff7f2002000000")
32
33 T = TypeVar("T")
34
35 def topologically_sort_subgraph(
36 start_nodes: Iterable[T],
37 *,
38 get_direct_children: Callable[[T], Iterable[T]],
39 ) -> Sequence[T]:
40 # based on pseudo-code in https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
41 res = OrderedSet() # "permanent mark"
42 seen = set() # "temporary mark"
43
44 def recurse(node: str):
45 if node in res:
46 return
47 if node in seen:
48 raise Exception("cycle detected")
49 seen.add(node)
50 direct_children = get_direct_children(node)
51 for child in direct_children:
52 recurse(child)
53 res.add(node)
54
55 for start_node in start_nodes:
56 if start_node not in res:
57 recurse(start_node)
58 return list(res)[::-1]
59
60
61
62 @dataclass(kw_only=True, slots=True, frozen=True)
63 class FakeBlock:
64 header: bytes
65 txids: Sequence[str] = None # FIXME needs OrderedSet with index-based lookup? >.<
66
67 def __post_init__(self):
68 if self.txids is None:
69 object.__setattr__(self, 'txids', tuple())
70
71
72 class TxConflicts(Exception): pass
73 class TxConflictsMempool(TxConflicts): pass
74 class TxConflictsBlockchain(TxConflicts): pass
75
76
77 class ToyServer(Logger):
78 """Electrum Server backend"""
79
80 asyncio_server: asyncio.base_events.Server
81 server_port: int
82 min_relay_feerate = 2000 # in satoshi per kvbyte
83
84 def __init__(self):
85 Logger.__init__(self)
86 self.sessions = set() # type: Set[ToyServerSession]
87 self._blocks = [FakeBlock(header=REGTEST_GENESIS_HEADER)] # type: list[FakeBlock]
88
89 # indexes:
90 self.sh_to_funding_txids = collections.defaultdict(set) # type: dict[str, set[str]]
91 self.sh_to_spending_txids = collections.defaultdict(set) # type: dict[str, set[str]]
92 self.txs = {} # type: dict[str, bytes] # txid->raw_tx
93 self._cache_blockheight_and_pos_from_txid = {} # type: dict[str, tuple[int, int]]
94 self.txo_to_spender_txid = {} # type: dict[TxOutpoint, str | None] # also contains UTXOs
95
96 self._faucet_w = None # type: Optional[Abstract_Wallet]
97
98 async def start(self):
99 session_factory = partial(ToyServerSession, toyserver=self)
100 self.asyncio_server = await aiorpcx.serve_rs(session_factory, "127.0.0.1")
101 server_socket_addr = self.asyncio_server.sockets[0].getsockname()
102 self.server_port = server_socket_addr[1]
103
104 async def stop(self):
105 self.asyncio_server.close()
106 await self.asyncio_server.wait_closed()
107
108 def block_height_and_pos_from_txid(self, txid: str) -> Optional[tuple[int, int]]: # FIXME slow
109 # check cache first
110 if (bh_and_pos := self._cache_blockheight_and_pos_from_txid.get(txid)) is not None:
111 height, pos = bh_and_pos
112 if (len(self._blocks) > height
113 and len(self._blocks[height].txids) > pos
114 and txid == self._blocks[height].txids[pos]
115 ):
116 # valid cache hit
117 return height, pos
118 else: # stale cache
119 self._cache_blockheight_and_pos_from_txid.pop(txid)
120 # linear search
121 for height, block in enumerate(self._blocks):
122 for pos, txid2 in enumerate(block.txids):
123 if txid == txid2:
124 self._cache_blockheight_and_pos_from_txid[txid] = height, pos
125 return height, pos
126 return None
127
128 def block_height_from_txid(self, txid: str) -> Optional[int]:
129 bh_and_pos = self.block_height_and_pos_from_txid(txid)
130 if bh_and_pos is None:
131 return None
132 bh, pos = bh_and_pos
133 return bh
134
135 def get_mempool_txids(self) -> set[str]: # FIXME slow
136 mempool = set()
137 for txid in self.txs:
138 if self.block_height_from_txid(txid) is None:
139 mempool.add(txid)
140 return mempool
141
142 def get_session_by_name(self, client_name: str) -> 'ToyServerSession':
143 found_sessions = [
144 session for session in self.sessions
145 if session.client_name == client_name]
146 if len(found_sessions) > 1:
147 raise Exception("multiple sessions reusing client_name")
148 elif len(found_sessions) == 0:
149 raise Exception("no session with given client_name")
150 else:
151 assert len(found_sessions) == 1
152 return found_sessions[0]
153
154 @property
155 def cur_height(self) -> int:
156 """chain tip"""
157 return len(self._blocks) - 1
158
159 def get_block_header(self, height: int) -> bytes:
160 return self._blocks[height].header
161
162 def _has_unconfirmed_inputs(self, txid: str) -> bool:
163 tx = Transaction(self.txs[txid])
164 return any(self.block_height_from_txid(txin.prevout.txid.hex()) is None for txin in tx.inputs())
165
166 def calc_sh_history(self, sh: str) -> Sequence[tuple[str, int]]:
167 txids = self.sh_to_funding_txids[sh] | self.sh_to_spending_txids[sh]
168 hist1 = []
169 for txid in txids:
170 bh_and_pos = self.block_height_and_pos_from_txid(txid)
171 if bh_and_pos is None:
172 bh_and_pos = (0, 0) if not self._has_unconfirmed_inputs(txid) else (-1, 0)
173 hist1.append((txid, bh_and_pos))
174
175 def sort_key(x):
176 txid, (bh, pos) = x
177 if bh <= 0:
178 bh = 10**9 - bh
179 return bh, pos, txid
180
181 hist1.sort(key=sort_key)
182 hist2 = [(txid, bh) for (txid, (bh, pos)) in hist1]
183 return hist2
184
185 def _get_funded_and_spent_scripthashes(self, tx: Transaction) -> tuple[set[str], set[str]]:
186 """Returns scripthashes touched by tx."""
187 txid = tx.txid()
188 assert txid
189 funded_sh = set()
190 for txout in tx.outputs():
191 sh = script_to_scripthash(txout.scriptpubkey)
192 funded_sh.add(sh)
193 spent_sh = set()
194 for txin in tx.inputs():
195 if txin.is_coinbase_input():
196 continue
197 parent_tx_raw = self.txs[txin.prevout.txid.hex()] # parent must not be missing!
198 parent_tx = Transaction(parent_tx_raw)
199 ptxout = parent_tx.outputs()[txin.prevout.out_idx]
200 sh = script_to_scripthash(ptxout.scriptpubkey)
201 spent_sh.add(sh)
202 return funded_sh, spent_sh
203
204 def _add_tx(self, tx: Transaction) -> set[str]:
205 txid = tx.txid()
206 assert txid
207 if txid in self.txs: # already added
208 funded_sh, spent_sh = self._get_funded_and_spent_scripthashes(tx)
209 return funded_sh | spent_sh
210 # we forbid conflicting txs. for mempool replacement, the caller must already have rm-ed the conflicts.
211 conflict_txids = self._get_transitive_conflict_txids(tx)
212 assert not conflict_txids, "tx conflict"
213 self.logger.debug(f"_add_tx: {txid}")
214 # update txid->tx map
215 self.txs[txid] = bfh(str(tx))
216 # fund UTXOs
217 for txout_idx, txout in enumerate(tx.outputs()):
218 outpoint = TxOutpoint(txid=bfh(txid), out_idx=txout_idx)
219 self.txo_to_spender_txid[outpoint] = None
220 # spend UTXOs
221 for txin in tx.inputs():
222 if txin.is_coinbase_input():
223 continue
224 double_spender_txid = self.txo_to_spender_txid.get(txin.prevout, ...)
225 if double_spender_txid is ...:
226 raise Exception(f"cannot spend non-existent UTXO: {txin.prevout}")
227 elif double_spender_txid is None: # UTXO exists and is unspent
228 self.txo_to_spender_txid[txin.prevout] = txid
229 elif double_spender_txid == txid:
230 raise Exception("TXO already marked as spent by same txid?")
231 else:
232 raise Exception(f"cannot double-spend UTXO: {txin.prevout}. conflict: {txid} vs {double_spender_txid}")
233 # update touched scripthashes
234 funded_sh, spent_sh = self._get_funded_and_spent_scripthashes(tx)
235 for sh in funded_sh:
236 self.sh_to_funding_txids[sh].add(txid)
237 for sh in spent_sh:
238 self.sh_to_spending_txids[sh].add(txid)
239 return funded_sh | spent_sh
240
241 def _remove_tx_that_has_no_children(self, tx: Transaction) -> set[str]:
242 txid = tx.txid()
243 assert txid
244 self.logger.debug(f"_remove_tx_that_has_no_children: {txid}")
245 assert self.block_height_from_txid(txid) is None, "tx already mined"
246 self.txs.pop(txid)
247 # un-fund UTXOs
248 for txout_idx, txout in enumerate(tx.outputs()):
249 outpoint = TxOutpoint(txid=bfh(txid), out_idx=txout_idx)
250 assert self.txo_to_spender_txid[outpoint] is None, "output already spent"
251 self.txo_to_spender_txid.pop(outpoint)
252 # un-spend UTXOs
253 for txin in tx.inputs():
254 if txin.is_coinbase_input():
255 continue
256 assert self.txo_to_spender_txid[txin.prevout] == txid
257 self.txo_to_spender_txid[txin.prevout] = None
258 # update touched scripthashes
259 funded_sh, spent_sh = self._get_funded_and_spent_scripthashes(tx)
260 for sh in funded_sh:
261 self.sh_to_funding_txids[sh].discard(txid)
262 for sh in spent_sh:
263 self.sh_to_spending_txids[sh].discard(txid)
264 return funded_sh | spent_sh
265
266 def _remove_tx_and_all_children(self, tx: Transaction) -> set[str]:
267 txid = tx.txid()
268 assert txid
269 assert txid in self.txs, "unknown tx"
270 children = self._get_transitive_children_txids(txid)
271 touched_sh = set()
272 for txid in children:
273 tx = Transaction(self.txs[txid])
274 touched_sh |= self._remove_tx_that_has_no_children(tx)
275 return touched_sh
276
277 def _get_direct_children_txids(self, txid: str) -> Sequence[str]:
278 res = []
279 tx = Transaction(self.txs[txid])
280 for txout_idx, txout in enumerate(tx.outputs()):
281 outpoint = TxOutpoint(txid=bfh(txid), out_idx=txout_idx)
282 if spender_txid := self.txo_to_spender_txid[outpoint]:
283 res.append(spender_txid)
284 return res
285
286 def _get_transitive_children_txids(self, txid: str) -> Sequence[str]:
287 """Returns all (grand-)children, including orig tx.
288 Topologically sorted, children first.
289 """
290 return topologically_sort_subgraph([txid], get_direct_children=self._get_direct_children_txids)[::-1]
291
292 def _get_direct_conflict_txids(self, tx: Transaction, *, include_self: bool = True) -> Sequence[str]:
293 txid = tx.txid()
294 assert txid
295 res = []
296 for txin in tx.inputs():
297 if txin.is_coinbase_input():
298 continue
299 if double_spender_txid := self.txo_to_spender_txid.get(txin.prevout, None):
300 if double_spender_txid != txid or include_self:
301 res.append(double_spender_txid)
302 return res
303
304 def _get_transitive_conflict_txids(self, tx: Transaction, *, include_self: bool = True) -> Iterable[str]:
305 res = set()
306 for direct_conflict in self._get_direct_conflict_txids(tx, include_self=include_self):
307 res |= set(self._get_transitive_children_txids(direct_conflict))
308 return res
309
310 def _txs_from_txids(self, txids: Iterable[str]) -> Iterable[Transaction]:
311 return [Transaction(self.txs[txid]) for txid in txids]
312
313 def _get_fee_sat_paid_by_tx(self, tx: Transaction) -> int:
314 input_sum = 0
315 for txin in tx.inputs():
316 parent_tx_raw = self.txs[txin.prevout.txid.hex()] # parent must not be missing!
317 parent_tx = Transaction(parent_tx_raw)
318 ptxout = parent_tx.outputs()[txin.prevout.out_idx]
319 input_sum += ptxout.value
320 return input_sum - tx.output_value()
321
322 async def mempool_add_tx(self, newtx: Transaction) -> None:
323 touched_sh = set()
324 conflict_txids = self._get_transitive_conflict_txids(newtx, include_self=False)
325 conflict_txs = self._txs_from_txids(conflict_txids)
326 if conflict_txids:
327 if any(self.block_height_from_txid(txid) is not None for txid in conflict_txids):
328 raise TxConflictsBlockchain()
329 conflict_wu = sum(tx.estimated_weight() for tx in conflict_txs)
330 conflict_fee = sum(self._get_fee_sat_paid_by_tx(tx) for tx in conflict_txs)
331 conflict_sat_per_kvbyte = 4000 * conflict_fee // conflict_wu
332 repl_fee = self._get_fee_sat_paid_by_tx(newtx)
333 repl_sat_per_kvbyte = 4000 * repl_fee // newtx.estimated_weight()
334 # our mempool replacement policy is simple but still similar to bitcoin core:
335 if not (
336 repl_fee > conflict_fee
337 and repl_sat_per_kvbyte >= conflict_sat_per_kvbyte + self.min_relay_feerate
338 ):
339 raise TxConflictsMempool(f"mempool conflict. {len(conflict_txs)=}. {repl_fee=}, {conflict_fee=}. {repl_sat_per_kvbyte=}, {conflict_sat_per_kvbyte=}")
340 # rm conflicts
341 for tx in conflict_txs:
342 if tx.txid() in self.txs: # might already be removed in an earlier loop iter
343 touched_sh = self._remove_tx_and_all_children(tx)
344 # no more conflicts. add new tx.
345 touched_sh |= self._add_tx(newtx)
346 # notify clients
347 for session in self.sessions:
348 await session.server_send_notifications(touched_sh=touched_sh)
349
350 async def mempool_rm_tx(self, tx: Transaction) -> None:
351 txid = tx.txid()
352 assert txid
353 assert txid in self.txs, "unknown tx"
354 assert self.block_height_from_txid(txid) is None, "tx already mined"
355 touched_sh = self._remove_tx_and_all_children(tx)
356 # notify clients
357 for session in self.sessions:
358 await session.server_send_notifications(touched_sh=touched_sh)
359
360 async def mine_block(
361 self,
362 *,
363 coinbase_outputs: Iterable[TxOutput] = None,
364 include_mempool: bool = True, # whether to mine (all) txs in the mempool
365 extra_txs: Iterable[Transaction] = None, # additional txs to mine. can overlap with mempool
366 ) -> tuple[FakeBlock, Transaction]:
367 if extra_txs is None:
368 extra_txs = []
369 coinbase_tx = Transaction(None)
370 coinbase_tx._inputs = [TxInput(prevout=TxOutpoint(txid=bytes(32), out_idx=0xffffffff))]
371 coinbase_tx._outputs = list(coinbase_outputs or []) + [TxOutput(scriptpubkey=bfh("6a04deadbeef"), value=0)]
372 coinbase_tx._locktime = self.cur_height # to prevent duplicate txids (our fake coinbase txs are low-entropy)
373 txs = OrderedSet() # type: OrderedSet[Transaction]
374 txs.add(coinbase_tx)
375 txs |= OrderedSet(extra_txs)
376 if include_mempool:
377 for mempool_txid in self.get_mempool_txids():
378 mempool_tx = Transaction(self.txs[mempool_txid])
379 txs.add(mempool_tx)
380 assert not any(tx.txid() is None for tx in txs)
381 # new header
382 prev_header = self._blocks[-1].header
383 prev_blockhash = blockchain.hash_raw_header(prev_header)
384 new_header = blockchain.serialize_header({
385 'version': 99999, # don't care
386 'prev_block_hash': prev_blockhash,
387 'merkle_root': 'deadbeef' * 8, # don't care
388 'timestamp': 1_500_000_000, # don't care
389 'bits': 0x1d00ffff, # don't care
390 'nonce': 1, # don't care
391 })
392 new_block = FakeBlock(header=new_header, txids=tuple(tx.txid() for tx in txs))
393 self._blocks.append(new_block)
394 # process txs
395 touched_sh = set()
396 for tx in txs:
397 touched_sh |= self._add_tx(tx)
398 # notify clients
399 for session in self.sessions:
400 await session.server_send_notifications(touched_sh=touched_sh, height_changed=True)
401 return new_block, coinbase_tx
402
403 async def unmine_block(self) -> None:
404 if self.cur_height == 0:
405 raise Exception("cannot unmine genesis")
406 # Simply pop the block from the chain.
407 block = self._blocks.pop()
408 # process txs
409 # note: all txs in that block are now automatically considered to be in-mempool.
410 # no need to call _remove_tx -- that would also rm them from the mempool.
411 touched_sh = set()
412 for txid in block.txids:
413 tx = Transaction(self.txs[txid])
414 funded_sh, spent_sh = self._get_funded_and_spent_scripthashes(tx)
415 touched_sh |= funded_sh | spent_sh
416 # notify clients
417 for session in self.sessions:
418 await session.server_send_notifications(touched_sh=touched_sh, height_changed=True)
419
420 async def set_up_faucet(self, *, config: SimpleConfig):
421 assert self._faucet_w is None
422 # FIXME we should give the faucet multiple UTXOs so that later it won't have to chain unconfirmed txs
423 # but this is broken atm: the faucet does not have a network so can't know which coins are mined.
424 # faucet_w considers all its UTXOs to be unconfirmed.
425 num_starting_utxos = 2
426 self._faucet_w = restore_wallet_from_text__for_unittest(
427 "9dk", passphrase="faucet", path=None, config=config, gap_limit=num_starting_utxos)['wallet'] # type: Abstract_Wallet
428 self._faucet_w.adb.get_local_height = lambda *args: self.cur_height
429 for faucet_addr in self._faucet_w.get_receiving_addresses():
430 block, cb_tx = await self.mine_block(coinbase_outputs=[TxOutput.from_address_and_value(faucet_addr, 50 * COIN)])
431 self._faucet_w.adb.receive_tx_callback(cb_tx, tx_height=self.cur_height)
432 for _ in range(COINBASE_MATURITY): # need to mine some blocks for maturity
433 await self.mine_block()
434 # note: balance is unverified due to lack of SPV, gets treated as "unconfirmed":
435 assert self._faucet_w.get_balance() == (0, 50 * COIN * num_starting_utxos, 0), self._faucet_w.get_balance()
436
437 async def ask_faucet(self, outputs: Sequence[TxOutput]) -> Transaction:
438 assert self._faucet_w, "faucet must be set up first using set_up_faucet()"
439 outputs = [PartialTxOutput.from_txout(txout) for txout in outputs]
440 tx = self._faucet_w.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(0))
441 self._faucet_w.sign_transaction(tx, password=None)
442 self._faucet_w.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
443 await self.mempool_add_tx(tx)
444 return tx
445
446
447 class ToyServerSession(aiorpcx.RPCSession, Logger):
448 """Server-side representation of a single electrum-protocol session."""
449
450 def __init__(self, *args, toyserver: ToyServer, **kwargs):
451 aiorpcx.RPCSession.__init__(self, *args, **kwargs)
452 Logger.__init__(self)
453 self.svr = toyserver
454 self.logger.debug(f'connection from {self.remote_address()}')
455 self.subbed_headers = False
456 self.notified_height = None # type: Optional[int]
457 self.subbed_scripthashes = set() # type: set[str]
458 self._method_counts = collections.defaultdict(int) # type: dict[str, int]
459 self.client_name = None
460 self.got_disconnected = asyncio.Event()
461 self.svr.sessions.add(self)
462
463 async def connection_lost(self):
464 await super().connection_lost()
465 self.logger.debug(f'{self.remote_address()} disconnected')
466 self.svr.sessions.discard(self)
467 self.got_disconnected.set()
468
469 async def handle_request(self, request):
470 handlers = {
471 'server.version': self._handle_server_version,
472 'server.features': self._handle_server_features,
473 'blockchain.estimatefee': self._handle_estimatefee,
474 'blockchain.headers.subscribe': self._handle_headers_subscribe,
475 'blockchain.block.header': self._handle_block_header,
476 'blockchain.block.headers': self._handle_block_headers,
477 'blockchain.scripthash.subscribe': self._handle_scripthash_subscribe,
478 'blockchain.scripthash.get_history': self._handle_scripthash_get_history,
479 'blockchain.transaction.get': self._handle_transaction_get,
480 'blockchain.transaction.broadcast': self._handle_transaction_broadcast,
481 'blockchain.transaction.get_merkle': self._handle_transaction_get_merkle,
482 'mempool.get_info': self._handle_mempool_get_info,
483 'server.ping': self._handle_ping,
484 }
485 handler = handlers.get(request.method)
486 self._method_counts[request.method] += 1
487 coro = aiorpcx.handler_invocation(handler, request)()
488 return await coro
489
490 async def _handle_server_version(self, client_name='', protocol_version=None, *args, **kwargs):
491 self.client_name = client_name
492 return ['toyserver/0.1', '1.6']
493
494 async def _handle_server_features(self) -> dict:
495 return {
496 'genesis_hash': constants.net.GENESIS,
497 'hosts': {"14.3.140.101": {"tcp_port": 51001, "ssl_port": 51002}},
498 'protocol_max': '1.6',
499 'protocol_min': '1.6',
500 'pruning': None,
501 'server_version': 'ElectrumX 1.19.0',
502 'hash_function': 'sha256',
503 }
504
505 async def _handle_estimatefee(self, number, mode=None):
506 return 0.00001000
507
508 async def _handle_mempool_get_info(self):
509 return {
510 "mempoolminfee": self.svr.min_relay_feerate / COIN,
511 "minrelaytxfee": self.svr.min_relay_feerate / COIN,
512 "incrementalrelayfee": self.svr.min_relay_feerate / COIN,
513 }
514
515 def _get_headersub_result(self):
516 height = self.svr.cur_height
517 return {'hex': self.svr.get_block_header(height).hex(), 'height': height}
518
519 async def _handle_headers_subscribe(self):
520 self.subbed_headers = True
521 return self._get_headersub_result()
522
523 async def _handle_block_header(self, height):
524 return self.svr.get_block_header(height).hex()
525
526 async def _handle_block_headers(self, start_height, count):
527 cur_height = self.svr.cur_height
528 assert start_height <= cur_height, (start_height, cur_height)
529 last_height = min(start_height+count-1, cur_height) # [start_height, last_height]
530 count = last_height - start_height + 1
531 headers = list(self.svr.get_block_header(idx).hex() for idx in range(start_height, last_height + 1))
532 return {'headers': headers, 'count': count, 'max': 2016}
533
534 async def _handle_ping(self):
535 return None
536
537 async def _handle_transaction_get(self, tx_hash: str, verbose=False):
538 assert not verbose
539 rawtx = self.svr.txs.get(tx_hash)
540 if rawtx is None:
541 raise RPCError(DAEMON_ERROR, f'daemon error: unknown txid={tx_hash}')
542 return rawtx.hex()
543
544 async def _handle_transaction_get_merkle(self, tx_hash: str, height: int) -> dict:
545 # Fake stuff. Client will ignore it due to config.NETWORK_SKIPMERKLECHECK
546 return {
547 "merkle":
548 [
549 "713d6c7e6ce7bbea708d61162231eaa8ecb31c4c5dd84f81c20409a90069cb24",
550 "03dbaec78d4a52fbaf3c7aa5d3fccd9d8654f323940716ddf5ee2e4bda458fde",
551 "e670224b23f156c27993ac3071940c0ff865b812e21e0a162fe7a005d6e57851",
552 "369a1619a67c3108a8850118602e3669455c70cdcdb89248b64cc6325575b885",
553 "4756688678644dcb27d62931f04013254a62aeee5dec139d1aac9f7b1f318112",
554 "7b97e73abc043836fd890555bfce54757d387943a6860e5450525e8e9ab46be5",
555 "61505055e8b639b7c64fd58bce6fc5c2378b92e025a02583303f69930091b1c3",
556 "27a654ff1895385ac14a574a0415d3bbba9ec23a8774f22ec20d53dd0b5386ff",
557 "5312ed87933075e60a9511857d23d460a085f3b6e9e5e565ad2443d223cfccdc",
558 "94f60b14a9f106440a197054936e6fb92abbd69d6059b38fdf79b33fc864fca0",
559 "2d64851151550e8c4d337f335ee28874401d55b358a66f1bafab2c3e9f48773d"
560 ],
561 "block_height": height,
562 "pos": 710,
563 }
564
565 async def _handle_transaction_broadcast(self, raw_tx: str) -> str:
566 tx = Transaction(raw_tx)
567 txid = tx.txid()
568 try:
569 await self.svr.mempool_add_tx(tx) # TODO don't await, just queue up? this sends notifs before response, lol
570 except TxConflicts as e:
571 raise RPCError(DAEMON_ERROR, str(e)) from e
572 return txid
573
574 async def _handle_scripthash_subscribe(self, sh: str) -> Optional[str]:
575 self.subbed_scripthashes.add(sh)
576 hist = self.svr.calc_sh_history(sh)
577 return history_status(hist)
578
579 async def _handle_scripthash_get_history(self, sh: str) -> Sequence[dict]:
580 hist_tuples = self.svr.calc_sh_history(sh)
581 hist_dicts = [{"height": height, "tx_hash": txid} for (txid, height) in hist_tuples]
582 for hist_dict in hist_dicts: # add "fee" key for mempool txs
583 if hist_dict["height"] in (0, -1,):
584 hist_dict["fee"] = 0
585 return hist_dicts
586
587 async def server_send_notifications(self, *, touched_sh: Iterable[str], height_changed: bool = False) -> None:
588 if height_changed and self.subbed_headers and self.notified_height != self.svr.cur_height:
589 self.notified_height = self.svr.cur_height
590 args = (self._get_headersub_result(),)
591 await self.send_notification('blockchain.headers.subscribe', args)
592 touched_sh = set(sh for sh in touched_sh if sh in self.subbed_scripthashes)
593 for sh in touched_sh:
594 hist = self.svr.calc_sh_history(sh)
595 args = (sh, history_status(hist))
596 await self.send_notification("blockchain.scripthash.subscribe", args)
597