Debian Codegraph @

tests/test_network.py

raw symbols SCIP
1 import asyncio
2 import tempfile
3 import unittest
4 from typing import List
5
6 from electrum import constants
7 from electrum.simple_config import SimpleConfig
8 from electrum import blockchain
9 from electrum.interface import Interface, ServerAddr, ChainResolutionMode
10 from electrum.crypto import sha256
11 from electrum.util import OldTaskGroup
12 from electrum import util
13
14 from . import ElectrumTestCase
15
16
17 CRM = ChainResolutionMode
18
19
20 class MockBlockchain:
21
22 def __init__(self, headers: List[str]):
23 self._headers = headers
24 self.forkpoint = len(headers)
25
26 def height(self) -> int:
27 return len(self._headers) - 1
28
29 def save_header(self, header: dict) -> None:
30 assert header['block_height'] == self.height()+1, f"new {header['block_height']=}, cur {self.height()=}"
31 self._headers.append(header['mock']['id'])
32
33 def check_header(self, header: dict) -> bool:
34 return header['mock']['id'] in self._headers
35
36 def can_connect(self, header: dict, *, check_height: bool = True) -> bool:
37 height = header['block_height']
38 if check_height and self.height() != height - 1:
39 return False
40 if self.check_header(header):
41 return True
42 return header['mock']['prev_id'] in self._headers
43
44 def fork(parent, header: dict) -> 'MockBlockchain':
45 if not parent.can_connect(header, check_height=False):
46 raise Exception("forking header does not connect to parent chain")
47 forkpoint = header.get('block_height')
48 self = MockBlockchain(parent._headers[:forkpoint])
49 self.save_header(header)
50 chain_id = header['mock']['id']
51 with blockchain.blockchains_lock:
52 blockchain.blockchains[chain_id] = self
53 return self
54
55
56 class MockNetwork:
57
58 def __init__(self, config: SimpleConfig):
59 self.config = config
60 self.asyncio_loop = util.get_asyncio_loop()
61 self.taskgroup = OldTaskGroup()
62 self.proxy = None
63
64 class MockInterface(Interface):
65 def __init__(self, config: SimpleConfig):
66 self.config = config
67 network = MockNetwork(config)
68 super().__init__(network=network, server=ServerAddr.from_str('mock-server:50000:t'))
69 self.q = asyncio.Queue()
70
71 async def get_block_header(self, height: int, *, mode: ChainResolutionMode) -> dict:
72 assert self.q.qsize() > 0, (height, mode)
73 item = await self.q.get()
74 self.logger.debug(f"step with {height=}. {mode=}. will get {item=}")
75 assert item['block_height'] == height, (item['block_height'], height)
76 assert mode in item['mock'], (mode, item)
77 return item
78
79 async def run(self):
80 return
81
82 async def _maybe_warm_headers_cache(self, *args, **kwargs):
83 return
84
85
86 class TestHeaderChainResolution(ElectrumTestCase):
87
88 @classmethod
89 def setUpClass(cls):
90 super().setUpClass()
91 constants.BitcoinRegtest.set_as_network()
92
93 @classmethod
94 def tearDownClass(cls):
95 super().tearDownClass()
96 constants.BitcoinMainnet.set_as_network()
97
98 def tearDown(self):
99 blockchain.blockchains = {}
100 super().tearDown()
101
102 async def asyncSetUp(self):
103 await super().asyncSetUp()
104 self.config = SimpleConfig({'electrum_path': self.electrum_path})
105 self.interface = MockInterface(self.config)
106
107 async def test_catchup_one_block_behind(self):
108 """Single chain, but client is behind. The client's height is 5, server is on block 6.
109 - first missing block found during *catchup* phase
110 """
111 ifa = self.interface
112 ifa.tip = 6
113 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a"])
114 blockchain.blockchains = {
115 "00a": ifa.blockchain,
116 }
117 ifa.q.put_nowait({'block_height': 6, 'mock': {CRM.CATCHUP:1, 'id': '06a', 'prev_id': '05a'}})
118 res = await ifa.sync_until(ifa.tip)
119 self.assertEqual((CRM.CATCHUP, 7), res)
120 self.assertEqual(ifa.q.qsize(), 0)
121 self.assertEqual(len(blockchain.blockchains), 1)
122
123 async def test_catchup_already_up_to_date(self):
124 """Single chain, local chain tip already matches server tip."""
125 ifa = self.interface
126 ifa.tip = 5
127 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a"])
128 blockchain.blockchains = {
129 "00a": ifa.blockchain,
130 }
131 ifa.q.put_nowait({'block_height': 5, 'mock': {CRM.CATCHUP:1, 'id': '05a', 'prev_id': '04a'}})
132 res = await ifa.sync_until(ifa.tip)
133 self.assertEqual((CRM.CATCHUP, 6), res)
134 self.assertEqual(ifa.q.qsize(), 0)
135 self.assertEqual(len(blockchain.blockchains), 1)
136
137 async def test_catchup_client_ahead_of_lagging_server(self):
138 """Single chain, server is lagging."""
139 ifa = self.interface
140 ifa.tip = 3
141 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a"])
142 blockchain.blockchains = {
143 "00a": ifa.blockchain,
144 }
145 ifa.q.put_nowait({'block_height': 3, 'mock': {CRM.CATCHUP:1, 'id': '03a', 'prev_id': '02a'}})
146 res = await ifa.sync_until(ifa.tip)
147 self.assertEqual((CRM.CATCHUP, 4), res)
148 self.assertEqual(ifa.q.qsize(), 0)
149 self.assertEqual(len(blockchain.blockchains), 1)
150
151 async def test_catchup_fast_forward(self):
152 """Single chain, but client is behind. The client's height is 5, server is already on block 12.
153 - first missing block found during *backward* phase
154 """
155 ifa = self.interface
156 ifa.tip = 12
157 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a"])
158 blockchain.blockchains = {
159 "00a": ifa.blockchain,
160 }
161 ifa.q.put_nowait({'block_height': 12, 'mock': {CRM.CATCHUP:1, 'id': '12a', 'prev_id': '11a'}})
162 ifa.q.put_nowait({'block_height': 6, 'mock': {CRM.BACKWARD:1, 'id': '06a', 'prev_id': '05a'}})
163 ifa.q.put_nowait({'block_height': 7, 'mock': {CRM.CATCHUP: 1, 'id': '07a', 'prev_id': '06a'}})
164 ifa.q.put_nowait({'block_height': 8, 'mock': {CRM.CATCHUP: 1, 'id': '08a', 'prev_id': '07a'}})
165 ifa.q.put_nowait({'block_height': 9, 'mock': {CRM.CATCHUP: 1, 'id': '09a', 'prev_id': '08a'}})
166 res = await ifa.sync_until(ifa.tip, next_height=9)
167 self.assertEqual((CRM.CATCHUP, 10), res)
168 self.assertEqual(ifa.q.qsize(), 0)
169 self.assertEqual(len(blockchain.blockchains), 1)
170
171 async def test_fork(self):
172 """client starts on main chain, has no knowledge of any fork.
173 server is on other side of chain split, the last common block is height 6.
174 - first missing block found during *binary* phase
175 - is *new* fork
176 """
177 ifa = self.interface
178 ifa.tip = 8
179 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a", "06a", "07a", "08a", "09a", "10a", "11a", "12a"])
180 blockchain.blockchains = {
181 "00a": ifa.blockchain,
182 }
183 ifa.q.put_nowait({'block_height': 8, 'mock': {CRM.CATCHUP:1, 'id': '08b', 'prev_id': '07b'}})
184 ifa.q.put_nowait({'block_height': 7, 'mock': {CRM.BACKWARD:1, 'id': '07b', 'prev_id': '06a'}})
185 ifa.q.put_nowait({'block_height': 5, 'mock': {CRM.BACKWARD:1, 'id': '05a', 'prev_id': '04a'}})
186 ifa.q.put_nowait({'block_height': 6, 'mock': {CRM.BINARY:1, 'id': '06a', 'prev_id': '05a'}})
187 res = await ifa.sync_until(ifa.tip, next_height=7)
188 self.assertEqual((CRM.FORK, 8), res)
189 self.assertEqual(ifa.q.qsize(), 0)
190 self.assertEqual(len(blockchain.blockchains), 2)
191
192 async def test_can_connect_during_backward(self):
193 """client starts on main chain. client already knows about another fork, which has local height 4.
194 server is on that fork but has more blocks.
195 - first missing block found during *backward* phase
196 - is *existing* fork
197 """
198 ifa = self.interface
199 ifa.tip = 8
200 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a", "06a", "07a", "08a", "09a", "10a", "11a", "12a"])
201 blockchain.blockchains = {
202 "00a": ifa.blockchain,
203 "03b": MockBlockchain(["00a", "01a", "02a", "03b", "04b"]),
204 }
205 ifa.q.put_nowait({'block_height': 8, 'mock': {CRM.CATCHUP:1, 'id': '08b', 'prev_id': '07b'}})
206 ifa.q.put_nowait({'block_height': 7, 'mock': {CRM.BACKWARD:1, 'id': '07b', 'prev_id': '06b'}})
207 ifa.q.put_nowait({'block_height': 5, 'mock': {CRM.BACKWARD:1, 'id': '05b', 'prev_id': '04b'}})
208 ifa.q.put_nowait({'block_height': 6, 'mock': {CRM.CATCHUP:1, 'id': '06b', 'prev_id': '05b'}})
209 res = await ifa.sync_until(ifa.tip, next_height=6)
210 self.assertEqual((CRM.CATCHUP, 7), res)
211 self.assertEqual(ifa.q.qsize(), 0)
212 self.assertEqual(len(blockchain.blockchains), 2)
213
214 async def test_chain_false_during_binary(self):
215 """client starts on main chain, has no knowledge of any fork.
216 server is on other side of chain split, the last common block is height 3.
217 - first missing block found during *binary* phase
218 - is *new* fork
219 """
220 ifa = self.interface
221 ifa.tip = 8
222 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a", "06a", "07a", "08a", "09a", "10a", "11a", "12a"])
223 blockchain.blockchains = {
224 "00a": ifa.blockchain,
225 }
226 ifa.q.put_nowait({'block_height': 8, 'mock': {CRM.CATCHUP:1, 'id': '08b', 'prev_id': '07b'}})
227 ifa.q.put_nowait({'block_height': 7, 'mock': {CRM.BACKWARD:1, 'id': '07b', 'prev_id': '06b'}})
228 ifa.q.put_nowait({'block_height': 5, 'mock': {CRM.BACKWARD:1, 'id': '05b', 'prev_id': '04b'}})
229 ifa.q.put_nowait({'block_height': 1, 'mock': {CRM.BACKWARD:1, 'id': '01a', 'prev_id': '00a'}})
230 ifa.q.put_nowait({'block_height': 3, 'mock': {CRM.BINARY:1, 'id': '03a', 'prev_id': '02a'}})
231 ifa.q.put_nowait({'block_height': 4, 'mock': {CRM.BINARY:1, 'id': '04b', 'prev_id': '03a'}})
232 ifa.q.put_nowait({'block_height': 5, 'mock': {CRM.CATCHUP:1, 'id': '05b', 'prev_id': '04b'}})
233 ifa.q.put_nowait({'block_height': 6, 'mock': {CRM.CATCHUP:1, 'id': '06b', 'prev_id': '05b'}})
234 res = await ifa.sync_until(ifa.tip, next_height=6)
235 self.assertEqual((CRM.CATCHUP, 7), res)
236 self.assertEqual(ifa.q.qsize(), 0)
237 self.assertEqual(len(blockchain.blockchains), 2)
238
239 async def test_chain_true_during_binary(self):
240 """client starts on main chain. client already knows about another fork, which has local height 10.
241 server is on that fork but has more blocks.
242 - first missing block found during *binary* phase
243 - is *existing* fork
244 """
245 ifa = self.interface
246 ifa.tip = 20
247 ifa.blockchain = MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a", "06a", "07a", "08a", "09a", "10a", "11a", "12a", "13a", "14a"])
248 blockchain.blockchains = {
249 "00a": ifa.blockchain,
250 "07b": MockBlockchain(["00a", "01a", "02a", "03a", "04a", "05a", "06a", "07b", "08b", "09b", "10b"]),
251 }
252 ifa.q.put_nowait({'block_height': 20, 'mock': {CRM.CATCHUP:1, 'id': '20b', 'prev_id': '19b'}})
253 ifa.q.put_nowait({'block_height': 15, 'mock': {CRM.BACKWARD:1, 'id': '15b', 'prev_id': '14b'}})
254 ifa.q.put_nowait({'block_height': 13, 'mock': {CRM.BACKWARD:1, 'id': '13b', 'prev_id': '12b'}})
255 ifa.q.put_nowait({'block_height': 9, 'mock': {CRM.BACKWARD:1, 'id': '09b', 'prev_id': '08b'}})
256 ifa.q.put_nowait({'block_height': 11, 'mock': {CRM.BINARY:1, 'id': '11b', 'prev_id': '10b'}})
257 ifa.q.put_nowait({'block_height': 10, 'mock': {CRM.BINARY:1, 'id': '10b', 'prev_id': '09b'}})
258 ifa.q.put_nowait({'block_height': 11, 'mock': {CRM.CATCHUP:1, 'id': '11b', 'prev_id': '10b'}})
259 ifa.q.put_nowait({'block_height': 12, 'mock': {CRM.CATCHUP:1, 'id': '12b', 'prev_id': '11b'}})
260 ifa.q.put_nowait({'block_height': 13, 'mock': {CRM.CATCHUP:1, 'id': '13b', 'prev_id': '12b'}})
261 res = await ifa.sync_until(ifa.tip, next_height=13)
262 self.assertEqual((CRM.CATCHUP, 14), res)
263 self.assertEqual(ifa.q.qsize(), 0)
264 self.assertEqual(len(blockchain.blockchains), 2)
265
266
267 if __name__ == "__main__":
268 constants.BitcoinRegtest.set_as_network()
269 unittest.main()