Dash Core  0.12.2.1
P2P Digital Currency
maxuploadtarget.py
Go to the documentation of this file.
1 #!/usr/bin/env python2
2 #
3 # Distributed under the MIT/X11 software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #
6 
7 from test_framework.mininode import *
8 from test_framework.test_framework import BitcoinTestFramework
9 from test_framework.util import *
10 import time
11 
12 '''
13 Test behavior of -maxuploadtarget.
14 
15 * Verify that getdata requests for old blocks (>1week) are dropped
16 if uploadtarget has been reached.
17 * Verify that getdata requests for recent blocks are respecteved even
18 if uploadtarget has been reached.
19 * Verify that the upload counters are reset after 24 hours.
20 '''
21 
22 # TestNode: bare-bones "peer". Used mostly as a conduit for a test to sending
23 # p2p messages to a node, generating the messages in the main testing logic.
25  def __init__(self):
26  NodeConnCB.__init__(self)
27  self.connection = None
28  self.ping_counter = 1
31 
32  def add_connection(self, conn):
33  self.connection = conn
34  self.peer_disconnected = False
35 
36  def on_inv(self, conn, message):
37  pass
38 
39  # Track the last getdata message we receive (used in the test)
40  def on_getdata(self, conn, message):
41  self.last_getdata = message
42 
43  def on_block(self, conn, message):
44  message.block.calc_sha256()
45  try:
46  self.block_receive_map[message.block.sha256] += 1
47  except KeyError as e:
48  self.block_receive_map[message.block.sha256] = 1
49 
50  # Spin until verack message is received from the node.
51  # We use this to signal that our test can begin. This
52  # is called from the testing thread, so it needs to acquire
53  # the global lock.
54  def wait_for_verack(self):
55  def veracked():
56  return self.verack_received
57  return wait_until(veracked, timeout=10)
58 
60  def disconnected():
61  return self.peer_disconnected
62  return wait_until(disconnected, timeout=10)
63 
64  # Wrapper for the NodeConn's send_message function
65  def send_message(self, message):
66  self.connection.send_message(message)
67 
68  def on_pong(self, conn, message):
69  self.last_pong = message
70 
71  def on_close(self, conn):
72  self.peer_disconnected = True
73 
74  # Sync up with the node after delivery of a block
75  def sync_with_ping(self, timeout=30):
76  def received_pong():
77  return (self.last_pong.nonce == self.ping_counter)
79  success = wait_until(received_pong, timeout)
80  self.ping_counter += 1
81  return success
82 
84  def __init__(self):
85  self.utxo = []
87 
88  def add_options(self, parser):
89  parser.add_option("--testbinary", dest="testbinary",
90  default=os.getenv("DASHD", "dashd"),
91  help="dashd binary to test")
92 
93  def setup_chain(self):
94  initialize_chain_clean(self.options.tmpdir, 2)
95 
96  def setup_network(self):
97  # Start a node with maxuploadtarget of 200 MB (/24h)
98  self.nodes = []
99  self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-maxuploadtarget=200", "-blockmaxsize=999000"]))
100 
101  def mine_full_block(self, node, address):
102  # Want to create a full block
103  # We'll generate a 66k transaction below, and 14 of them is close to the 1MB block limit
104  for j in xrange(14):
105  if len(self.utxo) < 14:
106  self.utxo = node.listunspent()
107  inputs=[]
108  outputs = {}
109  t = self.utxo.pop()
110  inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
111  remchange = t["amount"] - Decimal("0.001000")
112  outputs[address]=remchange
113  # Create a basic transaction that will send change back to ourself after account for a fee
114  # And then insert the 128 generated transaction outs in the middle rawtx[92] is where the #
115  # of txouts is stored and is the only thing we overwrite from the original transaction
116  rawtx = node.createrawtransaction(inputs, outputs)
117  newtx = rawtx[0:92]
118  newtx = newtx + self.txouts
119  newtx = newtx + rawtx[94:]
120  # Appears to be ever so slightly faster to sign with SIGHASH_NONE
121  signresult = node.signrawtransaction(newtx,None,None,"NONE")
122  txid = node.sendrawtransaction(signresult["hex"], True)
123  # Mine a full sized block which will be these transactions we just created
124  node.generate(1)
125 
126  def run_test(self):
127  # Before we connect anything, we first set the time on the node
128  # to be in the past, otherwise things break because the CNode
129  # time counters can't be reset backward after initialization
130  old_time = int(time.time() - 2*60*60*24*7)
131  self.nodes[0].setmocktime(old_time)
132 
133  # Generate some old blocks
134  self.nodes[0].generate(130)
135 
136  # test_nodes[0] will only request old blocks
137  # test_nodes[1] will only request new blocks
138  # test_nodes[2] will test resetting the counters
139  test_nodes = []
140  connections = []
141 
142  for i in xrange(3):
143  test_nodes.append(TestNode())
144  connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))
145  test_nodes[i].add_connection(connections[i])
146 
147  NetworkThread().start() # Start up network handling in another thread
148  [x.wait_for_verack() for x in test_nodes]
149 
150  # Test logic begins here
151 
152  # Now mine a big block
153  self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())
154 
155  # Store the hash; we'll request this later
156  big_old_block = self.nodes[0].getbestblockhash()
157  old_block_size = self.nodes[0].getblock(big_old_block, True)['size']
158  big_old_block = int(big_old_block, 16)
159 
160  # Advance to two days ago
161  self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24)
162 
163  # Mine one more block, so that the prior block looks old
164  self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())
165 
166  # We'll be requesting this new block too
167  big_new_block = self.nodes[0].getbestblockhash()
168  new_block_size = self.nodes[0].getblock(big_new_block)['size']
169  big_new_block = int(big_new_block, 16)
170 
171  # test_nodes[0] will test what happens if we just keep requesting the
172  # the same big old block too many times (expect: disconnect)
173 
174  getdata_request = msg_getdata()
175  getdata_request.inv.append(CInv(2, big_old_block))
176 
177  max_bytes_per_day = 200*1024*1024
178  daily_buffer = 144 * MAX_BLOCK_SIZE
179  max_bytes_available = max_bytes_per_day - daily_buffer
180  success_count = max_bytes_available // old_block_size
181 
182  # 144MB will be reserved for relaying new blocks, so expect this to
183  # succeed for ~70 tries.
184  for i in xrange(success_count):
185  test_nodes[0].send_message(getdata_request)
186  test_nodes[0].sync_with_ping()
187  assert_equal(test_nodes[0].block_receive_map[big_old_block], i+1)
188 
189  assert_equal(len(self.nodes[0].getpeerinfo()), 3)
190  # At most a couple more tries should succeed (depending on how long
191  # the test has been running so far).
192  for i in xrange(3):
193  test_nodes[0].send_message(getdata_request)
194  test_nodes[0].wait_for_disconnect()
195  assert_equal(len(self.nodes[0].getpeerinfo()), 2)
196  print "Peer 0 disconnected after downloading old block too many times"
197 
198  # Requesting the current block on test_nodes[1] should succeed indefinitely,
199  # even when over the max upload target.
200  # We'll try 200 times
201  getdata_request.inv = [CInv(2, big_new_block)]
202  for i in xrange(200):
203  test_nodes[1].send_message(getdata_request)
204  test_nodes[1].sync_with_ping()
205  assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)
206 
207  print "Peer 1 able to repeatedly download new block"
208 
209  # But if test_nodes[1] tries for an old block, it gets disconnected too.
210  getdata_request.inv = [CInv(2, big_old_block)]
211  test_nodes[1].send_message(getdata_request)
212  test_nodes[1].wait_for_disconnect()
213  assert_equal(len(self.nodes[0].getpeerinfo()), 1)
214 
215  print "Peer 1 disconnected after trying to download old block"
216 
217  print "Advancing system time on node to clear counters..."
218 
219  # If we advance the time by 24 hours, then the counters should reset,
220  # and test_nodes[2] should be able to retrieve the old block.
221  self.nodes[0].setmocktime(int(time.time()))
222  test_nodes[2].sync_with_ping()
223  test_nodes[2].send_message(getdata_request)
224  test_nodes[2].sync_with_ping()
225  assert_equal(test_nodes[2].block_receive_map[big_old_block], 1)
226 
227  print "Peer 2 able to download old block"
228 
229  [c.disconnect_node() for c in connections]
230 
231  #stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1
232  print "Restarting nodes with -whitelist=127.0.0.1"
233  stop_node(self.nodes[0], 0)
234  self.nodes[0] = start_node(0, self.options.tmpdir, ["-debug", "-whitelist=127.0.0.1", "-maxuploadtarget=1", "-blockmaxsize=999000"])
235 
236  #recreate/reconnect 3 test nodes
237  test_nodes = []
238  connections = []
239 
240  for i in xrange(3):
241  test_nodes.append(TestNode())
242  connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))
243  test_nodes[i].add_connection(connections[i])
244 
245  NetworkThread().start() # Start up network handling in another thread
246  [x.wait_for_verack() for x in test_nodes]
247 
248  #retrieve 20 blocks which should be enough to break the 1MB limit
249  getdata_request.inv = [CInv(2, big_new_block)]
250  for i in xrange(20):
251  test_nodes[1].send_message(getdata_request)
252  test_nodes[1].sync_with_ping()
253  assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)
254 
255  getdata_request.inv = [CInv(2, big_old_block)]
256  test_nodes[1].send_message(getdata_request)
257  test_nodes[1].wait_for_disconnect()
258  assert_equal(len(self.nodes[0].getpeerinfo()), 3) #node is still connected because of the whitelist
259 
260  print "Peer 1 still connected after trying to download old block (whitelisted)"
261 
262  [c.disconnect_node() for c in connections]
263 
264 if __name__ == '__main__':
265  MaxUploadTest().main()
def on_getdata(self, conn, message)
def on_close(self, conn)
def on_pong(self, conn, message)
def mine_full_block(self, node, address)
UniValue getblock(const UniValue &params, bool fHelp)
Definition: blockchain.cpp:483
def wait_until(predicate, attempts=float('inf'), timeout=float('inf'))
Definition: mininode.py:1020
UniValue getnewaddress(const UniValue &params, bool fHelp)
Definition: rpcwallet.cpp:113
def on_block(self, conn, message)
def on_inv(self, conn, message)
def initialize_chain_clean(test_dir, num_nodes)
Definition: util.py:252
def sync_with_ping(self, timeout=30)
def gen_return_txouts()
Definition: util.py:559
def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None)
Definition: util.py:281
def stop_node(node, i)
Definition: util.py:323
def add_connection(self, conn)
UniValue generate(const UniValue &params, bool fHelp)
Definition: mining.cpp:122
def send_message(self, message)
UniValue getbestblockhash(const UniValue &params, bool fHelp)
Definition: blockchain.cpp:148
UniValue getpeerinfo(const UniValue &params, bool fHelp)
Definition: net.cpp:70
UniValue setmocktime(const UniValue &params, bool fHelp)
Definition: misc.cpp:498
def p2p_port(n)
Definition: util.py:93
def assert_equal(thing1, thing2)
Definition: util.py:461