Skip to content

Commit 3eda7ea

Browse files
author
MarcoFalke
committed
Merge #18764: refactor: test: replace inv type magic numbers by constants
4a614ff test: explicit imports from test_framework.messages in p2p_invalid_messages.py (Sebastian Falbesoner) b35e1d2 test: add inventory type constant MSG_CMPCT_BLOCK (Sebastian Falbesoner) eeaaa58 test: replace inv type magic numbers by constants (Sebastian Falbesoner) Pull request description: Many functional tests still use magic numbers for inventory types, either passed to the `CInv` constructor or for comparing the `type` member of `CInv`. This PR replaces all of those by constants in the module `test_framework.messages` that have been introduced in commit c32cf9f: `MSG_TX` (1) or `MSG_BLOCK` (2). It also introduces a new constant `MSG_CMPCT_BLOCK` (naming as in `src/protocol.h`) and uses it to replace the remaining magic numbers. The occurences of the magic numbers were identified through `grep`ing for `CInv(` and `type ==`. The idea was first to create a scripted-diff, but since also adding missing `import`s is needed, this would be non-trivial. Besides, also some unneeded comments like `# 2 == "Block"` could be removed. ACKs for top commit: gzhao408: ACK [`4a614ff`](bitcoin/bitcoin@4a614ff) Tree-SHA512: 4ba4fdef9f3eef7fd5ac72cb03ca3524863d1ae292161c550424a4c1047283fa2d2e7e03017d1fbae3652b3cb14f08b8d4b368403f3f209993aef3f2e2b22784
2 parents 448bdff + 4a614ff commit 3eda7ea

13 files changed

+58
-44
lines changed

