Debian Codegraph @

tests/functional_tests/mining.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2018-2022, The Monero Project
4
5 #
6 # All rights reserved.
7 #
8 # Redistribution and use in source and binary forms, with or without modification, are
9 # permitted provided that the following conditions are met:
10 #
11 # 1. Redistributions of source code must retain the above copyright notice, this list of
12 # conditions and the following disclaimer.
13 #
14 # 2. Redistributions in binary form must reproduce the above copyright notice, this list
15 # of conditions and the following disclaimer in the documentation and/or other
16 # materials provided with the distribution.
17 #
18 # 3. Neither the name of the copyright holder nor the names of its contributors may be
19 # used to endorse or promote products derived from this software without specific
20 # prior written permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24 # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
25 # THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29 # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30 # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 from __future__ import print_function
33 import time
34 import os
35 import math
36 import monotonic
37 import util_resources
38 import multiprocessing
39 import string
40
41 """Test daemon mining RPC calls
42
43 Test the following RPCs:
44 - start_mining
45 - stop_mining
46 - mining_status
47
48 Control the behavior with these environment variables:
49 MINING_NO_MEASUREMENT - set to anything to use large enough and fixed mining timeouts
50 MINING_SILENT - set to anything to disable mining logging
51 """
52
53 from framework.daemon import Daemon
54 from framework.wallet import Wallet
55
56 def assert_non_null_hash(s):
57 assert len(s) == 64 # correct length
58 assert all((c in string.hexdigits for c in s)) # is parseable as hex
59 assert s != ('0' * 64) # isn't null hash
60
61 class MiningTest():
62 def run_test(self):
63 self.reset()
64 self.create()
65 self.mine(True)
66 self.mine(False)
67 self.submitblock()
68 self.reset()
69 self.test_randomx()
70
71 def reset(self):
72 print('Resetting blockchain')
73 daemon = Daemon()
74 res = daemon.get_height()
75 daemon.pop_blocks(res.height - 1)
76 daemon.flush_txpool()
77
78 def create(self):
79 print('Creating wallet')
80 wallet = Wallet()
81 # close the wallet if any, will throw if none is loaded
82 try: wallet.close_wallet()
83 except: pass
84 res = wallet.restore_deterministic_wallet(seed = 'velvet lymph giddy number token physics poetry unquoted nibs useful sabotage limits benches lifestyle eden nitrogen anvil fewest avoid batch vials washing fences goat unquoted')
85
86 def mine(self, via_daemon):
87 print("Test mining via " + ("daemon" if via_daemon else "wallet"))
88
89 cores_init = multiprocessing.cpu_count() # RX init uses all cores
90 cores_mine = 1 # Mining uses a parametric number of cores
91 is_mining_measurent = 'MINING_NO_MEASUREMENT' not in os.environ
92
93 if is_mining_measurent: # A dynamic calculation of the CPU power requested
94 time_pi_single_cpu = self.measure_cpu_power_get_time(cores_mine)
95 time_pi_all_cores = self.measure_cpu_power_get_time(cores_init)
96 # This is the last measurement, since it takes very little time and can be placed timewise-closer to the mining itself.
97 available_ram = self.get_available_ram() # So far no ideas how to use this var, other than printing it
98
99 start = monotonic.monotonic()
100 daemon = Daemon()
101 wallet = Wallet()
102
103 # check info/height/balance before generating blocks
104 res_info = daemon.get_info()
105 initial_height = res_info.height
106 res_getbalance = wallet.get_balance()
107 prev_balance = res_getbalance.balance
108
109 res_status = daemon.mining_status()
110
111 if via_daemon:
112 res = daemon.start_mining('42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm', threads_count = 1)
113 else:
114 res = wallet.start_mining(threads_count = cores_mine)
115
116 res_status = daemon.mining_status()
117 assert res_status.active == True
118 assert res_status.threads_count == cores_mine
119 assert res_status.address == '42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm'
120 assert res_status.is_background_mining_enabled == False
121 assert res_status.block_reward >= 600000000000
122
123 # wait till we mined a few of them
124 target_height = initial_height + 5
125 height = initial_height
126
127 if not is_mining_measurent:
128 timeout_init = 600
129 timeout_mine = 300
130 else:
131 """
132 Randomx init has high variance on CI machines due to noisy neighbors,
133 taking up resources in parallel (including by our own jobs).
134
135 Mining is organized in the following scheme:
136 1) first loop's pass: RandomX init and mining
137 2) every next pass: only mining
138 Pass 1) takes much more time than pass 2)
139 Pass 1) uses all cores, pass 2) just one (currently)
140 For the above reasons both passes need separate timeouts and adjustments.
141 After the first pass, the timeout is being reset to a lower value.
142 """
143
144 def calc_timeout(seconds_constant, time_pi, cores):
145 """
146 The time it took to calculate pi under certain conditions
147 is proportional to the time it will take to calculate the real job.
148
149 The number of cores used decreases the time almost linearly.
150 """
151 timeout = float(seconds_constant) * time_pi / float(cores)
152 return timeout
153
154 timeout_base_init = 60 # RX init needs more time
155 timeout_base_mine = 20
156 timeout_init = calc_timeout(timeout_base_init, time_pi_all_cores, cores_init)
157 timeout_mine = calc_timeout(timeout_base_mine, time_pi_single_cpu, cores_mine)
158
159 msg_timeout_src = "adjusted for the currently available CPU power" if is_mining_measurent else "selected to have the default value"
160 msg = "Timeout for {} {}, is {:.1f} s"
161 self.print_mining_info(msg.format("init, ", msg_timeout_src, timeout_init))
162 self.print_mining_info(msg.format("mining,", msg_timeout_src, timeout_mine))
163 timeout = timeout_init
164 rx_inited = False # Gets initialized in the first pass of the below loop
165 while height < target_height:
166 seen_height = height
167 for _ in range(int(math.ceil(timeout))):
168 time.sleep(1)
169 seconds_passed = monotonic.monotonic() - start
170 height = daemon.get_info().height
171 if height > seen_height:
172 break
173 else:
174 assert False, 'Failed to mine successor to block %d (initial block = %d) after %d s. RX initialized = %r' % (seen_height, initial_height, round(seconds_passed), rx_inited)
175 if not rx_inited:
176 rx_inited = True
177 timeout = timeout_mine # Resetting the timeout after first mined block and RX init
178 self.print_time_taken(start, "RX init + mining 1st block")
179 else:
180 self.print_time_taken(start, "mining iteration")
181
182 self.print_time_taken(start, "mining total")
183
184 if via_daemon:
185 res = daemon.stop_mining()
186 else:
187 res = wallet.stop_mining()
188
189 res_status = daemon.mining_status()
190 assert res_status.active == False
191
192 res_info = daemon.get_info()
193 new_height = res_info.height
194
195 wallet.refresh()
196 res_getbalance = wallet.get_balance()
197 balance = res_getbalance.balance
198 assert balance >= prev_balance + (new_height - initial_height) * 600000000000
199
200 if via_daemon:
201 res = daemon.start_mining('42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm', threads_count = 1, do_background_mining = True)
202 else:
203 res = wallet.start_mining(threads_count = 1, do_background_mining = True)
204 res_status = daemon.mining_status()
205 assert res_status.active == True
206 assert res_status.threads_count == 1
207 assert res_status.address == '42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm'
208 assert res_status.is_background_mining_enabled == True
209 assert res_status.block_reward >= 600000000000
210
211 # don't wait, might be a while if the machine is busy, which it probably is
212 if via_daemon:
213 res = daemon.stop_mining()
214 else:
215 res = wallet.stop_mining()
216 res_status = daemon.mining_status()
217 assert res_status.active == False
218
219 def measure_cpu_power_get_time(self, cores):
220 self.print_mining_info("Measuring the currently available CPU power...")
221 build_dir_funcional_tests = os.environ['FUNCTIONAL_TESTS_DIRECTORY']
222 time_pi = util_resources.get_time_pi_seconds(cores, build_dir_funcional_tests)
223 self.print_mining_info("Time taken to calculate Pi on {} core(s) was {:.2f} s.".format(cores, time_pi))
224 return time_pi
225
226 def get_available_ram(self):
227 available_ram = util_resources.available_ram_gb()
228 threshold_ram = 3
229 self.print_mining_info("Available RAM = " + str(round(available_ram, 1)) + " GB")
230 if available_ram < threshold_ram:
231 print("Warning! Available RAM =", round(available_ram, 1),
232 "GB is less than the reasonable threshold =", threshold_ram,
233 ". The RX init might exceed the calculated timeout.")
234 return available_ram
235
236 def submitblock(self):
237 print("Test submitblock")
238
239 daemon = Daemon()
240 res = daemon.get_height()
241 height = res.height
242 res = daemon.generateblocks('42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm', 5)
243 assert len(res.blocks) == 5
244 hashes = res.blocks
245 blocks = []
246 for block_hash in hashes:
247 res = daemon.getblock(hash = block_hash)
248 assert len(res.blob) > 0 and len(res.blob) % 2 == 0
249 blocks.append(res.blob)
250 res = daemon.get_height()
251 assert res.height == height + 5
252 res = daemon.pop_blocks(5)
253 res = daemon.get_height()
254 assert res.height == height
255 for i in range(len(hashes)):
256 block_hash = hashes[i]
257 assert len(block_hash) == 64
258 res = daemon.submitblock(blocks[i])
259 submitted_block_id = res.block_id
260 assert_non_null_hash(submitted_block_id)
261 res = daemon.get_height()
262 assert res.height == height + i + 1
263 assert res.hash == block_hash
264
265 def is_mining_silent(self):
266 return 'MINING_SILENT' in os.environ
267
268 def print_mining_info(self, msg):
269 if self.is_mining_silent():
270 return
271 print(msg)
272
273 def print_time_taken(self, start, msg_context):
274 if self.is_mining_silent():
275 return
276 seconds_passed = monotonic.monotonic() - start
277 print("Time taken for", msg_context, "=", round(seconds_passed, 1), "s.")
278
279 def test_randomx(self):
280 print("Test RandomX")
281
282 daemon = Daemon()
283 wallet = Wallet()
284
285 res = daemon.get_height()
286 daemon.pop_blocks(res.height - 1)
287 daemon.flush_txpool()
288
289 epoch = int(os.environ['SEEDHASH_EPOCH_BLOCKS'])
290 lag = int(os.environ['SEEDHASH_EPOCH_LAG'])
291 address = '42ey1afDFnn4886T7196doS9GPMzexD9gXpsZJDwVjeRVdFCSoHnv7KPbBeGpzJBzHRCAs9UxqeoyFQMYbqSWYTfJJQAWDm'
292
293 # check we can generate blocks, and that the seed hash changes when expected
294 res = daemon.getblocktemplate(address)
295 first_seed_hash = res.seed_hash
296 daemon.generateblocks(address, 1 + lag)
297 res = daemon.mining_status()
298 assert res.active == False
299 assert res.pow_algorithm == 'RandomX'
300 res = daemon.getblocktemplate(address)
301 seed_hash = res.seed_hash
302 t0 = time.time()
303 daemon.generateblocks(address, epoch - 3)
304 t0 = time.time() - t0
305 res = daemon.get_info()
306 assert res.height == lag + epoch - 1
307 res = daemon.getblocktemplate(address)
308 assert seed_hash == res.seed_hash
309 t0 = time.time()
310 daemon.generateblocks(address, 1)
311 t0 = time.time() - t0
312 res = daemon.get_info()
313 assert res.height == lag + epoch
314 daemon.generateblocks(address, 1)
315 res = daemon.getblocktemplate(address)
316 assert seed_hash != res.seed_hash
317 new_seed_hash = res.seed_hash
318 t0 = time.time()
319 daemon.generateblocks(address, epoch - 1)
320 t0 = time.time() - t0
321 res = daemon.getblocktemplate(address)
322 assert new_seed_hash == res.seed_hash
323 daemon.generateblocks(address, 1)
324 res = daemon.getblocktemplate(address)
325 assert new_seed_hash != res.seed_hash
326 new_seed_hash = res.seed_hash
327 t0 = time.time()
328 daemon.generateblocks(address, epoch - 1)
329 t0 = time.time() - t0
330 res = daemon.getblocktemplate(address)
331 assert new_seed_hash == res.seed_hash
332 daemon.generateblocks(address, 1)
333 res = daemon.getblocktemplate(address)
334 assert new_seed_hash != res.seed_hash
335 #print('First mining: ' + str(t0))
336
337 # pop all these blocks, and feed them again to monerod
338 print('Recreating the chain')
339 res = daemon.get_info()
340 height = res.height
341 assert height == lag + epoch * 3 + 1
342 block_hashes = [x.hash for x in daemon.getblockheadersrange(0, height - 1).headers]
343 assert len(block_hashes) == height
344 blocks = []
345 for i in range(len(block_hashes)):
346 res = daemon.getblock(height = i)
347 assert res.block_header.hash == block_hashes[i]
348 blocks.append(res.blob)
349 daemon.pop_blocks(height)
350 res = daemon.get_info()
351 assert res.height == 1
352 res = daemon.getblocktemplate(address)
353 assert first_seed_hash == res.seed_hash
354 t0 = time.time()
355 for h in range(len(block_hashes)):
356 res = daemon.submitblock(blocks[h])
357 submitted_block_id = res.block_id
358 assert_non_null_hash(submitted_block_id)
359 t0 = time.time() - t0
360 res = daemon.get_info()
361 assert height == res.height
362 res = daemon.getblocktemplate(address)
363 assert new_seed_hash != res.seed_hash
364 res = daemon.pop_blocks(1)
365 res = daemon.getblocktemplate(address)
366 assert new_seed_hash == res.seed_hash
367 #print('Submit: ' + str(t0))
368
369 # start mining from the genesis block again
370 print('Mining from genesis block again')
371 res = daemon.get_height()
372 top_hash = res.hash
373 res = daemon.getblockheaderbyheight(0)
374 genesis_block_hash = res.block_header.hash
375 t0 = time.time()
376 daemon.generateblocks(address, height - 2, prev_block = genesis_block_hash)
377 t0 = time.time() - t0
378 res = daemon.get_info()
379 assert res.height == height - 1
380 assert res.top_block_hash == top_hash
381 #print('Second mining: ' + str(t0))
382
383 # that one will cause a huge reorg
384 print('Adding one to reorg')
385 res = daemon.generateblocks(address, 1)
386 assert len(res.blocks) == 1
387 new_top_hash = res.blocks[0]
388 res = daemon.get_info()
389 assert res.height == height
390 assert res.top_block_hash == new_top_hash
391
392
393 class Guard:
394 def __enter__(self):
395 pass
396
397 def __exit__(self, exc_type, exc_value, traceback):
398 daemon = Daemon()
399 try: daemon.stop_mining()
400 except: pass
401
402 if __name__ == '__main__':
403 with Guard() as guard:
404 MiningTest().run_test()