2
2
# Copyright (c) 2017 The Bitcoin Core developers
3
3
# Distributed under the MIT software license, see the accompanying
4
4
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
- """Test recovery from a crash during chainstate writing."""
6
-
7
- from test_framework .test_framework import BitcoinTestFramework
8
- from test_framework .util import *
9
- from test_framework .script import *
10
- from test_framework .mininode import *
11
- import random
12
- try :
13
- import http .client as httplib
14
- except ImportError :
15
- import httplib
16
- import errno
17
-
18
- '''
19
- Test structure:
5
+ """Test recovery from a crash during chainstate writing.
20
6
21
7
- 4 nodes
22
8
* node0, node1, and node2 will have different dbcrash ratios, and different
37
23
* submit block to node
38
24
* if node crashed on/after submitting:
39
25
- restart until recovery succeeds
40
- - check that utxo matches node3 using gettxoutsetinfo
41
- '''
26
+ - check that utxo matches node3 using gettxoutsetinfo"""
42
27
43
- class ChainstateWriteCrashTest (BitcoinTestFramework ):
28
+ import errno
29
+ import http .client
30
+ import random
31
+ import sys
32
+ import time
33
+
34
+ from test_framework .mininode import *
35
+ from test_framework .script import *
36
+ from test_framework .test_framework import BitcoinTestFramework
37
+ from test_framework .util import *
38
+
39
+ HTTP_DISCONNECT_ERRORS = [http .client .CannotSendRequest ]
40
+ try :
41
+ HTTP_DISCONNECT_ERRORS .append (http .client .RemoteDisconnected )
42
+ except AttributeError :
43
+ pass
44
44
45
+ class ChainstateWriteCrashTest (BitcoinTestFramework ):
45
46
def __init__ (self ):
46
47
super ().__init__ ()
47
48
self .num_nodes = 4
@@ -50,32 +51,28 @@ def __init__(self):
50
51
# Set -maxmempool=0 to turn off mempool memory sharing with dbcache
51
52
# Set -rpcservertimeout=900 to reduce socket disconnects in this
52
53
# long-running test
53
- self .base_args = ["-limitdescendantsize=0" , "-maxmempool=0" , "-rpcservertimeout=900" ]
54
+ self .base_args = ["-limitdescendantsize=0" , "-maxmempool=0" , "-rpcservertimeout=900" , "-dbbatchsize=200000" ]
54
55
55
56
# Set different crash ratios and cache sizes. Note that not all of
56
57
# -dbcache goes to pcoinsTip.
57
- self .node0_args = ["-dbcrashratio=8" , "-dbcache=4" , "-dbbatchsize=200000" ] + self .base_args
58
- self .node1_args = ["-dbcrashratio=16" , "-dbcache=8" , "-dbbatchsize=200000" ] + self .base_args
59
- self .node2_args = ["-dbcrashratio=24" , "-dbcache=16" , "-dbbatchsize=200000" ] + self .base_args
58
+ self .node0_args = ["-dbcrashratio=8" , "-dbcache=4" ] + self .base_args
59
+ self .node1_args = ["-dbcrashratio=16" , "-dbcache=8" ] + self .base_args
60
+ self .node2_args = ["-dbcrashratio=24" , "-dbcache=16" ] + self .base_args
60
61
61
62
# Node3 is a normal node with default args, except will mine full blocks
62
63
self .node3_args = ["-blockmaxweight=4000000" ]
63
64
self .extra_args = [self .node0_args , self .node1_args , self .node2_args , self .node3_args ]
64
65
65
- # We'll track some test coverage statistics
66
- self .restart_counts = [0 , 0 , 0 ] # Track the restarts for nodes 0-2
67
- self .crashed_on_restart = 0 # Track count of crashes during recovery
68
-
69
66
def setup_network (self ):
70
67
self .setup_nodes ()
71
68
# Leave them unconnected, we'll use submitblock directly in this test
72
69
73
- # Starts up a given node id, waits for the tip to reach the given block
74
- # hash, and calculates the utxo hash. Exceptions on startup should
75
- # indicate node crash (due to -dbcrashratio), in which case we try again.
76
- # Give up after 60 seconds.
77
- # Returns the utxo hash of the given node.
78
70
def restart_node (self , node_index , expected_tip ):
71
+ """Start up a given node id, wait for the tip to reach the given block hash, and calculate the utxo hash.
72
+
73
+ Exceptions on startup should indicate node crash (due to -dbcrashratio), in which case we try again. Give up
74
+ after 60 seconds. Returns the utxo hash of the given node."""
75
+
79
76
time_start = time .time ()
80
77
while time .time () - time_start < 60 :
81
78
try :
@@ -99,14 +96,23 @@ def restart_node(self, node_index, expected_tip):
99
96
# and make sure that recovery happens.
100
97
raise AssertionError ("Unable to successfully restart node %d in allotted time" , node_index )
101
98
102
- # Try submitting a block to the given node.
103
- # Catch any exceptions that indicate the node has crashed.
104
- # Returns true if the block was submitted successfully; false otherwise.
105
99
def submit_block_catch_error (self , node_index , block ):
100
+ """Try submitting a block to the given node.
101
+
102
+ Catch any exceptions that indicate the node has crashed.
103
+ Returns true if the block was submitted successfully; false otherwise."""
104
+
106
105
try :
107
106
self .nodes [node_index ].submitblock (block )
108
107
return True
109
- except (httplib .CannotSendRequest , httplib .RemoteDisconnected ) as e :
108
+ except http .client .BadStatusLine as e :
109
+ # Prior to 3.5 BadStatusLine('') was raised for a remote disconnect error.
110
+ if sys .version_info [0 ] == 3 and sys .version_info [1 ] < 5 and e .line == "''" :
111
+ self .log .debug ("node %d submitblock raised exception: %s" , node_index , e )
112
+ return False
113
+ else :
114
+ raise
115
+ except tuple (HTTP_DISCONNECT_ERRORS ) as e :
110
116
self .log .debug ("node %d submitblock raised exception: %s" , node_index , e )
111
117
return False
112
118
except OSError as e :
@@ -118,11 +124,13 @@ def submit_block_catch_error(self, node_index, block):
118
124
# Unexpected exception, raise
119
125
raise
120
126
121
- # Use submitblock to sync node3's chain with the other nodes
122
- # If submitblock fails, restart the node and get the new utxo hash.
123
127
def sync_node3blocks (self , block_hashes ):
124
- # If any nodes crash while updating, we'll compare utxo hashes to
125
- # ensure recovery was successful.
128
+ """Use submitblock to sync node3's chain with the other nodes
129
+
130
+ If submitblock fails, restart the node and get the new utxo hash.
131
+ If any nodes crash while updating, we'll compare utxo hashes to
132
+ ensure recovery was successful."""
133
+
126
134
node3_utxo_hash = self .nodes [3 ].gettxoutsetinfo ()['hash_serialized_2' ]
127
135
128
136
# Retrieve all the blocks from node3
@@ -161,9 +169,10 @@ def sync_node3blocks(self, block_hashes):
161
169
self .log .debug ("Checking txoutsetinfo matches for node %d" , i )
162
170
assert_equal (nodei_utxo_hash , node3_utxo_hash )
163
171
164
- # Verify that the utxo hash of each node matches node3.
165
- # Restart any nodes that crash while querying.
166
172
def verify_utxo_hash (self ):
173
+ """Verify that the utxo hash of each node matches node3.
174
+
175
+ Restart any nodes that crash while querying."""
167
176
node3_utxo_hash = self .nodes [3 ].gettxoutsetinfo ()['hash_serialized_2' ]
168
177
self .log .info ("Verifying utxo hash matches for all nodes" )
169
178
@@ -175,9 +184,8 @@ def verify_utxo_hash(self):
175
184
nodei_utxo_hash = self .restart_node (i , self .nodes [3 ].getbestblockhash ())
176
185
assert_equal (nodei_utxo_hash , node3_utxo_hash )
177
186
178
-
179
187
def generate_small_transactions (self , node , count , utxo_list ):
180
- FEE = 1000 # TODO: replace this with node relay fee based calculation
188
+ FEE = 1000 # TODO: replace this with node relay fee based calculation
181
189
num_transactions = 0
182
190
random .shuffle (utxo_list )
183
191
while len (utxo_list ) >= 2 and num_transactions < count :
@@ -186,8 +194,8 @@ def generate_small_transactions(self, node, count, utxo_list):
186
194
for i in range (2 ):
187
195
utxo = utxo_list .pop ()
188
196
tx .vin .append (CTxIn (COutPoint (int (utxo ['txid' ], 16 ), utxo ['vout' ])))
189
- input_amount += int (utxo ['amount' ]* COIN )
190
- output_amount = (input_amount - FEE )// 3
197
+ input_amount += int (utxo ['amount' ] * COIN )
198
+ output_amount = (input_amount - FEE ) // 3
191
199
192
200
if output_amount <= 0 :
193
201
# Sanity check -- if we chose inputs that are too small, skip
@@ -202,6 +210,9 @@ def generate_small_transactions(self, node, count, utxo_list):
202
210
num_transactions += 1
203
211
204
212
def run_test (self ):
213
+ # Track test coverage statistics
214
+ self .restart_counts = [0 , 0 , 0 ] # Track the restarts for nodes 0-2
215
+ self .crashed_on_restart = 0 # Track count of crashes during recovery
205
216
206
217
# Start by creating a lot of utxos on node3
207
218
initial_height = self .nodes [3 ].getblockcount ()
@@ -210,7 +221,7 @@ def run_test(self):
210
221
211
222
# Sync these blocks with the other nodes
212
223
block_hashes_to_sync = []
213
- for height in range (initial_height + 1 , self .nodes [3 ].getblockcount ()+ 1 ):
224
+ for height in range (initial_height + 1 , self .nodes [3 ].getblockcount () + 1 ):
214
225
block_hashes_to_sync .append (self .nodes [3 ].getblockhash (height ))
215
226
216
227
self .log .debug ("Syncing %d blocks with other nodes" , len (block_hashes_to_sync ))
@@ -233,13 +244,15 @@ def run_test(self):
233
244
if random_height > starting_tip_height :
234
245
# Randomly reorg from this point with some probability (1/4 for
235
246
# tip, 1/5 for tip-1, ...)
236
- if random .random () < 1.0 / (current_height + 4 - random_height ):
247
+ if random .random () < 1.0 / (current_height + 4 - random_height ):
237
248
self .log .debug ("Invalidating block at height %d" , random_height )
238
249
self .nodes [3 ].invalidateblock (self .nodes [3 ].getblockhash (random_height ))
239
250
240
251
# Now generate new blocks until we pass the old tip height
241
252
self .log .debug ("Mining longer tip" )
242
- block_hashes = self .nodes [3 ].generate (current_height + 1 - self .nodes [3 ].getblockcount ())
253
+ block_hashes = []
254
+ while current_height + 1 > self .nodes [3 ].getblockcount ():
255
+ block_hashes .extend (self .nodes [3 ].generate (min (10 , current_height + 1 - self .nodes [3 ].getblockcount ())))
243
256
self .log .debug ("Syncing %d new blocks..." , len (block_hashes ))
244
257
self .sync_node3blocks (block_hashes )
245
258
utxo_list = self .nodes [3 ].listunspent ()
0 commit comments