test/functional/example_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
# Avoid wildcard * imports
1717
from test_framework.blocktools import (create_block, create_coinbase)
18-
from test_framework.messages import CInv
18+
from test_framework.messages import CInv, MSG_BLOCK
1919
from test_framework.mininode import (
2020
P2PInterface,
2121
mininode_lock,
@@ -198,7 +198,7 @@ def run_test(self):
198198

199199
getdata_request = msg_getdata()
200200
for block in blocks:
201-
getdata_request.inv.append(CInv(2, block))
201+
getdata_request.inv.append(CInv(MSG_BLOCK, block))
202202
self.nodes[2].p2p.send_message(getdata_request)
203203

204204
# wait_until() will loop until a predicate condition is met. Use it to test properties of the

test/functional/feature_maxuploadtarget.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from collections import defaultdict
1414
import time
1515

16-
from test_framework.messages import CInv, msg_getdata
16+
from test_framework.messages import CInv, MSG_BLOCK, msg_getdata
1717
from test_framework.mininode import P2PInterface
1818
from test_framework.test_framework import BitcoinTestFramework
1919
from test_framework.util import assert_equal, mine_large_block
@@ -84,7 +84,7 @@ def run_test(self):
8484
# the same big old block too many times (expect: disconnect)
8585

8686
getdata_request = msg_getdata()
87-
getdata_request.inv.append(CInv(2, big_old_block))
87+
getdata_request.inv.append(CInv(MSG_BLOCK, big_old_block))
8888

8989
max_bytes_per_day = 800*1024*1024
9090
daily_buffer = 144 * 4000000
@@ -109,15 +109,15 @@ def run_test(self):
109109
# Requesting the current block on p2p_conns[1] should succeed indefinitely,
110110
# even when over the max upload target.
111111
# We'll try 800 times
112-
getdata_request.inv = [CInv(2, big_new_block)]
112+
getdata_request.inv = [CInv(MSG_BLOCK, big_new_block)]
113113
for i in range(800):
114114
p2p_conns[1].send_and_ping(getdata_request)
115115
assert_equal(p2p_conns[1].block_receive_map[big_new_block], i+1)
116116

117117
self.log.info("Peer 1 able to repeatedly download new block")
118118

119119
# But if p2p_conns[1] tries for an old block, it gets disconnected too.
120-
getdata_request.inv = [CInv(2, big_old_block)]
120+
getdata_request.inv = [CInv(MSG_BLOCK, big_old_block)]
121121
p2p_conns[1].send_message(getdata_request)
122122
p2p_conns[1].wait_for_disconnect()
123123
assert_equal(len(self.nodes[0].getpeerinfo()), 1)
@@ -145,12 +145,12 @@ def run_test(self):
145145
self.nodes[0].add_p2p_connection(TestP2PConn())
146146

147147
#retrieve 20 blocks which should be enough to break the 1MB limit
148-
getdata_request.inv = [CInv(2, big_new_block)]
148+
getdata_request.inv = [CInv(MSG_BLOCK, big_new_block)]
149149
for i in range(20):
150150
self.nodes[0].p2p.send_and_ping(getdata_request)
151151
assert_equal(self.nodes[0].p2p.block_receive_map[big_new_block], i+1)
152152

153-
getdata_request.inv = [CInv(2, big_old_block)]
153+
getdata_request.inv = [CInv(MSG_BLOCK, big_old_block)]
154154
self.nodes[0].p2p.send_and_ping(getdata_request)
155155
assert_equal(len(self.nodes[0].getpeerinfo()), 1) #node is still connected because of the whitelist
156156

test/functional/p2p_compactblocks.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import random
1111

1212
from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
13-
from test_framework.messages import BlockTransactions, BlockTransactionsRequest, calculate_shortid, CBlock, CBlockHeader, CInv, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, FromHex, HeaderAndShortIDs, msg_no_witness_block, msg_no_witness_blocktxn, msg_cmpctblock, msg_getblocktxn, msg_getdata, msg_getheaders, msg_headers, msg_inv, msg_sendcmpct, msg_sendheaders, msg_tx, msg_block, msg_blocktxn, MSG_WITNESS_FLAG, NODE_NETWORK, P2PHeaderAndShortIDs, PrefilledTransaction, ser_uint256, ToHex
13+
from test_framework.messages import BlockTransactions, BlockTransactionsRequest, calculate_shortid, CBlock, CBlockHeader, CInv, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, FromHex, HeaderAndShortIDs, msg_no_witness_block, msg_no_witness_blocktxn, msg_cmpctblock, msg_getblocktxn, msg_getdata, msg_getheaders, msg_headers, msg_inv, msg_sendcmpct, msg_sendheaders, msg_tx, msg_block, msg_blocktxn, MSG_BLOCK, MSG_CMPCT_BLOCK, MSG_WITNESS_FLAG, NODE_NETWORK, P2PHeaderAndShortIDs, PrefilledTransaction, ser_uint256, ToHex
1414
from test_framework.mininode import mininode_lock, P2PInterface
1515
from test_framework.script import CScript, OP_TRUE, OP_DROP
1616
from test_framework.test_framework import BitcoinTestFramework
@@ -44,7 +44,7 @@ def on_headers(self, message):
4444

4545
def on_inv(self, message):
4646
for x in self.last_message["inv"].inv:
47-
if x.type == 2:
47+
if x.type == MSG_BLOCK:
4848
self.block_announced = True
4949
self.announced_blockhashes.add(x.hash)
5050

@@ -307,7 +307,7 @@ def test_compactblock_construction(self, test_node, use_witness_address=True):
307307
# Now fetch the compact block using a normal non-announce getdata
308308
with mininode_lock:
309309
test_node.clear_block_announcement()
310-
inv = CInv(4, block_hash) # 4 == "CompactBlock"
310+
inv = CInv(MSG_CMPCT_BLOCK, block_hash)
311311
test_node.send_message(msg_getdata([inv]))
312312

313313
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
@@ -380,7 +380,7 @@ def test_compactblock_requests(self, test_node, segwit=True):
380380
block = self.build_block_on_tip(node, segwit=segwit)
381381

382382
if announce == "inv":
383-
test_node.send_message(msg_inv([CInv(2, block.sha256)]))
383+
test_node.send_message(msg_inv([CInv(MSG_BLOCK, block.sha256)]))
384384
wait_until(lambda: "getheaders" in test_node.last_message, timeout=30, lock=mininode_lock)
385385
test_node.send_header_for_blocks([block])
386386
else:
@@ -564,7 +564,8 @@ def test_incorrect_blocktxn_response(self, test_node):
564564

565565
# We should receive a getdata request
566566
test_node.wait_for_getdata([block.sha256], timeout=10)
567-
assert test_node.last_message["getdata"].inv[0].type == 2 or test_node.last_message["getdata"].inv[0].type == 2 | MSG_WITNESS_FLAG
567+
assert test_node.last_message["getdata"].inv[0].type == MSG_BLOCK or \
568+
test_node.last_message["getdata"].inv[0].type == MSG_BLOCK | MSG_WITNESS_FLAG
568569

569570
# Deliver the block
570571
if version == 2:
@@ -633,7 +634,7 @@ def test_compactblocks_not_at_tip(self, test_node):
633634
wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
634635

635636
test_node.clear_block_announcement()
636-
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
637+
test_node.send_message(msg_getdata([CInv(MSG_CMPCT_BLOCK, int(new_blocks[0], 16))]))
637638
wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30, lock=mininode_lock)
638639

