Debian Codegraph @

tests/toyserver/test_toyserver.py

raw symbols SCIP
1 import electrum_ecc as ecc
2
3 from electrum import bitcoin
4 from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED
5 from electrum.bitcoin import COIN, construct_script, opcodes
6 from electrum.fee_policy import FixedFeePolicy
7 from electrum.simple_config import SimpleConfig
8 from electrum.transaction import PartialTxInput, PartialTxOutput, TxOutput, Transaction
9 from electrum.wallet import Abstract_Wallet
10
11 from .. import ElectrumTestCase
12 from .. import restore_wallet_from_text__for_unittest
13 from .toyserver import ToyServer, topologically_sort_subgraph, TxConflicts, TxConflictsBlockchain
14
15
16 class TestToyServer(ElectrumTestCase):
17 REGTEST = True
18
19 async def asyncSetUp(self):
20 await super().asyncSetUp()
21 self.config = SimpleConfig({'electrum_path': self.electrum_path})
22 self.toyserver = ToyServer()
23 await self.toyserver.start()
24 assert self.toyserver.cur_height == 0
25 for _ in range(10): # mine some blocks
26 await self.toyserver.mine_block()
27 await self.toyserver.set_up_faucet(config=self.config)
28 assert len(self.toyserver.get_mempool_txids()) == 0
29
30 async def asyncTearDown(self):
31 await self.toyserver.stop()
32 await super().asyncTearDown()
33
34 async def test_topological_sort(self):
35 graph = {
36 "A": ["B", "C"],
37 "B": ["X"],
38 "C": ["D1"],
39 "D1": ["D2"],
40 "D2": ["D3"],
41 "D3": ["D4"],
42 "D4": ["X"],
43 "X": ["Y"],
44 "Y": [],
45 }
46 get_direct_children = lambda x: graph[x]
47 # note: there are multiple valid orderings, not just the one we assert
48 self.assertEqual(
49 ["A", "C", "D1", "D2", "D3", "D4", "B", "X", "Y"],
50 topologically_sort_subgraph(["A"], get_direct_children=get_direct_children))
51 self.assertEqual(
52 ["A", "C", "D1", "D2", "D3", "D4", "B", "X", "Y"],
53 topologically_sort_subgraph(list(graph), get_direct_children=get_direct_children))
54
55 graph = {
56 "B": ["X"],
57 "C": ["D1"],
58 "D1": ["D2"],
59 "D2": ["D3"],
60 "D3": ["D4"],
61 "D4": ["X"],
62 "X": ["Y"],
63 "Y": [],
64 }
65 self.assertEqual(
66 ["C", "D1", "D2", "D3", "D4", "B", "X", "Y"],
67 topologically_sort_subgraph(["B", "C"], get_direct_children=get_direct_children))
68
69
70 async def test_basic_mempool_and_mining_txs(self):
71 server_height = self.toyserver.cur_height
72 self.assertEqual(self.toyserver.get_mempool_txids(), set())
73 secret_key = 0
74 for cycle in range(2):
75 mempool_txids = set()
76 # populate mempool
77 for _ in range(5):
78 secret_key += 1
79 spk = construct_script([secret_key * ecc.GENERATOR.get_public_key_bytes(compressed=True), opcodes.OP_CHECKSIG])
80 txout = TxOutput(scriptpubkey=spk, value=1 * COIN)
81 tx = await self.toyserver.ask_faucet([txout])
82 mempool_txids.add(tx.txid())
83 self.assertEqual(mempool_txids, self.toyserver.get_mempool_txids())
84 self.assertEqual(None, self.toyserver.block_height_from_txid(tx.txid()))
85 # mine a block
86 await self.toyserver.mine_block()
87 server_height += 1
88 self.assertEqual(server_height, self.toyserver.cur_height)
89 self.assertEqual(set(), self.toyserver.get_mempool_txids())
90 for txid in mempool_txids: # old mempool
91 self.assertEqual(server_height, self.toyserver.block_height_from_txid(txid))
92
93 async def test_mempool_replacement(self):
94 self.assertEqual(self.toyserver.get_mempool_txids(), set())
95
96 w = restore_wallet_from_text__for_unittest("9dk", path=None, config=self.config, gap_limit=4)['wallet'] # type: Abstract_Wallet
97 # fund w
98 w_addr0 = w.get_receiving_addresses()[0]
99 funding_tx = await self.toyserver.ask_faucet([TxOutput.from_address_and_value(w_addr0, 20 * COIN)])
100 w.adb.add_transaction(funding_tx)
101 self.assertEqual(self.toyserver.get_mempool_txids(), {funding_tx.txid()})
102 # wallet sends all to itself on fresh address: tx1
103 w_addr1 = w.get_receiving_addresses()[1]
104 tx1 = w.make_unsigned_transaction(
105 outputs=[PartialTxOutput.from_address_and_value(w_addr1, "!")], fee_policy=FixedFeePolicy(5000))
106 w.sign_transaction(tx1, password=None)
107 w.adb.add_transaction(tx1)
108 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1), set())
109 await self.toyserver.mempool_add_tx(tx1)
110 self.assertEqual(self.toyserver.get_mempool_txids(), {funding_tx.txid(), tx1.txid()})
111 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1, include_self=False), set())
112 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1, include_self=True), {tx1.txid()})
113 # wallet sends all to itself on fresh address: tx2
114 w_addr2 = w.get_receiving_addresses()[2]
115 tx2 = w.make_unsigned_transaction(
116 outputs=[PartialTxOutput.from_address_and_value(w_addr2, "!")], fee_policy=FixedFeePolicy(5000))
117 w.sign_transaction(tx2, password=None)
118 w.adb.add_transaction(tx2)
119 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx2), set())
120 await self.toyserver.mempool_add_tx(tx2)
121 self.assertEqual(self.toyserver.get_mempool_txids(), {funding_tx.txid(), tx1.txid(), tx2.txid()})
122
123 self.assertEqual(len(w.adb.get_history(w.get_addresses())), 3)
124
125 # -- wallet wants to double-spend tx1 (also invalidating tx2)
126 # first, wallet tries tx1b, but uses too low fee
127 w.adb.remove_transaction(tx1.txid())
128 self.assertEqual(len(w.adb.get_history(w.get_addresses())), 1)
129 w_addr3 = w.get_receiving_addresses()[3]
130 tx1b = w.make_unsigned_transaction(
131 outputs=[PartialTxOutput.from_address_and_value(w_addr3, "!")], fee_policy=FixedFeePolicy(5000))
132 w.sign_transaction(tx1b, password=None)
133 w.adb.add_transaction(tx1b)
134 self.assertEqual(len(w.adb.get_history(w.get_addresses())), 2)
135 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1b), {tx1.txid(), tx2.txid()})
136 with self.assertRaises(TxConflicts):
137 await self.toyserver.mempool_add_tx(tx1b)
138 self.assertEqual(self.toyserver.get_mempool_txids(), {funding_tx.txid(), tx1.txid(), tx2.txid()})
139
140 # second, wallet tries tx1c, which pays high enough fees for replacement
141 w.adb.remove_transaction(tx1b.txid())
142 tx1c = w.make_unsigned_transaction(
143 outputs=[PartialTxOutput.from_address_and_value(w_addr3, "!")], fee_policy=FixedFeePolicy(10_001))
144 w.sign_transaction(tx1c, password=None)
145 w.adb.add_transaction(tx1c)
146 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1c), {tx1.txid(), tx2.txid()})
147 await self.toyserver.mempool_add_tx(tx1c)
148 self.assertEqual(self.toyserver.get_mempool_txids(), {funding_tx.txid(), tx1c.txid()})
149
150 # mine a block
151 await self.toyserver.mine_block()
152 self.assertEqual(self.toyserver.get_mempool_txids(), set())
153 self.assertEqual(self.toyserver.cur_height, self.toyserver.block_height_from_txid(funding_tx.txid()))
154 self.assertEqual(self.toyserver.cur_height, self.toyserver.block_height_from_txid(tx1c.txid()))
155
156 # -- wallet wants to double-spend tx1c - but it is already mined!
157 w.adb.remove_transaction(tx1c.txid())
158 tx1d = w.make_unsigned_transaction(
159 outputs=[PartialTxOutput.from_address_and_value(w_addr3, "!")], fee_policy=FixedFeePolicy(25_000))
160 w.sign_transaction(tx1d, password=None)
161 w.adb.add_transaction(tx1d)
162 self.assertEqual(len(w.adb.get_history(w.get_addresses())), 2)
163 self.assertEqual(self.toyserver._get_transitive_conflict_txids(tx1d), {tx1c.txid()})
164 with self.assertRaises(TxConflictsBlockchain):
165 await self.toyserver.mempool_add_tx(tx1d)
166 self.assertEqual(self.toyserver.get_mempool_txids(), set())
167
168 async def test_sort_order_of_scripthash_get_history(self):
169 """txs touching a sh, as returned by 'blockchain.scripthash.get_history', must be in a canonical order"""
170 # create a "gateway" wallet with many UTXOs, so later it can send without chaining unconfirmed txs
171 w_gateway = restore_wallet_from_text__for_unittest(
172 "9dk", passphrase="gateway", gap_limit=10, path=None, config=self.config)['wallet'] # type: Abstract_Wallet
173 for gateway_addr in w_gateway.get_receiving_addresses():
174 tx = await self.toyserver.ask_faucet([TxOutput.from_address_and_value(gateway_addr, 2 * COIN)])
175 w_gateway.adb.add_transaction(tx)
176 await self.toyserver.mine_block()
177 coins_gateway = w_gateway.get_spendable_coins(w_gateway.get_addresses())
178 coins_gateway_ctr = -1
179
180 # create target wallet
181 w = restore_wallet_from_text__for_unittest("9dk", path=None, config=self.config)['wallet'] # type: Abstract_Wallet
182 w_addr0 = w.get_receiving_addresses()[0]
183 w_addr1 = w.get_receiving_addresses()[1]
184
185 async def send_1btc_from_gateway_to_target(addr) -> 'Transaction':
186 nonlocal coins_gateway_ctr
187 coins_gateway_ctr += 1
188 tx = w_gateway.make_unsigned_transaction(
189 coins=[coins_gateway[coins_gateway_ctr]],
190 outputs=[PartialTxOutput.from_address_and_value(addr, 1 * COIN)], fee_policy=FixedFeePolicy(5000))
191 w_gateway.sign_transaction(tx, password=None)
192 await self.toyserver.mempool_add_tx(tx)
193 return tx
194
195 # fund address multiple times in a block
196 tx1 = await send_1btc_from_gateway_to_target(w_addr0)
197 w.adb.add_transaction(tx1)
198 tx2 = await send_1btc_from_gateway_to_target(w_addr0)
199 w.adb.add_transaction(tx2)
200 tx3 = await send_1btc_from_gateway_to_target(w_addr0)
201 w.adb.add_transaction(tx3)
202
203 await self.toyserver.mine_block()
204
205 # fund address once in a new block
206 tx4 = await send_1btc_from_gateway_to_target(w_addr0)
207 w.adb.add_transaction(tx4)
208
209 await self.toyserver.mine_block()
210
211 # fund address multiple times with mempool txs
212 tx5 = await send_1btc_from_gateway_to_target(w_addr0)
213 w.adb.add_transaction(tx5)
214 tx6 = await send_1btc_from_gateway_to_target(w_addr0)
215 w.adb.add_transaction(tx6)
216 tx7 = await send_1btc_from_gateway_to_target(w_addr0)
217 w.adb.add_transaction(tx7)
218
219 # fund address twice with unconfirmed parent txs
220 coins_tx5_out = [c for c in w.get_spendable_coins(domain=[w_addr0]) if c.prevout.txid.hex() == tx5.txid()]
221 assert len(coins_tx5_out) == 1
222 tx8 = w.make_unsigned_transaction(
223 coins=coins_tx5_out,
224 outputs=[PartialTxOutput.from_address_and_value(w_addr1, 100_000)], fee_policy=FixedFeePolicy(5000))
225 w.sign_transaction(tx8, password=None)
226 w.adb.add_transaction(tx8)
227 await self.toyserver.mempool_add_tx(tx8)
228
229 coins_tx6_out = [c for c in w.get_spendable_coins(domain=[w_addr0]) if c.prevout.txid.hex() == tx6.txid()]
230 assert len(coins_tx6_out) == 1
231 tx9 = w.make_unsigned_transaction(
232 coins=coins_tx6_out,
233 outputs=[PartialTxOutput.from_address_and_value(w_addr1, 100_000)], fee_policy=FixedFeePolicy(5000))
234 w.sign_transaction(tx9, password=None)
235 w.adb.add_transaction(tx9)
236 await self.toyserver.mempool_add_tx(tx9)
237
238 self.assertEqual(len(self.toyserver.get_mempool_txids()), 5)
239 # finally, validate "blockchain.scripthash.get_history" sort order
240 sh_history = self.toyserver.calc_sh_history(bitcoin.address_to_scripthash(w_addr0))
241 self.assertEqual(len(sh_history), 9)
242 tx123_A, tx123_B, tx123_C = sorted([tx1.txid(), tx2.txid(), tx3.txid()], key=lambda x: self.toyserver.block_height_and_pos_from_txid(x))
243 tx567_A, tx567_B, tx567_C = sorted([tx5.txid(), tx6.txid(), tx7.txid()])
244 tx89_A, tx89_B = sorted([tx8.txid(), tx9.txid()])
245 self.assertEqual(sh_history, [
246 (tx123_A, self.toyserver.cur_height - 1),
247 (tx123_B, self.toyserver.cur_height - 1),
248 (tx123_C, self.toyserver.cur_height - 1),
249 (tx4.txid(), self.toyserver.cur_height),
250 (tx567_A, 0),
251 (tx567_B, 0),
252 (tx567_C, 0),
253 (tx89_A, -1),
254 (tx89_B, -1),
255 ])