639640
test_node.clear_block_announcement()
@@ -642,7 +643,7 @@ def test_compactblocks_not_at_tip(self, test_node):
642643
test_node.clear_block_announcement()
643644
with mininode_lock:
644645
test_node.last_message.pop("block", None)
645-
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
646+
test_node.send_message(msg_getdata([CInv(MSG_CMPCT_BLOCK, int(new_blocks[0], 16))]))
646647
wait_until(lambda: "block" in test_node.last_message, timeout=30, lock=mininode_lock)
647648
with mininode_lock:
648649
test_node.last_message["block"].block.calc_sha256()

test/functional/p2p_feefilter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from decimal import Decimal
88
import time
99

10-
from test_framework.messages import msg_feefilter
10+
from test_framework.messages import MSG_TX, msg_feefilter
1111
from test_framework.mininode import mininode_lock, P2PInterface
1212
from test_framework.test_framework import BitcoinTestFramework
1313

@@ -31,7 +31,7 @@ def __init__(self):
3131

3232
def on_inv(self, message):
3333
for i in message.inv:
34-
if (i.type == 1):
34+
if (i.type == MSG_TX):
3535
self.txinvs.append(hashToHex(i.hash))
3636

3737
def clear_invs(self):

test/functional/p2p_fingerprint.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import time
1212

1313
from test_framework.blocktools import (create_block, create_coinbase)
14-
from test_framework.messages import CInv
14+
from test_framework.messages import CInv, MSG_BLOCK
1515
from test_framework.mininode import (
1616
P2PInterface,
1717
msg_headers,
@@ -48,7 +48,7 @@ def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
4848
# Send a getdata request for a given block hash
4949
def send_block_request(self, block_hash, node):
5050
msg = msg_getdata()
51-
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
51+
msg.inv.append(CInv(MSG_BLOCK, block_hash))
5252
node.send_message(msg)
5353

5454
# Send a getheaders request for a given single block hash

test/functional/p2p_invalid_messages.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,16 @@
77
import struct
88
import sys
99

10-
from test_framework import messages
10+
from test_framework.messages import (
11+
CBlockHeader,
12+
CInv,
13+
msg_getdata,
14+
msg_headers,
15+
msg_inv,
16+
msg_ping,
17+
MSG_TX,
18+
ser_string,
19+
)
1120
from test_framework.mininode import (
1221
NetworkThread,
1322
P2PDataStore,
@@ -25,7 +34,7 @@ def __init__(self, *, str_data):
2534
self.str_data = str_data.encode() if not isinstance(str_data, bytes) else str_data
2635

2736
def serialize(self):
28-
return messages.ser_string(self.str_data)
37+
return ser_string(self.str_data)
2938

3039
def __repr__(self):
3140
return "{}(data={})".format(self.msgtype, self.str_data)
@@ -135,7 +144,7 @@ def run_test(self):
135144
# For some reason unknown to me, we sometimes have to push additional data to the
136145
# peer in order for it to realize a disconnect.
137146
try:
138-
node.p2p.send_message(messages.msg_ping(nonce=123123))
147+
node.p2p.send_message(msg_ping(nonce=123123))
139148
except IOError:
140149
pass
141150

@@ -158,7 +167,7 @@ async def swap_magic_bytes():
158167
asyncio.run_coroutine_threadsafe(swap_magic_bytes(), NetworkThread.network_event_loop).result()
159168

160169
with self.nodes[0].assert_debug_log(['PROCESSMESSAGE: INVALID MESSAGESTART ping']):
161-
conn.send_message(messages.msg_ping(nonce=0xff))
170+
conn.send_message(msg_ping(nonce=0xff))
162171
conn.wait_for_disconnect(timeout=1)
163172
self.nodes[0].disconnect_p2ps()
164173

@@ -206,13 +215,13 @@ def test_msgtype(self):
206215
def test_large_inv(self):
207216
conn = self.nodes[0].add_p2p_connection(P2PInterface())
208217
with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (0 -> 20): message inv size() = 50001']):
209-
msg = messages.msg_inv([messages.CInv(1, 1)] * 50001)
218+
msg = msg_inv([CInv(MSG_TX, 1)] * 50001)
210219
conn.send_and_ping(msg)
211220
with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (20 -> 40): message getdata size() = 50001']):
212-
msg = messages.msg_getdata([messages.CInv(1, 1)] * 50001)
221+
msg = msg_getdata([CInv(MSG_TX, 1)] * 50001)
213222
conn.send_and_ping(msg)
214223
with self.nodes[0].assert_debug_log(['Misbehaving', 'peer=4 (40 -> 60): headers message size = 2001']):
215-
msg = messages.msg_headers([messages.CBlockHeader()] * 2001)
224+
msg = msg_headers([CBlockHeader()] * 2001)
216225
conn.send_and_ping(msg)
217226
self.nodes[0].disconnect_p2ps()
218227

test/functional/p2p_leak_tx.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
55
"""Test that we don't leak txs to inbound peers that we haven't yet announced to"""
66

7-
from test_framework.messages import msg_getdata, CInv
7+
from test_framework.messages import msg_getdata, CInv, MSG_TX
88
from test_framework.mininode import P2PDataStore
99
from test_framework.test_framework import BitcoinTestFramework
1010
from test_framework.util import (
@@ -37,7 +37,7 @@ def run_test(self):
3737
txid = gen_node.sendtoaddress(gen_node.getnewaddress(), 0.01)
3838

3939
want_tx = msg_getdata()
40-
want_tx.inv.append(CInv(t=1, h=int(txid, 16)))
40+
want_tx.inv.append(CInv(t=MSG_TX, h=int(txid, 16)))
4141
inbound_peer.last_message.pop('notfound', None)
4242
inbound_peer.send_and_ping(want_tx)
4343

test/functional/p2p_node_network_limited.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
and that it responds to getdata requests for blocks correctly:
99
- send a block within 288 + 2 of the tip
1010
- disconnect peers who request blocks older than that."""
11-
from test_framework.messages import CInv, msg_getdata, msg_verack, NODE_NETWORK_LIMITED, NODE_WITNESS
11+
from test_framework.messages import CInv, MSG_BLOCK, msg_getdata, msg_verack, NODE_NETWORK_LIMITED, NODE_WITNESS
1212
from test_framework.mininode import P2PInterface, mininode_lock
1313
from test_framework.test_framework import BitcoinTestFramework
1414
from test_framework.util import (
@@ -31,7 +31,7 @@ def wait_for_addr(self, timeout=5):
3131
wait_until(test_function, timeout=timeout, lock=mininode_lock)
3232
def send_getdata_for_block(self, blockhash):
3333
getdata_request = msg_getdata()
34-
getdata_request.inv.append(CInv(2, int(blockhash, 16)))
34+
getdata_request.inv.append(CInv(MSG_BLOCK, int(blockhash, 16)))
3535
self.send_message(getdata_request)
3636

3737
class NodeNetworkLimitedTest(BitcoinTestFramework):

test/functional/p2p_segwit.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
CTxOut,
2323
CTxWitness,
2424
MAX_BLOCK_BASE_SIZE,
25+
MSG_BLOCK,
26+
MSG_TX,
2527
MSG_WITNESS_FLAG,
2628
NODE_NETWORK,
2729
NODE_WITNESS,
@@ -157,7 +159,7 @@ def on_getdata(self, message):
157159
def announce_tx_and_wait_for_getdata(self, tx, timeout=60, success=True):
158160
with mininode_lock:
159161
self.last_message.pop("getdata", None)
160-
self.send_message(msg_inv(inv=[CInv(1, tx.sha256)]))
162+
self.send_message(msg_inv(inv=[CInv(MSG_TX, tx.sha256)]))
161163
if success:
162164
self.wait_for_getdata([tx.sha256], timeout)
163165
else:
@@ -173,7 +175,7 @@ def announce_block_and_wait_for_getdata(self, block, use_header, timeout=60):
173175
if use_header:
174176
self.send_message(msg)
175177
else:
176-
self.send_message(msg_inv(inv=[CInv(2, block.sha256)]))
178+
self.send_message(msg_inv(inv=[CInv(MSG_BLOCK, block.sha256)]))
177179
self.wait_for_getheaders()
178180
self.send_message(msg)
179181
self.wait_for_getdata([block.sha256])
@@ -576,7 +578,7 @@ def test_witness_tx_relay_before_segwit_activation(self):
576578
# Verify that if a peer doesn't set nServices to include NODE_WITNESS,
577579
# the getdata is just for the non-witness portion.
578580
self.old_node.announce_tx_and_wait_for_getdata(tx)
579-
assert self.old_node.last_message["getdata"].inv[0].type == 1
581+
assert self.old_node.last_message["getdata"].inv[0].type == MSG_TX
580582

581583
# Since we haven't delivered the tx yet, inv'ing the same tx from
582584
# a witness transaction ought not result in a getdata.
@@ -1310,9 +1312,9 @@ def test_tx_relay_after_segwit_activation(self):
13101312
tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program]
13111313
# Also check that old_node gets a tx announcement, even though this is
13121314
# a witness transaction.
1313-
self.old_node.wait_for_inv([CInv(1, tx2.sha256)]) # wait until tx2 was inv'ed
1315+
self.old_node.wait_for_inv([CInv(MSG_TX, tx2.sha256)]) # wait until tx2 was inv'ed
13141316
test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=True)
1315-
self.old_node.wait_for_inv([CInv(1, tx3.sha256)])
1317+
self.old_node.wait_for_inv([CInv(MSG_TX, tx3.sha256)])
13161318

13171319
# Test that getrawtransaction returns correct witness information
13181320
# hash, size, vsize

test/functional/p2p_sendheaders.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
NODE_WITNESS,
9393
P2PInterface,
9494
mininode_lock,
95+
MSG_BLOCK,
9596
msg_block,
9697
msg_getblocks,
9798
msg_getdata,
@@ -120,7 +121,7 @@ def send_get_data(self, block_hashes):
120121
"""Request data for a list of block hashes."""
121122
msg = msg_getdata()
122123
for x in block_hashes:
123-
msg.inv.append(CInv(2, x))
124+
msg.inv.append(CInv(MSG_BLOCK, x))
124125
self.send_message(msg)
125126

126127
def send_get_headers(self, locator, hashstop):
@@ -131,7 +132,7 @@ def send_get_headers(self, locator, hashstop):
131132

132133
def send_block_inv(self, blockhash):
133134
msg = msg_inv()
134-
msg.inv = [CInv(2, blockhash)]
135+
msg.inv = [CInv(MSG_BLOCK, blockhash)]
135136
self.send_message(msg)
136137

137138
def send_header_for_blocks(self, new_blocks):

0 commit comments

Comments
 (0)