diff --git a/test/functional/abc_p2p_avalanche_peer_discovery.py b/test/functional/abc_p2p_avalanche_peer_discovery.py index 4087b6cb1..4c5fe7adc 100644 --- a/test/functional/abc_p2p_avalanche_peer_discovery.py +++ b/test/functional/abc_p2p_avalanche_peer_discovery.py @@ -1,470 +1,470 @@ # Copyright (c) 2020-2021 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the peer discovery behavior of avalanche nodes. This includes tests for the service flag, avahello handshake and proof exchange. """ import time from test_framework.address import ADDRESS_ECREG_UNSPENDABLE from test_framework.avatools import ( AvaP2PInterface, avalanche_proof_from_hex, create_coinbase_stakes, gen_proof, get_ava_p2p_interface_no_handshake, get_proof_ids, wait_for_proof, ) from test_framework.key import ECKey, ECPubKey from test_framework.messages import ( MSG_AVA_PROOF, MSG_TYPE_MASK, NODE_AVALANCHE, NODE_NETWORK, CInv, msg_getdata, ) from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, uint256_hex from test_framework.wallet_util import bytes_to_wif UNCONDITIONAL_RELAY_DELAY = 2 * 60 MAX_AVALANCHE_PERIODIC_NETWORKING = 5 * 60 class GetProofDataCountingInterface(AvaP2PInterface): def __init__(self): self.get_proof_data_count = 0 super().__init__() def on_getdata(self, message): for i in message.inv: if i.type & MSG_TYPE_MASK == MSG_AVA_PROOF: self.get_proof_data_count += 1 class AvalanchePeerDiscoveryTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [ [ "-avaproofstakeutxodustthreshold=1000000", "-avaproofstakeutxoconfirmations=3", "-persistavapeers=0", ] ] self.supports_cli = False def run_test(self): node = self.nodes[0] # duplicate the deterministic sig test from src/test/key_tests.cpp privkey = ECKey() privkey.set( bytes.fromhex( "12b004fff7f4b69ef8650e767f18f11ede158148b425660723b9f9a66e61f747" ), True, ) wif_privkey = bytes_to_wif(privkey.get_bytes()) self.log.info( "Check the node is signalling the avalanche service bit only if there is a" " proof." ) assert_equal( int(node.getnetworkinfo()["localservices"], 16) & NODE_AVALANCHE, 0 ) # Create stakes by mining blocks addrkey0 = node.get_deterministic_priv_key() blockhashes = self.generatetoaddress( node, 4, addrkey0.address, sync_fun=self.no_op ) stakes = create_coinbase_stakes(node, [blockhashes[0]], addrkey0.key) proof_sequence = 11 proof_expiration = 0 proof = node.buildavalancheproof( proof_sequence, proof_expiration, wif_privkey, stakes ) master_key = ECKey() master_key.generate() limited_id = avalanche_proof_from_hex(proof).limited_proofid delegation = node.delegateavalancheproof( uint256_hex(limited_id), bytes_to_wif(privkey.get_bytes()), master_key.get_pubkey().get_bytes().hex(), ) self.log.info("Test the avahello signature with no proof") peer = get_ava_p2p_interface_no_handshake(node) avahello = peer.wait_for_avahello().hello assert_equal(avahello.delegation.limited_proofid, 0) self.log.info( "A delegation with all zero limited id indicates that the peer has no proof" ) no_proof_peer = GetProofDataCountingInterface() node.add_p2p_connection(no_proof_peer, wait_for_verack=True) - no_proof_peer.sync_send_with_ping() + no_proof_peer.sync_with_ping() # No proof is requested with p2p_lock: assert_equal(no_proof_peer.get_proof_data_count, 0) assert_equal(len(node.getavalanchepeerinfo()), 0) self.log.info( "A peer can send another hello containing a proof, only if the previous" " delegation was empty" ) # Send another hello, with a non-null delegation no_proof_peer.send_avahello(delegation, master_key) # Check the associated proof gets requested by the node no_proof_peer.wait_until(lambda: no_proof_peer.get_proof_data_count > 0) # Send the proof proofobj = avalanche_proof_from_hex(proof) no_proof_peer.send_avaproof(proofobj) wait_for_proof(node, uint256_hex(proofobj.proofid)) # Make sure we are added as a peer avalanchepeerinfo = node.getavalanchepeerinfo() assert_equal(len(avalanchepeerinfo), 1) # With a single node assert_equal(len(avalanchepeerinfo[0]["node_list"]), 1) nodeid = avalanchepeerinfo[0]["node_list"][0] # Subsequent avahello get ignored for _ in range(3): with node.assert_debug_log( [f"Ignoring avahello from peer {nodeid}: already in our node set"] ): no_proof_peer.send_avahello(delegation, master_key) # Restart the node self.restart_node( 0, self.extra_args[0] + [ f"-avaproof={proof}", "-avamasterkey=cND2ZvtabDbJ1gucx9GWH6XT9kgTAqfb6cotPt5Q5CyxVDhid2EN", ], ) assert_equal( int(node.getnetworkinfo()["localservices"], 16) & NODE_AVALANCHE, NODE_AVALANCHE, ) def check_avahello(args): # Restart the node with the given args self.restart_node(0, self.extra_args[0] + args) peer = get_ava_p2p_interface_no_handshake(node) avahello = peer.wait_for_avahello().hello avakey = ECPubKey() avakey.set(bytes.fromhex(node.getavalanchekey())) assert avakey.verify_schnorr(avahello.sig, avahello.get_sighash(peer)) self.log.info("Test the avahello signature with a generated delegation") check_avahello( [ f"-avaproof={proof}", "-avamasterkey=cND2ZvtabDbJ1gucx9GWH6XT9kgTAqfb6cotPt5Q5CyxVDhid2EN", ] ) self.log.info("Test the avahello signature with a supplied delegation") check_avahello( [ f"-avaproof={proof}", f"-avadelegation={delegation}", f"-avamasterkey={bytes_to_wif(master_key.get_bytes())}", ] ) stakes = create_coinbase_stakes(node, [blockhashes[1]], addrkey0.key) interface_proof_hex = node.buildavalancheproof( proof_sequence, proof_expiration, wif_privkey, stakes ) limited_id = avalanche_proof_from_hex(interface_proof_hex).limited_proofid # delegate delegated_key = ECKey() delegated_key.generate() interface_delegation_hex = node.delegateavalancheproof( uint256_hex(limited_id), bytes_to_wif(privkey.get_bytes()), delegated_key.get_pubkey().get_bytes().hex(), None, ) self.log.info("Test that wrong avahello signature causes a ban") bad_interface = get_ava_p2p_interface_no_handshake(node) wrong_key = ECKey() wrong_key.generate() with node.assert_debug_log( [ "Misbehaving", ( "peer=1 (0 -> 100) DISCOURAGE THRESHOLD EXCEEDED: " "invalid-avahello-signature" ), ] ): bad_interface.send_avahello(interface_delegation_hex, wrong_key) bad_interface.wait_for_disconnect() self.log.info( "Check that receiving a valid avahello triggers a proof getdata request" ) good_interface = get_ava_p2p_interface_no_handshake(node) proofid = good_interface.send_avahello(interface_delegation_hex, delegated_key) def getdata_found(peer, proofid): with p2p_lock: return ( good_interface.last_message.get("getdata") and good_interface.last_message["getdata"].inv[-1].hash == proofid ) self.wait_until(lambda: getdata_found(good_interface, proofid)) self.log.info("Check that we can download the proof from our peer") node_proofid = avalanche_proof_from_hex(proof).proofid getdata = msg_getdata([CInv(MSG_AVA_PROOF, node_proofid)]) self.log.info("Proof has been inv'ed recently, check it can be requested") good_interface.send_message(getdata) # This is our local proof so if it was announced it can be requested # without waiting for validation. assert_equal(len(node.getavalanchepeerinfo()), 0) def proof_received(peer, proofid): with p2p_lock: return ( peer.last_message.get("avaproof") and peer.last_message["avaproof"].proof.proofid == proofid ) self.wait_until(lambda: proof_received(good_interface, node_proofid)) # Restart the node self.restart_node( 0, self.extra_args[0] + [ f"-avaproof={proof}", "-avamasterkey=cND2ZvtabDbJ1gucx9GWH6XT9kgTAqfb6cotPt5Q5CyxVDhid2EN", ], ) def wait_for_proof_validation(): # Add an inbound so the node proof can be registered and advertised node.add_p2p_connection(P2PInterface()) # Connect some blocks to trigger the proof verification self.generate(node, 1, sync_fun=self.no_op) self.wait_until(lambda: node_proofid in get_proof_ids(node)) wait_for_proof_validation() self.log.info("The proof has not been announced, it cannot be requested") peer = get_ava_p2p_interface_no_handshake(node, services=NODE_NETWORK) # Build a new proof and only announce this one _, new_proof_obj = gen_proof(self, node) new_proof = new_proof_obj.serialize().hex() new_proofid = new_proof_obj.proofid # Make the proof mature self.generate(node, 2, sync_fun=self.no_op) node.sendavalancheproof(new_proof) wait_for_proof(node, uint256_hex(new_proofid)) # Request both our local proof and the new proof getdata = msg_getdata( [CInv(MSG_AVA_PROOF, node_proofid), CInv(MSG_AVA_PROOF, new_proofid)] ) peer.send_message(getdata) self.wait_until(lambda: proof_received(peer, new_proofid)) assert not proof_received(peer, node_proofid) self.log.info("The proof is known for long enough to be requested") current_time = int(time.time()) node.setmocktime(current_time + UNCONDITIONAL_RELAY_DELAY) getdata = msg_getdata([CInv(MSG_AVA_PROOF, node_proofid)]) peer.send_message(getdata) self.wait_until(lambda: proof_received(peer, node_proofid)) # Restart the node self.restart_node( 0, self.extra_args[0] + [ f"-avaproof={proof}", "-avamasterkey=cND2ZvtabDbJ1gucx9GWH6XT9kgTAqfb6cotPt5Q5CyxVDhid2EN", ], ) wait_for_proof_validation() # The only peer is the node itself assert_equal(len(node.getavalanchepeerinfo()), 1) assert_equal(node.getavalanchepeerinfo()[0]["proof"], proof) peer = get_ava_p2p_interface_no_handshake(node) peer_proofid = peer.send_avahello(interface_delegation_hex, delegated_key) self.wait_until(lambda: getdata_found(peer, peer_proofid)) assert peer_proofid not in get_proof_ids(node) self.log.info( "Check that the peer gets added as an avalanche node as soon as the node" " knows about the proof" ) node.sendavalancheproof(interface_proof_hex) def has_node_count(count): peerinfo = node.getavalanchepeerinfo() return ( len(peerinfo) == 2 and peerinfo[-1]["proof"] == interface_proof_hex and peerinfo[-1]["nodecount"] == count ) self.wait_until(lambda: has_node_count(1)) self.log.info( "Check that the peer gets added immediately if the proof is already known" ) # Connect another peer using the same proof peer_proof_known = get_ava_p2p_interface_no_handshake(node) peer_proof_known.send_avahello(interface_delegation_hex, delegated_key) self.wait_until(lambda: has_node_count(2)) self.log.info("Check that repeated avahello messages are ignored") for i in range(3): with node.assert_debug_log(["Ignoring avahello from peer"]): peer_proof_known.send_avahello(interface_delegation_hex, delegated_key) self.log.info("Invalidate the proof and check the nodes are removed") tip = node.getbestblockhash() # Invalidate the block after the proof utxo to make the proof immature node.invalidateblock(blockhashes[2]) # Change the address to make sure we don't generate a block identical # to the one we just invalidated. Can be generate(1) after D9694 or # D9697 is landed. forked_tip = self.generatetoaddress( node, 1, ADDRESS_ECREG_UNSPENDABLE, sync_fun=self.no_op )[0] self.wait_until(lambda: len(node.getavalanchepeerinfo()) == 1) assert peer_proofid not in get_proof_ids(node) self.log.info("Reorg back and check the nodes are added back") node.invalidateblock(forked_tip) node.reconsiderblock(tip) self.wait_until(lambda: has_node_count(2), timeout=2) self.log.info( "Check the node sends an avahello message to all peers even if the" " avalanche service bit is not advertised" ) for _ in range(3): nonavapeer = get_ava_p2p_interface_no_handshake(node, services=NODE_NETWORK) nonavapeer.wait_for_avahello() self.log.info( "Check the node waits for inbound connection to advertise its proof" ) self.restart_node( 0, self.extra_args[0] + [ f"-avaproof={proof}", f"-avadelegation={delegation}", f"-avamasterkey={bytes_to_wif(master_key.get_bytes())}", ], ) outbound = AvaP2PInterface() outbound.master_privkey, outbound.proof = gen_proof(self, node) node.add_outbound_p2p_connection( outbound, p2p_idx=1, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) # Check the proof is not advertised when there is no inbound hello = outbound.wait_for_avahello().hello assert_equal(hello.delegation.limited_proofid, 0) outbound.avahello = None # Check we don't get any avahello message until we have inbounds for _ in range(5): node.mockscheduler(MAX_AVALANCHE_PERIODIC_NETWORKING) - outbound.sync_send_with_ping() + outbound.sync_with_ping() assert outbound.avahello is None # Add an inbound inbound = node.add_p2p_connection(P2PInterface()) # Wait for the periodic update node.mockscheduler(MAX_AVALANCHE_PERIODIC_NETWORKING) # Check we got an avahello with the expected proof hello = outbound.wait_for_avahello().hello assert_equal(hello.delegation.limited_proofid, proofobj.limited_proofid) outbound.avahello = None # Check we don't get any avahello message anymore for _ in range(5): node.mockscheduler(MAX_AVALANCHE_PERIODIC_NETWORKING) - outbound.sync_send_with_ping() + outbound.sync_with_ping() assert outbound.avahello is None # Disconnect the inbound peer inbound.peer_disconnect() inbound.wait_for_disconnect() # Add another outbound peer other_outbound = AvaP2PInterface() other_outbound.master_privkey, other_outbound.proof = gen_proof(self, node) node.add_outbound_p2p_connection( other_outbound, p2p_idx=2, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) # Check we got an avahello with the expected proof, because the inbound # capability has been latched hello = other_outbound.wait_for_avahello().hello assert_equal(hello.delegation.limited_proofid, proofobj.limited_proofid) if __name__ == "__main__": AvalanchePeerDiscoveryTest().main() diff --git a/test/functional/abc_p2p_avalanche_quorum.py b/test/functional/abc_p2p_avalanche_quorum.py index c8ecf4aa0..693b3a3d3 100644 --- a/test/functional/abc_p2p_avalanche_quorum.py +++ b/test/functional/abc_p2p_avalanche_quorum.py @@ -1,267 +1,267 @@ # Copyright (c) 2020-2022 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the quorum detection of avalanche.""" from test_framework.avatools import ( AvaP2PInterface, build_msg_avaproofs, gen_proof, get_ava_p2p_interface_no_handshake, get_proof_ids, wait_for_proof, ) from test_framework.key import ECPubKey from test_framework.messages import ( NODE_AVALANCHE, NODE_NETWORK, AvalancheVote, AvalancheVoteError, ) from test_framework.p2p import p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, uint256_hex class AvalancheQuorumTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.min_avaproofs_node_count = 8 self.extra_args = [ [ "-avaproofstakeutxodustthreshold=1000000", "-avaproofstakeutxoconfirmations=1", "-avacooldown=0", "-avatimeout=0", "-avaminquorumstake=150000000", "-avaminquorumconnectedstakeratio=0.8", "-minimumchainwork=0", "-persistavapeers=0", ] ] * self.num_nodes self.extra_args[0] = self.extra_args[0] + ["-avaminavaproofsnodecount=0"] self.extra_args[1] = self.extra_args[1] + [ f"-avaminavaproofsnodecount={self.min_avaproofs_node_count}" ] self.extra_args[2] = self.extra_args[2] + [ f"-avaminavaproofsnodecount={self.min_avaproofs_node_count}" ] def run_test(self): # Initially all nodes start with 8 nodes attached to a single proof privkey, proof = gen_proof(self, self.nodes[0]) for node in self.nodes: for _ in range(8): n = get_ava_p2p_interface_no_handshake(node) success = node.addavalanchenode( n.nodeid, privkey.get_pubkey().get_bytes().hex(), proof.serialize().hex(), ) assert success is True # Prepare peers proofs peers = [] for i in range(0, self.min_avaproofs_node_count + 1): key, proof = gen_proof(self, self.nodes[0]) peers.append({"key": key, "proof": proof}) # Let the nodes known about all the blocks then disconnect them so we're # sure they won't exchange proofs when we start connecting peers. self.sync_all() self.disconnect_nodes(0, 1) # Restart node 2 to apply the minimum chainwork and make sure it's still # in IBD state. chainwork = int(self.nodes[2].getblockchaininfo()["chainwork"], 16) self.restart_node( 2, extra_args=self.extra_args[2] + [f"-minimumchainwork={chainwork + 2:#x}"] ) assert self.nodes[2].getblockchaininfo()["initialblockdownload"] # Build polling nodes pollers = [get_ava_p2p_interface_no_handshake(node) for node in self.nodes] def poll_and_assert_response(node, expected): pubkey = ECPubKey() pubkey.set(bytes.fromhex(node.getavalanchekey())) poller = pollers[node.index] # Send poll for best block block = int(node.getbestblockhash(), 16) poller.send_poll([block]) # Get response and check that the vote is what we expect response = poller.wait_for_avaresponse() r = response.response assert pubkey.verify_schnorr(response.sig, r.get_hash()) assert_equal(len(r.votes), 1) actual = repr(r.votes[0]) expected = repr(AvalancheVote(expected, block)) assert_equal(actual, expected) p2p_idx = 0 def get_ava_outbound(node, peer, empty_avaproof): nonlocal p2p_idx avapeer = AvaP2PInterface() avapeer.proof = peer["proof"] avapeer.master_privkey = peer["key"] node.add_outbound_p2p_connection( avapeer, p2p_idx=p2p_idx, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) p2p_idx += 1 avapeer.nodeid = node.getpeerinfo()[-1]["id"] peer["node"] = avapeer # There is no compact proof request if the node is in IBD state if not node.getblockchaininfo()["initialblockdownload"]: avapeer.wait_until(lambda: avapeer.last_message.get("getavaproofs")) if empty_avaproof: avapeer.send_message(build_msg_avaproofs([])) - avapeer.sync_send_with_ping() + avapeer.sync_with_ping() with p2p_lock: assert_equal(avapeer.message_count.get("avaproofsreq", 0), 0) else: avapeer.send_and_ping(build_msg_avaproofs([peer["proof"]])) avapeer.wait_until(lambda: avapeer.last_message.get("avaproofsreq")) return avapeer def add_avapeer_and_check_status(peer, expected_status, empty_avaproof=False): for i, node in enumerate(self.nodes): get_ava_outbound(node, peer, empty_avaproof) poll_and_assert_response(node, expected_status[i]) # Start polling. The response should be UNKNOWN because there's not # enough stake [ poll_and_assert_response(node, AvalancheVoteError.UNKNOWN) for node in self.nodes ] # Create one peer with half the remaining missing stake and add one # node add_avapeer_and_check_status( peers[0], [ AvalancheVoteError.UNKNOWN, AvalancheVoteError.UNKNOWN, AvalancheVoteError.UNKNOWN, ], ) # Create a second peer with the other half and add one node. # This is enough for node0 but not node1 add_avapeer_and_check_status( peers[1], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.UNKNOWN, AvalancheVoteError.UNKNOWN, ], ) # Add more peers for triggering the avaproofs messaging for i in range(2, self.min_avaproofs_node_count - 1): add_avapeer_and_check_status( peers[i], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.UNKNOWN, AvalancheVoteError.UNKNOWN, ], ) add_avapeer_and_check_status( peers[self.min_avaproofs_node_count - 1], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.ACCEPTED, AvalancheVoteError.UNKNOWN, ], ) # The proofs are not requested during IBD, so node 2 has no proof yet. assert_equal(len(get_proof_ids(self.nodes[2])), 0) # And all the nodes are pending assert_equal( self.nodes[2].getavalancheinfo()["network"]["pending_node_count"], self.min_avaproofs_node_count, ) self.generate(self.nodes[2], 1, sync_fun=self.no_op) assert not self.nodes[2].getblockchaininfo()["initialblockdownload"] # Connect the pending nodes so the next compact proofs requests can get # accounted for for i in range(self.min_avaproofs_node_count): node.sendavalancheproof(peers[i]["proof"].serialize().hex()) assert_equal( self.nodes[2].getavalancheinfo()["network"]["pending_node_count"], 0 ) # The avaproofs message are not accounted during IBD, so this is not # enough. poll_and_assert_response(self.nodes[2], AvalancheVoteError.UNKNOWN) # Connect more peers to reach the message threshold while node 2 is out # of IBD. for i in range(self.min_avaproofs_node_count - 1): add_avapeer_and_check_status( peers[i], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.ACCEPTED, AvalancheVoteError.UNKNOWN, ], ) # The messages is not accounted when there is no shortid add_avapeer_and_check_status( peers[self.min_avaproofs_node_count - 1], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.ACCEPTED, AvalancheVoteError.UNKNOWN, ], empty_avaproof=True, ) # The messages are accounted and the node quorum finally valid add_avapeer_and_check_status( peers[self.min_avaproofs_node_count], [ AvalancheVoteError.ACCEPTED, AvalancheVoteError.ACCEPTED, AvalancheVoteError.ACCEPTED, ], ) # Unless there is not enough nodes to poll for node in self.nodes: avapeers = [p2p for p2p in node.p2ps if p2p not in pollers] for peer in avapeers[7:]: peer.peer_disconnect() peer.wait_for_disconnect() poll_and_assert_response(node, AvalancheVoteError.UNKNOWN) # Add a node back and check it resumes the quorum status avapeer = AvaP2PInterface(self, node) node.add_p2p_connection(avapeer) wait_for_proof(node, uint256_hex(avapeer.proof.proofid)) poll_and_assert_response(node, AvalancheVoteError.ACCEPTED) if __name__ == "__main__": AvalancheQuorumTest().main() diff --git a/test/functional/abc_p2p_compactproofs.py b/test/functional/abc_p2p_compactproofs.py index fe551f88b..5ca22c186 100644 --- a/test/functional/abc_p2p_compactproofs.py +++ b/test/functional/abc_p2p_compactproofs.py @@ -1,736 +1,736 @@ # Copyright (c) 2022 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test proof inventory relaying """ import random import time from test_framework.avatools import ( AvaP2PInterface, NoHandshakeAvaP2PInterface, build_msg_avaproofs, gen_proof, get_ava_p2p_interface, get_proof_ids, wait_for_proof, ) from test_framework.messages import ( NODE_AVALANCHE, NODE_NETWORK, AvalanchePrefilledProof, calculate_shortid, msg_avaproofsreq, msg_getavaproofs, ) from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import MAX_NODES, assert_equal, p2p_port, uint256_hex # Timeout after which the proofs can be cleaned up AVALANCHE_AVAPROOFS_TIMEOUT = 2 * 60 # Max interval between 2 periodic networking processing AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL = 5 * 60 class ProofStoreP2PInterface(AvaP2PInterface): def __init__(self, test_framework=None, node=None): self.proofs = [] super().__init__(test_framework, node) def on_avaproof(self, message): self.proofs.append(message.proof) def get_proofs(self): with p2p_lock: return self.proofs class CompactProofsTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args = [ [ "-avaproofstakeutxodustthreshold=1000000", "-avaproofstakeutxoconfirmations=1", "-avacooldown=0", "-whitelist=noban@127.0.0.1", "-persistavapeers=0", ] ] * self.num_nodes def setup_network(self): # Don't connect the nodes self.setup_nodes() @staticmethod def received_avaproofs(peer): with p2p_lock: return peer.last_message.get("avaproofs") @staticmethod def get_avaproofs(peer): with p2p_lock: return peer.last_message.pop("avaproofs", None) def test_send_outbound_getavaproofs(self): self.log.info( "Check we send a getavaproofs message to our avalanche outbound peers" ) node = self.nodes[0] p2p_idx = 0 non_avapeers = [] for _ in range(4): peer = P2PInterface() node.add_outbound_p2p_connection( peer, p2p_idx=p2p_idx, connection_type="outbound-full-relay", services=NODE_NETWORK, ) non_avapeers.append(peer) p2p_idx += 1 inbound_avapeers = [ node.add_p2p_connection(NoHandshakeAvaP2PInterface()) for _ in range(4) ] outbound_avapeers = [] # With a proof and the service bit set for _ in range(4): peer = AvaP2PInterface(self, node) node.add_outbound_p2p_connection( peer, p2p_idx=p2p_idx, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) outbound_avapeers.append(peer) p2p_idx += 1 # Without a proof and no service bit set for _ in range(4): peer = AvaP2PInterface() node.add_outbound_p2p_connection( peer, p2p_idx=p2p_idx, connection_type="outbound-full-relay", services=NODE_NETWORK, ) outbound_avapeers.append(peer) p2p_idx += 1 def all_peers_received_getavaproofs(): with p2p_lock: return all( p.last_message.get("getavaproofs") for p in outbound_avapeers ) self.wait_until(all_peers_received_getavaproofs) with p2p_lock: assert all( p.message_count.get("getavaproofs", 0) >= 1 for p in outbound_avapeers ) assert all( p.message_count.get("getavaproofs", 0) == 0 for p in non_avapeers ) assert all( p.message_count.get("getavaproofs", 0) == 0 for p in inbound_avapeers ) self.log.info( "Check we send periodic getavaproofs message to some of our peers" ) def count_outbounds_getavaproofs(): with p2p_lock: return sum( [p.message_count.get("getavaproofs", 0) for p in outbound_avapeers] ) outbounds_getavaproofs = count_outbounds_getavaproofs() node.mockscheduler(AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL) self.wait_until( lambda: count_outbounds_getavaproofs() == outbounds_getavaproofs + 3 ) outbounds_getavaproofs += 3 with p2p_lock: assert all( p.message_count.get("getavaproofs", 0) == 0 for p in non_avapeers ) assert all( p.message_count.get("getavaproofs", 0) == 0 for p in inbound_avapeers ) self.log.info( "After the first avaproofs has been received, all the peers are requested" " periodically" ) responding_outbound_avapeer = AvaP2PInterface(self, node) node.add_outbound_p2p_connection( responding_outbound_avapeer, p2p_idx=p2p_idx, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) p2p_idx += 1 outbound_avapeers.append(responding_outbound_avapeer) self.wait_until(all_peers_received_getavaproofs) _, proof = gen_proof(self, node) # Send the avaproofs message avaproofs = build_msg_avaproofs([proof]) responding_outbound_avapeer.send_and_ping(avaproofs) # Now the node will request from all its peers at each time period outbounds_getavaproofs = count_outbounds_getavaproofs() num_outbound_avapeers = len(outbound_avapeers) node.mockscheduler(AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL) self.wait_until( lambda: count_outbounds_getavaproofs() == outbounds_getavaproofs + num_outbound_avapeers ) outbounds_getavaproofs += num_outbound_avapeers self.log.info("Empty avaproofs will not trigger any request") for p in outbound_avapeers: p.send_message(build_msg_avaproofs([])) with p2p_lock: # Only this peer actually sent a proof assert_equal( responding_outbound_avapeer.message_count.get("avaproofsreq", 0), 1 ) assert_equal( sum( [p.message_count.get("avaproofsreq", 0) for p in outbound_avapeers] ), 1, ) # Sanity checks assert all( p.message_count.get("getavaproofs", 0) == 0 for p in non_avapeers ) assert all( p.message_count.get("getavaproofs", 0) == 0 for p in inbound_avapeers ) def test_send_manual_getavaproofs(self): self.log.info( "Check we send a getavaproofs message to our manually connected peers that" " support avalanche" ) node = self.nodes[0] # Get rid of previously connected nodes node.disconnect_p2ps() def added_node_connected(ip_port): added_node_info = node.getaddednodeinfo(ip_port) return len(added_node_info) == 1 and added_node_info[0]["connected"] def connect_callback(address, port): self.log.debug(f"Connecting to {address}:{port}") p = AvaP2PInterface(self, node) p2p_idx = 1 p.peer_accept_connection( connect_cb=connect_callback, connect_id=p2p_idx, net=node.chain, timeout_factor=node.timeout_factor, services=NODE_NETWORK | NODE_AVALANCHE, )() ip_port = f"127.0.0.1:{p2p_port(MAX_NODES - p2p_idx)}" node.addnode(node=ip_port, command="add") self.wait_until(lambda: added_node_connected(ip_port)) assert_equal(node.getpeerinfo()[-1]["addr"], ip_port) assert_equal(node.getpeerinfo()[-1]["connection_type"], "manual") # Make sure p.is_connected is set, otherwise the last_message check # below will assert. p.wait_for_connect() p.wait_until(lambda: p.last_message.get("getavaproofs")) def test_respond_getavaproofs(self): self.log.info("Check the node responds to getavaproofs messages") node = self.nodes[0] def send_getavaproof_check_shortid_len(peer, expected_len): peer.send_message(msg_getavaproofs()) self.wait_until(lambda: self.received_avaproofs(peer)) avaproofs = self.received_avaproofs(peer) assert_equal(len(avaproofs.shortids), expected_len) # Initially the node has 0 peer self.restart_node(0) assert_equal(len(get_proof_ids(node)), 0) peer = node.add_p2p_connection(NoHandshakeAvaP2PInterface()) send_getavaproof_check_shortid_len(peer, 0) # Add some peers with a proof sending_peer = node.add_p2p_connection(NoHandshakeAvaP2PInterface()) avapeers = [] for _ in range(15): p = get_ava_p2p_interface(self, node) sending_peer.send_avaproof(p.proof) wait_for_proof(node, uint256_hex(p.proof.proofid)) avapeers.append(p) proofids = get_proof_ids(node) assert_equal(len(proofids), 15) receiving_peer = node.add_p2p_connection(NoHandshakeAvaP2PInterface()) send_getavaproof_check_shortid_len(receiving_peer, len(proofids)) avaproofs = self.get_avaproofs(receiving_peer) assert avaproofs is not None expected_shortids = [ calculate_shortid(avaproofs.key0, avaproofs.key1, proofid) for proofid in sorted(proofids) ] assert_equal(expected_shortids, avaproofs.shortids) # Don't expect any prefilled proof for now assert_equal(len(avaproofs.prefilled_proofs), 0) # Disconnect some peers and check their proof is no longer sent in the # compact proofs messages for i in range(10): avapeers[i].peer_disconnect() avapeers[i].wait_for_disconnect() proofids.remove(avapeers[i].proof.proofid) assert_equal(len(proofids), 5) send_getavaproof_check_shortid_len(receiving_peer, len(proofids)) avaproofs = self.get_avaproofs(receiving_peer) assert avaproofs is not None expected_shortids = [ calculate_shortid(avaproofs.key0, avaproofs.key1, proofid) for proofid in sorted(proofids) ] assert_equal(expected_shortids, avaproofs.shortids) def test_request_missing_proofs(self): self.log.info( "Check the node requests the missing proofs after receiving an avaproofs" " message" ) node = self.nodes[0] self.restart_node(0) key0 = random.randint(0, 2**64 - 1) key1 = random.randint(0, 2**64 - 1) proofs = [gen_proof(self, node)[1] for _ in range(10)] # Build a map from proofid to shortid. Use sorted proofids so we don't # have the same indices than the `proofs` list. proofids = [p.proofid for p in proofs] shortid_map = {} for proofid in sorted(proofids): shortid_map[proofid] = calculate_shortid(key0, key1, proofid) self.log.info("The node ignores unsollicited avaproofs") spam_peer = get_ava_p2p_interface(self, node) msg = build_msg_avaproofs(proofs, prefilled_proofs=[], key_pair=[key0, key1]) with node.assert_debug_log(["Ignoring unsollicited avaproofs"]): spam_peer.send_message(msg) def received_avaproofsreq(peer): with p2p_lock: return peer.last_message.get("avaproofsreq") p2p_idx = 0 def add_avalanche_p2p_outbound(): nonlocal p2p_idx peer = AvaP2PInterface(self, node) node.add_outbound_p2p_connection( peer, p2p_idx=p2p_idx, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) p2p_idx += 1 peer.wait_until(lambda: peer.last_message.get("getavaproofs")) return peer def expect_indices(shortids, expected_indices, prefilled_proofs=None): nonlocal p2p_idx msg = build_msg_avaproofs( [], prefilled_proofs=prefilled_proofs, key_pair=[key0, key1] ) msg.shortids = shortids peer = add_avalanche_p2p_outbound() peer.send_message(msg) self.wait_until(lambda: received_avaproofsreq(peer)) avaproofsreq = received_avaproofsreq(peer) assert_equal(avaproofsreq.indices, expected_indices) self.log.info("Check no proof is requested if there is no shortid") msg = build_msg_avaproofs([]) sender = add_avalanche_p2p_outbound() with node.assert_debug_log(["Got an avaproofs message with no shortid"]): sender.send_message(msg) # Make sure we don't get an avaproofsreq message - sender.sync_send_with_ping() + sender.sync_with_ping() with p2p_lock: assert_equal(sender.message_count.get("avaproofsreq", 0), 0) self.log.info("Check the node requests all the proofs if it known none") expect_indices(list(shortid_map.values()), list(range(len(shortid_map)))) self.log.info("Check the node requests only the missing proofs") known_proofids = [] for proof in proofs[:5]: node.sendavalancheproof(proof.serialize().hex()) known_proofids.append(proof.proofid) expected_indices = [ i for i, proofid in enumerate(shortid_map) if proofid not in known_proofids ] expect_indices(list(shortid_map.values()), expected_indices) self.log.info("Check the node don't request prefilled proofs") # Get the indices for a couple of proofs indice_proof5 = list(shortid_map.keys()).index(proofids[5]) indice_proof6 = list(shortid_map.keys()).index(proofids[6]) prefilled_proofs = [ AvalanchePrefilledProof(indice_proof5, proofs[5]), AvalanchePrefilledProof(indice_proof6, proofs[6]), ] prefilled_proofs = sorted( prefilled_proofs, key=lambda prefilled_proof: prefilled_proof.index ) remaining_shortids = [ shortid for proofid, shortid in shortid_map.items() if proofid not in proofids[5:7] ] known_proofids.extend(proofids[5:7]) expected_indices = [ i for i, proofid in enumerate(shortid_map) if proofid not in known_proofids ] expect_indices( remaining_shortids, expected_indices, prefilled_proofs=prefilled_proofs ) self.log.info("Check the node requests no proof if it knows all of them") for proof in proofs[5:]: node.sendavalancheproof(proof.serialize().hex()) known_proofids.append(proof.proofid) expect_indices(list(shortid_map.values()), []) self.log.info("Check out of bounds index") bad_peer = add_avalanche_p2p_outbound() msg = build_msg_avaproofs( [], prefilled_proofs=[ AvalanchePrefilledProof(len(shortid_map) + 1, gen_proof(self, node)[1]) ], key_pair=[key0, key1], ) msg.shortids = list(shortid_map.values()) with node.assert_debug_log(["Misbehaving", "avaproofs-bad-indexes"]): bad_peer.send_message(msg) bad_peer.wait_for_disconnect() self.log.info("An invalid prefilled proof will trigger a ban") _, no_stake = gen_proof(self, node) no_stake.stakes = [] bad_peer = add_avalanche_p2p_outbound() msg = build_msg_avaproofs( [], prefilled_proofs=[ AvalanchePrefilledProof(len(shortid_map), no_stake), ], key_pair=[key0, key1], ) msg.shortids = list(shortid_map.values()) with node.assert_debug_log(["Misbehaving", "invalid-proof"]): bad_peer.send_message(msg) bad_peer.wait_for_disconnect() def test_send_missing_proofs(self): self.log.info("Check the node respond to missing proofs requests") node = self.nodes[0] self.restart_node( 0, extra_args=self.extra_args[0] + ["-avaminquorumstake=1000000", "-avaminavaproofsnodecount=0"], ) numof_proof = 10 avapeers = [get_ava_p2p_interface(self, node) for _ in range(numof_proof)] proofs = [peer.proof for peer in avapeers] assert_equal(node.getavalancheinfo()["ready_to_poll"], True) for proof in proofs: node.sendavalancheproof(proof.serialize().hex()) proofids = get_proof_ids(node) assert all(proof.proofid in proofids for proof in proofs) self.log.info("Unsollicited requests are ignored") peer = node.add_p2p_connection(ProofStoreP2PInterface()) peer.send_and_ping(msg_avaproofsreq()) assert_equal(len(peer.get_proofs()), 0) def request_proofs(peer): peer.send_message(msg_getavaproofs()) self.wait_until(lambda: self.received_avaproofs(peer)) avaproofs = self.received_avaproofs(peer) assert_equal(len(avaproofs.shortids), numof_proof) return avaproofs _ = request_proofs(peer) self.log.info("Sending an empty request has no effect") peer.send_and_ping(msg_avaproofsreq()) assert_equal(len(peer.get_proofs()), 0) self.log.info("Check the requested proofs are sent by the node") def check_received_proofs(indices): requester = node.add_p2p_connection(ProofStoreP2PInterface()) avaproofs = request_proofs(requester) req = msg_avaproofsreq() req.indices = indices requester.send_message(req) # Check we got the expected number of proofs self.wait_until(lambda: len(requester.get_proofs()) == len(indices)) # Check we got the expected proofs received_shortids = [ calculate_shortid(avaproofs.key0, avaproofs.key1, proof.proofid) for proof in requester.get_proofs() ] assert_equal( set(received_shortids), {avaproofs.shortids[i] for i in indices} ) # Only the first proof check_received_proofs([0]) # Only the last proof check_received_proofs([numof_proof - 1]) # Half first check_received_proofs(range(0, numof_proof // 2)) # Half last check_received_proofs(range(numof_proof // 2, numof_proof)) # Even check_received_proofs([i for i in range(numof_proof) if i % 2 == 0]) # Odds check_received_proofs([i for i in range(numof_proof) if i % 2 == 1]) # All check_received_proofs(range(numof_proof)) self.log.info( "Check the node will not send the proofs if not requested before the" " timeout elapsed" ) # Disconnect the peers except the ones with a proof attached for peer in node.p2ps: if peer not in avapeers: peer.peer_disconnect() peer.wait_for_disconnect() mocktime = int(time.time()) node.setmocktime(mocktime) slow_peer = ProofStoreP2PInterface(self, node) node.add_outbound_p2p_connection( slow_peer, p2p_idx=0, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) numof_proof += 1 slow_peer.wait_until(lambda: slow_peer.last_message.get("getavaproofs")) # Make sure to send at least one avaproofs message, otherwise the node # will only send a getavaproofs message to up to 3 nodes and the test # might randomly fail. avaproofs_msg = build_msg_avaproofs([slow_peer.proof]) slow_peer.send_and_ping(avaproofs_msg) slow_peer.nodeid = node.getpeerinfo()[-1]["id"] _ = request_proofs(slow_peer) # Elapse the timeout mocktime += AVALANCHE_AVAPROOFS_TIMEOUT + 1 node.setmocktime(mocktime) node.mockscheduler(AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL) # Periodic compact proofs requests are sent in the same loop than the # cleanup, so when such a request is made we are sure the cleanup did # happen. slow_peer.wait_until(lambda: slow_peer.message_count.get("getavaproofs") > 1) req = msg_avaproofsreq() req.indices = range(numof_proof) slow_peer.send_and_ping(req) # Check we get no proof assert_equal(len(slow_peer.get_proofs()), 0) def test_compact_proofs_download_on_connect(self): self.log.info( "Check the node get compact proofs upon avalanche outbound discovery" ) requestee = self.nodes[0] requester = self.nodes[1] self.restart_node(0) numof_proof = 10 proofs = [gen_proof(self, requestee)[1] for _ in range(numof_proof)] for proof in proofs: requestee.sendavalancheproof(proof.serialize().hex()) proofids = get_proof_ids(requestee) assert all(proof.proofid in proofids for proof in proofs) # Start the requester and check it gets all the proofs self.start_node(1) self.connect_nodes(0, 1) self.wait_until( lambda: all(proof.proofid in proofids for proof in get_proof_ids(requester)) ) def test_no_compactproofs_during_ibs(self): self.log.info("Check the node don't request compact proofs during IBD") node = self.nodes[0] chainwork = int(node.getblockchaininfo()["chainwork"], 16) self.restart_node( 0, extra_args=self.extra_args[0] + [f"-minimumchainwork={chainwork + 2:#x}"] ) assert node.getblockchaininfo()["initialblockdownload"] peer = P2PInterface() node.add_outbound_p2p_connection( peer, p2p_idx=0, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) # Force the node to process the sending loop - peer.sync_send_with_ping() + peer.sync_with_ping() with p2p_lock: assert_equal(peer.message_count.get("getavaproofs", 0), 0) # Make sure there is no message sent as part as the periodic network # messaging either node.mockscheduler(AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL) - peer.sync_send_with_ping() + peer.sync_with_ping() with p2p_lock: assert_equal(peer.message_count.get("getavaproofs", 0), 0) def test_send_inbound_getavaproofs(self): self.log.info("Check we also request the inbounds for their compact proofs") node = self.nodes[0] self.restart_node( 0, extra_args=self.extra_args[0] + ["-avaminquorumstake=1000000", "-avaminavaproofsnodecount=0"], ) assert_equal(node.getavalancheinfo()["ready_to_poll"], False) outbound = AvaP2PInterface() node.add_outbound_p2p_connection(outbound, p2p_idx=0) inbound = AvaP2PInterface() node.add_p2p_connection(inbound) inbound.nodeid = node.getpeerinfo()[-1]["id"] def count_getavaproofs(peers): with p2p_lock: return sum( [peer.message_count.get("getavaproofs", 0) for peer in peers] ) # Upon connection only the outbound gets a compact proofs message assert_equal(count_getavaproofs([inbound]), 0) self.wait_until(lambda: count_getavaproofs([outbound]) == 1) # Periodic send will include the inbound as well current_total = count_getavaproofs([inbound, outbound]) while count_getavaproofs([inbound]) == 0: node.mockscheduler(AVALANCHE_MAX_PERIODIC_NETWORKING_INTERVAL) self.wait_until( lambda: count_getavaproofs([inbound, outbound]) > current_total ) current_total = count_getavaproofs([inbound, outbound]) def run_test(self): # Most if the tests only need a single node, let the other ones start # the node when required self.stop_node(1) self.test_send_outbound_getavaproofs() self.test_send_manual_getavaproofs() self.test_respond_getavaproofs() self.test_request_missing_proofs() self.test_send_missing_proofs() self.test_compact_proofs_download_on_connect() self.test_no_compactproofs_during_ibs() self.test_send_inbound_getavaproofs() if __name__ == "__main__": CompactProofsTest().main() diff --git a/test/functional/abc_p2p_getavaaddr.py b/test/functional/abc_p2p_getavaaddr.py index 0861fc401..6cb98558b 100644 --- a/test/functional/abc_p2p_getavaaddr.py +++ b/test/functional/abc_p2p_getavaaddr.py @@ -1,541 +1,541 @@ # Copyright (c) 2022 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test getavaaddr p2p message""" import time from decimal import Decimal from test_framework.avatools import AvaP2PInterface, gen_proof from test_framework.messages import ( NODE_AVALANCHE, NODE_NETWORK, AvalancheVote, AvalancheVoteError, msg_avahello, msg_getaddr, msg_getavaaddr, msg_verack, ) from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import MAX_NODES, assert_equal, p2p_port, uint256_hex # getavaaddr time interval in seconds, as defined in net_processing.cpp # A node will ignore repeated getavaaddr during this interval GETAVAADDR_INTERVAL = 2 * 60 # Address are sent every 30s on average, with a Poisson filter. Use a large # enough delay so it's very unlikely we don't get the message within this time. MAX_ADDR_SEND_DELAY = 10 * 60 # The interval between avalanche statistics computation AVALANCHE_STATISTICS_INTERVAL = 10 * 60 # The getavaaddr messages are sent every 2 to 5 minutes MAX_GETAVAADDR_DELAY = 5 * 60 class AddrReceiver(P2PInterface): def __init__(self): super().__init__() self.received_addrs = None def get_received_addrs(self): with p2p_lock: return self.received_addrs def on_addr(self, message): self.received_addrs = [] for addr in message.addrs: self.received_addrs.append(f"{addr.ip}:{addr.port}") def addr_received(self): return self.received_addrs is not None class MutedAvaP2PInterface(AvaP2PInterface): def __init__(self, test_framework=None, node=None): super().__init__(test_framework, node) self.is_responding = False self.privkey = None self.addr = None self.poll_received = 0 def set_addr(self, addr): self.addr = addr def on_avapoll(self, message): self.poll_received += 1 class AllYesAvaP2PInterface(MutedAvaP2PInterface): def __init__(self, test_framework=None, node=None): super().__init__(test_framework, node) self.is_responding = True def on_avapoll(self, message): self.send_avaresponse( message.poll.round, [ AvalancheVote(AvalancheVoteError.ACCEPTED, inv.hash) for inv in message.poll.invs ], self.master_privkey if self.delegation is None else self.delegated_privkey, ) super().on_avapoll(message) class AvaHelloInterface(AvaP2PInterface): def __init__(self): super().__init__() def on_version(self, message): self.send_message(msg_verack()) self.send_message(msg_avahello()) class AvaAddrTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = False self.num_nodes = 1 self.extra_args = [ [ "-avaproofstakeutxodustthreshold=1000000", "-avaproofstakeutxoconfirmations=1", "-avacooldown=0", "-avaminquorumstake=0", "-avaminavaproofsnodecount=0", "-whitelist=noban@127.0.0.1", "-persistavapeers=0", ] ] def check_all_peers_received_getavaaddr_once(self, avapeers): def received_all_getavaaddr(avapeers): with p2p_lock: return all(p.last_message.get("getavaaddr") for p in avapeers) self.wait_until(lambda: received_all_getavaaddr(avapeers)) with p2p_lock: assert all(p.message_count.get("getavaaddr", 0) == 1 for p in avapeers) def getavaaddr_interval_test(self): node = self.nodes[0] # Init mock time mock_time = int(time.time()) node.setmocktime(mock_time) # Add some avalanche peers to the node for _ in range(10): node.add_p2p_connection(AllYesAvaP2PInterface(self, node)) # Build some statistics to ensure some addresses will be returned def all_peers_received_poll(): with p2p_lock: return all(avanode.poll_received > 0 for avanode in node.p2ps) self.wait_until(all_peers_received_poll) node.mockscheduler(AVALANCHE_STATISTICS_INTERVAL) requester = node.add_p2p_connection(AddrReceiver()) requester.send_message(msg_getavaaddr()) # Remember the time we sent the getavaaddr message getavaddr_time = mock_time # Spamming more get getavaaddr has no effect for _ in range(2): with node.assert_debug_log( ["Ignoring repeated getavaaddr from peer"], timeout=10 ): requester.send_message(msg_getavaaddr()) # Move the time so we get an addr response mock_time += MAX_ADDR_SEND_DELAY node.setmocktime(mock_time) requester.wait_until(requester.addr_received) # Check our message is now accepted again now that the getavaaddr # interval is elapsed assert mock_time >= getavaddr_time + GETAVAADDR_INTERVAL requester.send_message(msg_getavaaddr()) # We can get an addr message again mock_time += MAX_ADDR_SEND_DELAY node.setmocktime(mock_time) requester.wait_until(requester.addr_received) def address_test(self, maxaddrtosend, num_proof, num_avanode): self.restart_node( 0, extra_args=self.extra_args[0] + [f"-maxaddrtosend={maxaddrtosend}"] ) node = self.nodes[0] # Init mock time mock_time = int(time.time()) node.setmocktime(mock_time) # Create a bunch of proofs and associate each a bunch of nodes. avanodes = [] for _ in range(num_proof): master_privkey, proof = gen_proof(self, node) for n in range(num_avanode): avanode = AllYesAvaP2PInterface() if n % 2 else MutedAvaP2PInterface() avanode.master_privkey = master_privkey avanode.proof = proof node.add_p2p_connection(avanode) peerinfo = node.getpeerinfo()[-1] avanode.set_addr(peerinfo["addr"]) avanodes.append(avanode) responding_addresses = [ avanode.addr for avanode in avanodes if avanode.is_responding ] assert_equal(len(responding_addresses), num_proof * num_avanode // 2) # Check we have what we expect def all_nodes_connected(): avapeers = node.getavalanchepeerinfo() if len(avapeers) != num_proof: return False for avapeer in avapeers: if avapeer["nodecount"] != num_avanode: return False return True self.wait_until(all_nodes_connected) # Force the availability score to diverge between the responding and the # muted nodes. self.generate(node, 1, sync_fun=self.no_op) def poll_all_for_block(): with p2p_lock: return all( avanode.poll_received > (10 if avanode.is_responding else 0) for avanode in avanodes ) self.wait_until(poll_all_for_block) # Move the scheduler time 10 minutes forward so that so that our peers # get an availability score computed. node.mockscheduler(AVALANCHE_STATISTICS_INTERVAL) requester = node.add_p2p_connection(AddrReceiver()) requester.send_and_ping(msg_getavaaddr()) # Sanity check that the availability score is set up as expected peerinfo = node.getpeerinfo() muted_addresses = [ avanode.addr for avanode in avanodes if not avanode.is_responding ] assert all( p["availability_score"] < 0 for p in peerinfo if p["addr"] in muted_addresses ) assert all( p["availability_score"] > 0 for p in peerinfo if p["addr"] in responding_addresses ) # Requester has no availability_score because it's not an avalanche # peer assert "availability_score" not in peerinfo[-1].keys() mock_time += MAX_ADDR_SEND_DELAY node.setmocktime(mock_time) requester.wait_until(requester.addr_received) addresses = requester.get_received_addrs() assert_equal(len(addresses), min(maxaddrtosend, len(responding_addresses))) # Check all the addresses belong to responding peer assert all(address in responding_addresses for address in addresses) def getavaaddr_outbound_test(self): self.log.info( "Check we send a getavaaddr message to our avalanche outbound peers" ) node = self.nodes[0] # Get rid of previously connected nodes node.disconnect_p2ps() avapeers = [] for i in range(16): avapeer = AvaP2PInterface() node.add_outbound_p2p_connection( avapeer, p2p_idx=i, ) avapeers.append(avapeer) self.check_all_peers_received_getavaaddr_once(avapeers) # Generate some block to poll for self.generate(node, 1, sync_fun=self.no_op) # Because none of the avalanche peers is responding, our node should # fail out of option shortly and send a getavaaddr message to its # outbound avalanche peers. node.mockscheduler(MAX_GETAVAADDR_DELAY) def all_peers_received_getavaaddr(): with p2p_lock: return all(p.message_count.get("getavaaddr", 0) > 1 for p in avapeers) self.wait_until(all_peers_received_getavaaddr) def getavaaddr_manual_test(self): self.log.info( "Check we send a getavaaddr message to our manually connected peers that" " support avalanche" ) node = self.nodes[0] # Get rid of previously connected nodes node.disconnect_p2ps() def added_node_connected(ip_port): added_node_info = node.getaddednodeinfo(ip_port) return len(added_node_info) == 1 and added_node_info[0]["connected"] def connect_callback(address, port): self.log.debug(f"Connecting to {address}:{port}") p = AvaP2PInterface() p2p_idx = 1 p.peer_accept_connection( connect_cb=connect_callback, connect_id=p2p_idx, net=node.chain, timeout_factor=node.timeout_factor, )() ip_port = f"127.0.0.1:{p2p_port(MAX_NODES - p2p_idx)}" node.addnode(node=ip_port, command="add") self.wait_until(lambda: added_node_connected(ip_port)) assert_equal(node.getpeerinfo()[-1]["addr"], ip_port) assert_equal(node.getpeerinfo()[-1]["connection_type"], "manual") # Make sure p.is_connected is set, otherwise the last_message check # below will assert. p.wait_for_connect() p.wait_until(lambda: p.last_message.get("getavaaddr")) # Generate some block to poll for self.generate(node, 1, sync_fun=self.no_op) # Because our avalanche peer is not responding, our node should fail # out of option shortly and send another getavaaddr message. node.mockscheduler(MAX_GETAVAADDR_DELAY) p.wait_until(lambda: p.message_count.get("getavaaddr", 0) > 1) def getavaaddr_noquorum(self): self.log.info( "Check we send a getavaaddr message while our quorum is not established" ) node = self.nodes[0] self.restart_node( 0, extra_args=self.extra_args[0] + [ "-avaminquorumstake=500000000", "-avaminquorumconnectedstakeratio=0.8", ], ) avapeers = [] for i in range(16): avapeer = AllYesAvaP2PInterface(self, node) node.add_outbound_p2p_connection( avapeer, p2p_idx=i, connection_type="avalanche", services=NODE_NETWORK | NODE_AVALANCHE, ) avapeers.append(avapeer) peerinfo = node.getpeerinfo()[-1] avapeer.set_addr(peerinfo["addr"]) self.check_all_peers_received_getavaaddr_once(avapeers) def total_getavaaddr_msg(): with p2p_lock: return sum([p.message_count.get("getavaaddr", 0) for p in avapeers]) # Because we have not enough stake to start polling, we keep requesting # more addresses from all our peers total_getavaaddr = total_getavaaddr_msg() node.mockscheduler(MAX_GETAVAADDR_DELAY) self.wait_until( lambda: total_getavaaddr_msg() == total_getavaaddr + len(avapeers) ) # Move the schedulter time forward to make sure we get statistics # computed. But since we did not start polling yet it should remain all # zero. node.mockscheduler(AVALANCHE_STATISTICS_INTERVAL) def wait_for_availability_score(): peerinfo = node.getpeerinfo() return all( p.get("availability_score", None) == Decimal(0) for p in peerinfo ) self.wait_until(wait_for_availability_score) requester = node.add_p2p_connection(AddrReceiver()) requester.send_and_ping(msg_getavaaddr()) node.setmocktime(int(time.time() + MAX_ADDR_SEND_DELAY)) # Check all the peers addresses are returned. requester.wait_until(requester.addr_received) addresses = requester.get_received_addrs() assert_equal(len(addresses), len(avapeers)) expected_addresses = [avapeer.addr for avapeer in avapeers] assert all(address in expected_addresses for address in addresses) # Add more nodes so we reach the mininum quorum stake amount. for _ in range(4): avapeer = AllYesAvaP2PInterface(self, node) node.add_p2p_connection(avapeer) self.wait_until(lambda: node.getavalancheinfo()["ready_to_poll"] is True) def is_vote_finalized(proof): return node.getrawavalancheproof(uint256_hex(proof.proofid)).get( "finalized", False ) # Wait until all proofs are finalized self.wait_until( lambda: all( is_vote_finalized(p.proof) for p in node.p2ps if isinstance(p, AvaP2PInterface) ) ) # Go through several rounds of getavaaddr requests. We don't know for # sure how many will be sent as it depends on whether the peers # responded fast enough during the polling phase, but at some point a # single outbound peer will be requested and no more. def sent_single_getavaaddr(): total_getavaaddr = total_getavaaddr_msg() node.mockscheduler(MAX_GETAVAADDR_DELAY) self.wait_until(lambda: total_getavaaddr_msg() >= total_getavaaddr + 1) for p in avapeers: - p.sync_send_with_ping() + p.sync_with_ping() return total_getavaaddr_msg() == total_getavaaddr + 1 self.wait_until(sent_single_getavaaddr) def test_send_inbound_getavaaddr_until_quorum_is_established(self): self.log.info( "Check we also request the inbounds until the quorum is established" ) node = self.nodes[0] self.restart_node( 0, extra_args=self.extra_args[0] + ["-avaminquorumstake=1000000"] ) assert_equal(node.getavalancheinfo()["ready_to_poll"], False) outbound = MutedAvaP2PInterface() node.add_outbound_p2p_connection(outbound, p2p_idx=0) inbound = MutedAvaP2PInterface() node.add_p2p_connection(inbound) inbound.nodeid = node.getpeerinfo()[-1]["id"] def count_getavaaddr(peers): with p2p_lock: return sum([peer.message_count.get("getavaaddr", 0) for peer in peers]) # Upon connection only the outbound gets a getavaaddr message assert_equal(count_getavaaddr([inbound]), 0) self.wait_until(lambda: count_getavaaddr([outbound]) == 1) # Periodic send will include the inbound as well current_total = count_getavaaddr([inbound, outbound]) while count_getavaaddr([inbound]) == 0: node.mockscheduler(MAX_GETAVAADDR_DELAY) self.wait_until( lambda: count_getavaaddr([inbound, outbound]) > current_total ) current_total = count_getavaaddr([inbound, outbound]) # Connect the minimum amount of stake and nodes for _ in range(8): node.add_p2p_connection(AvaP2PInterface(self, node)) self.wait_until(lambda: node.getavalancheinfo()["ready_to_poll"] is True) # From now only the outbound is requested count_inbound = count_getavaaddr([inbound]) for _ in range(10): # Trigger a poll self.generate(node, 1, sync_fun=self.no_op) - inbound.sync_send_with_ping() + inbound.sync_with_ping() node.mockscheduler(MAX_GETAVAADDR_DELAY) self.wait_until( lambda: count_getavaaddr([inbound, outbound]) > current_total ) current_total = count_getavaaddr([inbound, outbound]) assert_equal(count_getavaaddr([inbound]), count_inbound) def test_addr_requests_order(self): node = self.nodes[0] # Get rid of previously connected nodes node.disconnect_p2ps() def check_addr_requests(p): p.wait_until(lambda: p.last_message.get("getavaaddr")) p.wait_until(lambda: p.message_count.get("getavaaddr", 0) == 1) p.wait_until(lambda: p.last_message.get("getaddr")) p.wait_until(lambda: p.message_count.get("getaddr", 0) == 1) # Test getaddr is sent first requester1 = node.add_outbound_p2p_connection(AvaHelloInterface(), p2p_idx=0) requester1.send_message(msg_getaddr()) requester1.send_message(msg_getavaaddr()) check_addr_requests(requester1) # Test getavaaddr is sent first requester2 = node.add_outbound_p2p_connection(AvaHelloInterface(), p2p_idx=1) requester2.send_message(msg_getavaaddr()) requester2.send_message(msg_getaddr()) check_addr_requests(requester2) def run_test(self): self.getavaaddr_interval_test() # Limited by maxaddrtosend self.address_test(maxaddrtosend=3, num_proof=2, num_avanode=8) # Limited by the number of good nodes self.address_test(maxaddrtosend=100, num_proof=2, num_avanode=8) self.getavaaddr_outbound_test() self.getavaaddr_manual_test() self.getavaaddr_noquorum() self.test_send_inbound_getavaaddr_until_quorum_is_established() self.test_addr_requests_order() if __name__ == "__main__": AvaAddrTest().main() diff --git a/test/functional/abc_p2p_proof_inventory.py b/test/functional/abc_p2p_proof_inventory.py index 042748083..dc9eebc06 100644 --- a/test/functional/abc_p2p_proof_inventory.py +++ b/test/functional/abc_p2p_proof_inventory.py @@ -1,382 +1,382 @@ # Copyright (c) 2021 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test proof inventory relaying """ import time from test_framework.address import ADDRESS_ECREG_UNSPENDABLE from test_framework.avatools import ( AvaP2PInterface, avalanche_proof_from_hex, gen_proof, get_proof_ids, wait_for_proof, ) from test_framework.messages import ( MSG_AVA_PROOF, MSG_TYPE_MASK, CInv, msg_avaproof, msg_getdata, ) from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_greater_than, assert_raises_rpc_error, uint256_hex, ) from test_framework.wallet_util import bytes_to_wif # Broadcast reattempt occurs every 10 to 15 minutes MAX_INITIAL_BROADCAST_DELAY = 15 * 60 # Delay to allow the node to respond to getdata requests UNCONDITIONAL_RELAY_DELAY = 2 * 60 class ProofInvStoreP2PInterface(P2PInterface): def __init__(self): super().__init__() self.proof_invs_counter = 0 self.last_proofid = None def on_inv(self, message): for i in message.inv: if i.type & MSG_TYPE_MASK == MSG_AVA_PROOF: self.proof_invs_counter += 1 self.last_proofid = i.hash class ProofInventoryTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 5 self.extra_args = [ [ "-avaproofstakeutxodustthreshold=1000000", "-avaproofstakeutxoconfirmations=2", "-avacooldown=0", "-whitelist=noban@127.0.0.1", "-persistavapeers=0", ] ] * self.num_nodes def generate_proof(self, node, mature=True): privkey, proof = gen_proof(self, node) if mature: self.generate(node, 1, sync_fun=self.no_op) return privkey, proof def test_send_proof_inv(self): self.log.info("Test sending a proof to our peers") node = self.nodes[0] for _ in range(10): node.add_p2p_connection(ProofInvStoreP2PInterface()) _, proof = self.generate_proof(node) assert node.sendavalancheproof(proof.serialize().hex()) def proof_inv_found(peer): with p2p_lock: return peer.last_proofid == proof.proofid self.wait_until(lambda: all(proof_inv_found(i) for i in node.p2ps)) self.log.info("Test that we don't send the same inv several times") extra_peer = ProofInvStoreP2PInterface() node.add_p2p_connection(extra_peer) # Send the same proof one more time node.sendavalancheproof(proof.serialize().hex()) # Our new extra peer should receive it but not the others self.wait_until(lambda: proof_inv_found(extra_peer)) assert all(p.proof_invs_counter == 1 for p in node.p2ps) # Send the proof again and force the send loop to be processed for peer in node.p2ps: node.sendavalancheproof(proof.serialize().hex()) peer.sync_with_ping() assert all(p.proof_invs_counter == 1 for p in node.p2ps) def test_receive_proof(self): self.log.info("Test a peer is created on proof reception") node = self.nodes[0] _, proof = self.generate_proof(node) peer = node.add_p2p_connection(P2PInterface()) msg = msg_avaproof() msg.proof = proof peer.send_message(msg) self.wait_until(lambda: proof.proofid in get_proof_ids(node)) self.log.info("Test receiving a proof with an immature utxo") _, immature = self.generate_proof(node, mature=False) immature_proofid = uint256_hex(immature.proofid) msg = msg_avaproof() msg.proof = immature peer.send_message(msg) wait_for_proof(node, immature_proofid, expect_status="immature") def test_ban_invalid_proof(self): node = self.nodes[0] _, bad_proof = self.generate_proof(node) bad_proof.stakes = [] privkey = node.get_deterministic_priv_key().key missing_stake = node.buildavalancheproof( 1, 0, privkey, [ { "txid": "0" * 64, "vout": 0, "amount": 10000000, "height": 42, "iscoinbase": False, "privatekey": privkey, } ], ) self.restart_node(0, ["-avaproofstakeutxodustthreshold=1000000"]) peer = node.add_p2p_connection(P2PInterface()) msg = msg_avaproof() # Sending a proof with a missing utxo doesn't trigger a ban msg.proof = avalanche_proof_from_hex(missing_stake) with node.assert_debug_log(["received: avaproof"], ["Misbehaving"]): peer.send_message(msg) peer.sync_with_ping() msg.proof = bad_proof with node.assert_debug_log( [ "Misbehaving", "invalid-proof", ] ): peer.send_message(msg) peer.wait_for_disconnect() def test_proof_relay(self): # This test makes no sense with less than 2 nodes ! assert_greater_than(self.num_nodes, 2) proofs_keys = [self.generate_proof(self.nodes[0]) for _ in self.nodes] proofids = {proof_key[1].proofid for proof_key in proofs_keys} # generate_proof does not sync, so do it manually self.sync_blocks() def restart_nodes_with_proof(nodes, extra_args=None): for node in nodes: privkey, proof = proofs_keys[node.index] self.restart_node( node.index, self.extra_args[node.index] + [ f"-avaproof={proof.serialize().hex()}", f"-avamasterkey={bytes_to_wif(privkey.get_bytes())}", ] + (extra_args or []), ) restart_nodes_with_proof(self.nodes[:-1]) chainwork = int(self.nodes[-1].getblockchaininfo()["chainwork"], 16) restart_nodes_with_proof( self.nodes[-1:], extra_args=[f"-minimumchainwork={chainwork + 100:#x}"] ) # Add an inbound so the node proof can be registered and advertised [node.add_p2p_connection(P2PInterface()) for node in self.nodes] [ [self.connect_nodes(node.index, j) for j in range(node.index)] for node in self.nodes ] # Connect a block to make the proofs added to our pool self.generate( self.nodes[0], 1, sync_fun=lambda: self.sync_blocks(self.nodes[:-1]) ) # Generate a different block on the IBD node, as it will not sync the low # work block while in IBD and it also needs a block to trigger its own proof # registration self.generate(self.nodes[-1], 1, sync_fun=self.no_op) self.log.info("Nodes should eventually get the proof from their peer") self.sync_proofs(self.nodes[:-1]) for node in self.nodes[:-1]: assert_equal(set(get_proof_ids(node)), proofids) assert self.nodes[-1].getblockchaininfo()["initialblockdownload"] self.log.info("Except the node that has not completed IBD") assert_equal(len(get_proof_ids(self.nodes[-1])), 1) # The same if we send a proof directly with no download request peer = AvaP2PInterface() self.nodes[-1].add_p2p_connection(peer) _, proof = self.generate_proof(self.nodes[0]) peer.send_avaproof(proof) - peer.sync_send_with_ping() + peer.sync_with_ping() with p2p_lock: assert_equal(peer.message_count.get("getdata", 0), 0) # Leave the nodes in good shape for the next tests restart_nodes_with_proof(self.nodes) [ [self.connect_nodes(node.index, j) for j in range(node.index)] for node in self.nodes ] def test_manually_sent_proof(self): node0 = self.nodes[0] _, proof = self.generate_proof(node0) self.log.info("Send a proof via RPC and check all the nodes download it") node0.sendavalancheproof(proof.serialize().hex()) self.sync_proofs() def test_unbroadcast(self): self.log.info("Test broadcasting proofs") node = self.nodes[0] # Disconnect the other nodes/peers, or they will request the proof and # invalidate the test [n.stop_node() for n in self.nodes[1:]] node.disconnect_p2ps() def add_peers(count): peers = [] for i in range(count): peer = node.add_p2p_connection(ProofInvStoreP2PInterface()) peer.wait_for_verack() peers.append(peer) return peers _, proof = self.generate_proof(node) proofid_hex = uint256_hex(proof.proofid) # Broadcast the proof peers = add_peers(3) assert node.sendavalancheproof(proof.serialize().hex()) wait_for_proof(node, proofid_hex) def proof_inv_received(peers): with p2p_lock: return all( p.last_message.get("inv") and p.last_message["inv"].inv[-1].hash == proof.proofid for p in peers ) self.wait_until(lambda: proof_inv_received(peers)) # If no peer request the proof for download, the node should reattempt # broadcasting to all new peers after 10 to 15 minutes. peers = add_peers(3) node.mockscheduler(MAX_INITIAL_BROADCAST_DELAY + 1) peers[-1].sync_with_ping() self.wait_until(lambda: proof_inv_received(peers)) # If at least one peer requests the proof, there is no more attempt to # broadcast it node.setmocktime(int(time.time()) + UNCONDITIONAL_RELAY_DELAY) msg = msg_getdata([CInv(t=MSG_AVA_PROOF, h=proof.proofid)]) peers[-1].send_message(msg) # Give enough time for the node to broadcast the proof again peers = add_peers(3) node.mockscheduler(MAX_INITIAL_BROADCAST_DELAY + 1) peers[-1].sync_with_ping() assert not proof_inv_received(peers) self.log.info("Proofs that become invalid should no longer be broadcasted") # Restart and add connect a new set of peers self.restart_node(0) # Broadcast the proof peers = add_peers(3) assert node.sendavalancheproof(proof.serialize().hex()) self.wait_until(lambda: proof_inv_received(peers)) # Sanity check our node knows the proof, and it is valid wait_for_proof(node, proofid_hex) # Mature the utxo then spend it self.generate(node, 100, sync_fun=self.no_op) utxo = proof.stakes[0].stake.utxo raw_tx = node.createrawtransaction( inputs=[ { # coinbase "txid": uint256_hex(utxo.txid), "vout": utxo.n, } ], outputs={ADDRESS_ECREG_UNSPENDABLE: 25_000_000 - 250.00}, ) signed_tx = node.signrawtransactionwithkey( hexstring=raw_tx, privkeys=[node.get_deterministic_priv_key().key], ) node.sendrawtransaction(signed_tx["hex"]) # Mine the tx in a block self.generate(node, 1, sync_fun=self.no_op) # Wait for the proof to be invalidated def check_proof_not_found(proofid): try: assert_raises_rpc_error( -8, "Proof not found", node.getrawavalancheproof, proofid ) return True except BaseException: return False self.wait_until(lambda: check_proof_not_found(proofid_hex)) # It should no longer be broadcasted peers = add_peers(3) node.mockscheduler(MAX_INITIAL_BROADCAST_DELAY + 1) peers[-1].sync_with_ping() assert not proof_inv_received(peers) def run_test(self): self.test_send_proof_inv() self.test_receive_proof() self.test_proof_relay() self.test_manually_sent_proof() # Run these tests last because they need to disconnect the nodes self.test_unbroadcast() self.test_ban_invalid_proof() if __name__ == "__main__": ProofInventoryTest().main() diff --git a/test/functional/p2p_addr_relay.py b/test/functional/p2p_addr_relay.py index a842c138d..85b5c9b59 100644 --- a/test/functional/p2p_addr_relay.py +++ b/test/functional/p2p_addr_relay.py @@ -1,528 +1,528 @@ # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test addr relay """ import random import time from test_framework.messages import ( NODE_NETWORK, CAddress, msg_addr, msg_getaddr, msg_verack, ) from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_greater_than, assert_greater_than_or_equal, ) ONE_MINUTE = 60 TEN_MINUTES = 10 * ONE_MINUTE ONE_HOUR = 60 * ONE_MINUTE TWO_HOURS = 2 * ONE_HOUR ONE_DAY = 24 * ONE_HOUR ADDR_DESTINATIONS_THRESHOLD = 4 class AddrReceiver(P2PInterface): num_ipv4_received = 0 test_addr_contents = False _tokens = 1 send_getaddr = True def __init__(self, test_addr_contents=False, send_getaddr=True): super().__init__() self.test_addr_contents = test_addr_contents self.send_getaddr = send_getaddr def on_addr(self, message): for addr in message.addrs: self.num_ipv4_received += 1 if self.test_addr_contents: # relay_tests checks the content of the addr messages match # expectations based on the message creation in setup_addr_msg assert_equal(addr.nServices, NODE_NETWORK) if not 8333 <= addr.port < 8343: raise AssertionError( f"Invalid addr.port of {addr.port} (8333-8342 expected)" ) assert addr.ip.startswith("123.123.123.") def on_getaddr(self, message): # When the node sends us a getaddr, it increments the addr relay tokens # for the connection by 1000 self._tokens += 1000 @property def tokens(self): with p2p_lock: return self._tokens def increment_tokens(self, n): # When we move mocktime forward, the node increments the addr relay # tokens for its peers with p2p_lock: self._tokens += n def addr_received(self): return self.num_ipv4_received != 0 def on_version(self, message): self.send_message(msg_verack()) if self.send_getaddr: self.send_message(msg_getaddr()) def getaddr_received(self): return self.message_count["getaddr"] > 0 class AddrTest(BitcoinTestFramework): counter = 0 mocktime = int(time.time()) def set_test_params(self): self.num_nodes = 1 self.extra_args = [["-whitelist=addr@127.0.0.1"]] def run_test(self): self.oversized_addr_test() self.relay_tests() self.inbound_blackhole_tests() self.destination_rotates_once_in_24_hours_test() self.destination_rotates_more_than_once_over_several_days_test() # This test populates the addrman, which can impact the node's behavior # in subsequent tests self.getaddr_tests() self.blocksonly_mode_tests() self.rate_limit_tests() def setup_addr_msg(self, num): addrs = [] for i in range(num): addr = CAddress() addr.time = self.mocktime + i addr.nServices = NODE_NETWORK addr.ip = f"123.123.123.{self.counter % 256}" addr.port = 8333 + i addrs.append(addr) self.counter += 1 msg = msg_addr() msg.addrs = addrs return msg def setup_rand_addr_msg(self, num): addrs = [] for i in range(num): addr = CAddress() addr.time = self.mocktime + i addr.nServices = NODE_NETWORK addr.ip = ( f"{random.randrange(128,169)}.{random.randrange(1,255)}" f".{random.randrange(1,255)}.{random.randrange(1,255)}" ) addr.port = 8333 addrs.append(addr) msg = msg_addr() msg.addrs = addrs return msg def send_addr_msg(self, source, msg, receivers): source.send_and_ping(msg) # pop m_next_addr_send timer self.mocktime += 10 * 60 self.nodes[0].setmocktime(self.mocktime) for peer in receivers: - peer.sync_send_with_ping() + peer.sync_with_ping() def oversized_addr_test(self): self.log.info("Send an addr message that is too large") addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = self.setup_addr_msg(1010) with self.nodes[0].assert_debug_log(["addr message size = 1010"]): addr_source.send_and_ping(msg) self.nodes[0].disconnect_p2ps() def relay_tests(self): self.log.info("Test address relay") self.log.info("Check that addr message content is relayed and added to addrman") addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) num_receivers = 7 receivers = [] for _ in range(num_receivers): receivers.append( self.nodes[0].add_p2p_connection(AddrReceiver(test_addr_contents=True)) ) # Keep this with length <= 10. Addresses from larger messages are not # relayed. num_ipv4_addrs = 10 msg = self.setup_addr_msg(num_ipv4_addrs) with self.nodes[0].assert_debug_log( [ "received: addr (301 bytes) peer=1", ] ): self.send_addr_msg(addr_source, msg, receivers) total_ipv4_received = sum(r.num_ipv4_received for r in receivers) # Every IPv4 address must be relayed to two peers, other than the # originating node (addr_source). ipv4_branching_factor = 2 assert_equal(total_ipv4_received, num_ipv4_addrs * ipv4_branching_factor) self.nodes[0].disconnect_p2ps() self.log.info("Check relay of addresses received from outbound peers") inbound_peer = self.nodes[0].add_p2p_connection( AddrReceiver(test_addr_contents=True, send_getaddr=False) ) full_outbound_peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay" ) msg = self.setup_addr_msg(2) self.send_addr_msg(full_outbound_peer, msg, [inbound_peer]) self.log.info( "Check that the first addr message received from an outbound peer is not" " relayed" ) # Currently, there is a flag that prevents the first addr message # received from a new outbound peer to be relayed to others. Originally # meant to prevent large GETADDR responses from being relayed, it now # typically affects the self-announcement of the outbound peer which is # often sent before the GETADDR response. assert_equal(inbound_peer.num_ipv4_received, 0) # Send an empty ADDR message to initialize address relay on this # connection. inbound_peer.send_and_ping(msg_addr()) self.log.info( "Check that subsequent addr messages sent from an outbound peer are relayed" ) msg2 = self.setup_addr_msg(2) self.send_addr_msg(full_outbound_peer, msg2, [inbound_peer]) assert_equal(inbound_peer.num_ipv4_received, 2) self.log.info("Check address relay to outbound peers") block_relay_peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=1, connection_type="block-relay-only" ) msg3 = self.setup_addr_msg(2) self.send_addr_msg(inbound_peer, msg3, [full_outbound_peer, block_relay_peer]) self.log.info("Check that addresses are relayed to full outbound peers") assert_equal(full_outbound_peer.num_ipv4_received, 2) self.log.info( "Check that addresses are not relayed to block-relay-only outbound peers" ) assert_equal(block_relay_peer.num_ipv4_received, 0) self.nodes[0].disconnect_p2ps() def sum_addr_messages(self, msgs_dict): return sum( bytes_received for (msg, bytes_received) in msgs_dict.items() if msg in ["addr", "addrv2", "getaddr"] ) def inbound_blackhole_tests(self): self.log.info( "Check that we only relay addresses to inbound peers who have previously" " sent us addr related messages" ) addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver()) blackhole_peer = self.nodes[0].add_p2p_connection( AddrReceiver(send_getaddr=False) ) initial_addrs_received = receiver_peer.num_ipv4_received peerinfo = self.nodes[0].getpeerinfo() assert_equal(peerinfo[0]["addr_relay_enabled"], True) # addr_source assert_equal(peerinfo[1]["addr_relay_enabled"], True) # receiver_peer assert_equal(peerinfo[2]["addr_relay_enabled"], False) # blackhole_peer # addr_source sends 2 addresses to node0 msg = self.setup_addr_msg(2) addr_source.send_and_ping(msg) self.mocktime += 30 * 60 self.nodes[0].setmocktime(self.mocktime) receiver_peer.sync_with_ping() blackhole_peer.sync_with_ping() peerinfo = self.nodes[0].getpeerinfo() # Confirm node received addr-related messages from receiver peer assert_greater_than(self.sum_addr_messages(peerinfo[1]["bytesrecv_per_msg"]), 0) # And that peer received addresses assert_equal(receiver_peer.num_ipv4_received - initial_addrs_received, 2) # Confirm node has not received addr-related messages from blackhole # peer assert_equal(self.sum_addr_messages(peerinfo[2]["bytesrecv_per_msg"]), 0) # And that peer did not receive addresses assert_equal(blackhole_peer.num_ipv4_received, 0) self.log.info( "After blackhole peer sends addr message, it becomes eligible for addr" " gossip" ) blackhole_peer.send_and_ping(msg_addr()) # Confirm node has now received addr-related messages from blackhole # peer assert_greater_than(self.sum_addr_messages(peerinfo[1]["bytesrecv_per_msg"]), 0) assert_equal(self.nodes[0].getpeerinfo()[2]["addr_relay_enabled"], True) msg = self.setup_addr_msg(2) self.send_addr_msg(addr_source, msg, [receiver_peer, blackhole_peer]) # And that peer received addresses assert_equal(blackhole_peer.num_ipv4_received, 2) self.nodes[0].disconnect_p2ps() def getaddr_tests(self): # In the previous tests, the node answered GETADDR requests with an # empty addrman. Due to GETADDR response caching (see # CConnman::GetAddresses), the node would continue to provide 0 addrs # in response until enough time has passed or the node is restarted. self.restart_node(0) self.log.info("Test getaddr behavior") self.log.info( "Check that we send a getaddr message upon connecting to an" " outbound-full-relay peer" ) full_outbound_peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay" ) full_outbound_peer.sync_with_ping() assert full_outbound_peer.getaddr_received() self.log.info( "Check that we do not send a getaddr message upon connecting to a" " block-relay-only peer" ) block_relay_peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=1, connection_type="block-relay-only" ) block_relay_peer.sync_with_ping() assert_equal(block_relay_peer.getaddr_received(), False) self.log.info("Check that we answer getaddr messages only from inbound peers") inbound_peer = self.nodes[0].add_p2p_connection( AddrReceiver(send_getaddr=False) ) inbound_peer.sync_with_ping() # Add some addresses to addrman for i in range(1000): first_octet = i >> 8 second_octet = i % 256 a = f"{first_octet}.{second_octet}.1.1" self.nodes[0].addpeeraddress(a, 8333) full_outbound_peer.send_and_ping(msg_getaddr()) block_relay_peer.send_and_ping(msg_getaddr()) inbound_peer.send_and_ping(msg_getaddr()) self.mocktime += 5 * 60 self.nodes[0].setmocktime(self.mocktime) inbound_peer.wait_until(lambda: inbound_peer.addr_received() is True) assert_equal(full_outbound_peer.num_ipv4_received, 0) assert_equal(block_relay_peer.num_ipv4_received, 0) assert inbound_peer.num_ipv4_received > 100 self.nodes[0].disconnect_p2ps() def blocksonly_mode_tests(self): self.log.info("Test addr relay in -blocksonly mode") self.restart_node(0, ["-blocksonly", "-whitelist=addr@127.0.0.1"]) self.mocktime = int(time.time()) self.log.info("Check that we send getaddr messages") full_outbound_peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay" ) full_outbound_peer.sync_with_ping() assert full_outbound_peer.getaddr_received() self.log.info("Check that we relay address messages") addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = self.setup_addr_msg(2) self.send_addr_msg(addr_source, msg, [full_outbound_peer]) assert_equal(full_outbound_peer.num_ipv4_received, 2) self.nodes[0].disconnect_p2ps() def send_addrs_and_test_rate_limiting( self, peer, no_relay, *, new_addrs, total_addrs ): """Send an addr message and check that the number of addresses processed and rate-limited is as expected """ peer.send_and_ping(self.setup_rand_addr_msg(new_addrs)) peerinfo = self.nodes[0].getpeerinfo()[0] addrs_processed = peerinfo["addr_processed"] addrs_rate_limited = peerinfo["addr_rate_limited"] self.log.debug( f"addrs_processed = {addrs_processed}, " f"addrs_rate_limited = {addrs_rate_limited}" ) if no_relay: assert_equal(addrs_processed, 0) assert_equal(addrs_rate_limited, 0) else: assert_equal(addrs_processed, min(total_addrs, peer.tokens)) assert_equal(addrs_rate_limited, max(0, total_addrs - peer.tokens)) def rate_limit_tests(self): self.mocktime = int(time.time()) self.restart_node(0, []) self.nodes[0].setmocktime(self.mocktime) for conn_type, no_relay in [ ("outbound-full-relay", False), ("block-relay-only", True), ("inbound", False), ]: self.log.info( f"Test rate limiting of addr processing for {conn_type} peers" ) if conn_type == "inbound": peer = self.nodes[0].add_p2p_connection(AddrReceiver()) else: peer = self.nodes[0].add_outbound_p2p_connection( AddrReceiver(), p2p_idx=0, connection_type=conn_type ) # Send 600 addresses. For all but the block-relay-only peer this # should result in addresses being processed. self.send_addrs_and_test_rate_limiting( peer, no_relay, new_addrs=600, total_addrs=600 ) # Send 600 more addresses. For the outbound-full-relay peer (which # we send a GETADDR, and thus will process up to 1001 incoming # addresses), this means more addresses will be processed. self.send_addrs_and_test_rate_limiting( peer, no_relay, new_addrs=600, total_addrs=1200 ) # Send 10 more. As we reached the processing limit for all nodes, # no more addresses should be procesesd. self.send_addrs_and_test_rate_limiting( peer, no_relay, new_addrs=10, total_addrs=1210 ) # Advance the time by 100 seconds, permitting the processing of 10 # more addresses. # Send 200 and verify that 10 are processed. self.mocktime += 100 self.nodes[0].setmocktime(self.mocktime) peer.increment_tokens(10) self.send_addrs_and_test_rate_limiting( peer, no_relay, new_addrs=200, total_addrs=1410 ) # Advance the time by 1000 seconds, permitting the processing of 100 # more addresses. # Send 200 and verify that 100 are processed. self.mocktime += 1000 self.nodes[0].setmocktime(self.mocktime) peer.increment_tokens(100) self.send_addrs_and_test_rate_limiting( peer, no_relay, new_addrs=200, total_addrs=1610 ) self.nodes[0].disconnect_p2ps() def get_nodes_that_received_addr( self, peer, receiver_peer, addr_receivers, time_interval_1, time_interval_2 ): # Clean addr response related to the initial getaddr. There is no way to avoid initial # getaddr because the peer won't self-announce then. for addr_receiver in addr_receivers: addr_receiver.num_ipv4_received = 0 for _ in range(10): self.mocktime += time_interval_1 self.msg.addrs[0].time = self.mocktime + TEN_MINUTES self.nodes[0].setmocktime(self.mocktime) with self.nodes[0].assert_debug_log(["received: addr (31 bytes) peer=0"]): peer.send_and_ping(self.msg) self.mocktime += time_interval_2 self.nodes[0].setmocktime(self.mocktime) receiver_peer.sync_with_ping() return [node for node in addr_receivers if node.addr_received()] def destination_rotates_once_in_24_hours_test(self): self.restart_node(0, []) self.log.info( "Test within 24 hours an addr relay destination is rotated at most once" ) self.mocktime = int(time.time()) self.msg = self.setup_addr_msg(1) self.addr_receivers = [] peer = self.nodes[0].add_p2p_connection(P2PInterface()) receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver()) addr_receivers = [ self.nodes[0].add_p2p_connection(AddrReceiver()) for _ in range(20) ] nodes_received_addr = self.get_nodes_that_received_addr( peer, receiver_peer, addr_receivers, 0, TWO_HOURS ) # 10 intervals of 2 hours # Per RelayAddress, we would announce these addrs to 2 destinations per day. # Since it's at most one rotation, at most 4 nodes can receive ADDR. assert_greater_than_or_equal( ADDR_DESTINATIONS_THRESHOLD, len(nodes_received_addr) ) self.nodes[0].disconnect_p2ps() def destination_rotates_more_than_once_over_several_days_test(self): self.restart_node(0, []) self.log.info( "Test after several days an addr relay destination is rotated more than once" ) self.msg = self.setup_addr_msg(1) peer = self.nodes[0].add_p2p_connection(P2PInterface()) receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver()) addr_receivers = [ self.nodes[0].add_p2p_connection(AddrReceiver()) for _ in range(20) ] # 10 intervals of 1 day (+ 1 hour, which should be enough to cover 30-min Poisson in most cases) nodes_received_addr = self.get_nodes_that_received_addr( peer, receiver_peer, addr_receivers, ONE_DAY, ONE_HOUR ) # Now that there should have been more than one rotation, more than # ADDR_DESTINATIONS_THRESHOLD nodes should have received ADDR. assert_greater_than(len(nodes_received_addr), ADDR_DESTINATIONS_THRESHOLD) self.nodes[0].disconnect_p2ps() if __name__ == "__main__": AddrTest().main() diff --git a/test/functional/p2p_addrfetch.py b/test/functional/p2p_addrfetch.py index 2f1c92d08..307e35c6a 100644 --- a/test/functional/p2p_addrfetch.py +++ b/test/functional/p2p_addrfetch.py @@ -1,90 +1,90 @@ # Copyright (c) 2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test p2p addr-fetch connections """ import time from test_framework.messages import NODE_NETWORK, CAddress, msg_addr from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal ADDR = CAddress() ADDR.time = int(time.time()) ADDR.nServices = NODE_NETWORK ADDR.ip = "192.0.0.8" ADDR.port = 18444 class P2PAddrFetch(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def assert_getpeerinfo(self, *, peer_ids): num_peers = len(peer_ids) info = self.nodes[0].getpeerinfo() assert_equal(len(info), num_peers) for n in range(0, num_peers): assert_equal(info[n]["id"], peer_ids[n]) assert_equal(info[n]["connection_type"], "addr-fetch") def run_test(self): node = self.nodes[0] self.log.info("Connect to an addr-fetch peer") peer_id = 0 peer = node.add_outbound_p2p_connection( P2PInterface(), p2p_idx=peer_id, connection_type="addr-fetch" ) self.assert_getpeerinfo(peer_ids=[peer_id]) self.log.info( "Check that we send getaddr but don't try to sync headers with the" " addr-fetch peer" ) - peer.sync_send_with_ping() + peer.sync_with_ping() with p2p_lock: assert peer.message_count["getaddr"] == 1 assert peer.message_count["getheaders"] == 0 self.log.info( "Check that answering the getaddr with a single address does not lead to" " disconnect" ) # This prevents disconnecting on self-announcements msg = msg_addr() msg.addrs = [ADDR] peer.send_and_ping(msg) self.assert_getpeerinfo(peer_ids=[peer_id]) self.log.info( "Check that answering with larger addr messages leads to disconnect" ) msg.addrs = [ADDR] * 2 peer.send_message(msg) peer.wait_for_disconnect(timeout=5) self.log.info("Check timeout for addr-fetch peer that does not send addrs") peer_id = 1 peer = node.add_outbound_p2p_connection( P2PInterface(), p2p_idx=peer_id, connection_type="addr-fetch" ) time_now = int(time.time()) self.assert_getpeerinfo(peer_ids=[peer_id]) # Expect addr-fetch peer connection to be maintained up to 5 minutes. node.setmocktime(time_now + 295) self.assert_getpeerinfo(peer_ids=[peer_id]) # Expect addr-fetch peer connection to be disconnected after 5 minutes. node.setmocktime(time_now + 301) peer.wait_for_disconnect(timeout=5) self.assert_getpeerinfo(peer_ids=[]) if __name__ == "__main__": P2PAddrFetch().main() diff --git a/test/functional/p2p_blocksonly.py b/test/functional/p2p_blocksonly.py index b0babc20f..aee868028 100644 --- a/test/functional/p2p_blocksonly.py +++ b/test/functional/p2p_blocksonly.py @@ -1,152 +1,152 @@ # Copyright (c) 2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test p2p blocksonly mode & block-relay-only connections.""" import time from test_framework.messages import MSG_TX, CInv, msg_inv, msg_tx from test_framework.p2p import P2PInterface, P2PTxInvStore from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal from test_framework.wallet import MiniWallet class P2PBlocksOnly(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [["-blocksonly"]] def run_test(self): self.miniwallet = MiniWallet(self.nodes[0]) # Add enough mature utxos to the wallet, so that all txs spend # confirmed coins self.miniwallet.rescan_utxos() self.blocksonly_mode_tests() self.blocks_relay_conn_tests() def blocksonly_mode_tests(self): self.log.info("Tests with node running in -blocksonly mode") assert_equal(self.nodes[0].getnetworkinfo()["localrelay"], False) self.nodes[0].add_p2p_connection(P2PInterface()) tx, txid, tx_hex = self.check_p2p_tx_violation() self.log.info("Check that tx invs also violate the protocol") self.nodes[0].add_p2p_connection(P2PInterface()) with self.nodes[0].assert_debug_log( [ "transaction" " (0000000000000000000000000000000000000000000000000000000000001234)" " inv sent in violation of protocol, disconnecting peer" ] ): self.nodes[0].p2ps[0].send_message(msg_inv([CInv(t=MSG_TX, h=0x1234)])) self.nodes[0].p2ps[0].wait_for_disconnect() del self.nodes[0].p2ps[0] self.log.info( "Check that txs from rpc are not rejected and relayed to other peers" ) tx_relay_peer = self.nodes[0].add_p2p_connection(P2PInterface()) assert_equal(self.nodes[0].getpeerinfo()[0]["relaytxes"], True) assert_equal(self.nodes[0].testmempoolaccept([tx_hex])[0]["allowed"], True) with self.nodes[0].assert_debug_log([f"received getdata for: tx {txid} peer"]): self.nodes[0].sendrawtransaction(tx_hex) tx_relay_peer.wait_for_tx(txid) assert_equal(self.nodes[0].getmempoolinfo()["size"], 1) self.log.info("Restarting node 0 with relay permission and blocksonly") self.restart_node( 0, [ "-persistmempool=0", "-whitelist=relay@127.0.0.1", "-blocksonly", ], ) assert_equal(self.nodes[0].getrawmempool(), []) first_peer = self.nodes[0].add_p2p_connection(P2PInterface()) second_peer = self.nodes[0].add_p2p_connection(P2PInterface()) peer_1_info = self.nodes[0].getpeerinfo()[0] assert_equal(peer_1_info["permissions"], ["relay"]) peer_2_info = self.nodes[0].getpeerinfo()[1] assert_equal(peer_2_info["permissions"], ["relay"]) assert_equal(self.nodes[0].testmempoolaccept([tx_hex])[0]["allowed"], True) self.log.info( "Check that the tx from first_peer with relay-permission is " "relayed to others (ie.second_peer)" ) with self.nodes[0].assert_debug_log(["received getdata"]): # Note that normally, first_peer would never send us transactions # since we're a blocksonly node. By activating blocksonly, we # explicitly tell our peers that they should not send us # transactions, and Bitcoin ABC respects that choice and will not # send transactions. # But if, for some reason, first_peer decides to relay transactions # to us anyway, we should relay them to second_peer since we gave # relay permission to first_peer. # See https://github.com/bitcoin/bitcoin/issues/19943 for details. first_peer.send_message(msg_tx(tx)) self.log.info( "Check that the peer with relay-permission is still connected" " after sending the transaction" ) assert_equal(first_peer.is_connected, True) second_peer.wait_for_tx(txid) assert_equal(self.nodes[0].getmempoolinfo()["size"], 1) self.log.info("Relay-permission peer's transaction is accepted and relayed") self.nodes[0].disconnect_p2ps() self.generate(self.nodes[0], 1) def blocks_relay_conn_tests(self): self.log.info( "Tests with node in normal mode with block-relay-only connections" ) # disables blocks only mode self.restart_node(0, ["-noblocksonly"]) assert_equal(self.nodes[0].getnetworkinfo()["localrelay"], True) # Ensure we disconnect if a block-relay-only connection sends us a # transaction self.nodes[0].add_outbound_p2p_connection( P2PInterface(), p2p_idx=0, connection_type="block-relay-only" ) assert_equal(self.nodes[0].getpeerinfo()[0]["relaytxes"], False) _, txid, tx_hex = self.check_p2p_tx_violation() self.log.info("Check that txs from RPC are not sent to blockrelay connection") conn = self.nodes[0].add_outbound_p2p_connection( P2PTxInvStore(), p2p_idx=1, connection_type="block-relay-only" ) self.nodes[0].sendrawtransaction(tx_hex) # Bump time forward to ensure m_next_inv_send_time timer pops self.nodes[0].setmocktime(int(time.time()) + 60) - conn.sync_send_with_ping() + conn.sync_with_ping() assert int(txid, 16) not in conn.get_invs() def check_p2p_tx_violation(self): self.log.info("Check that txs from P2P are rejected and result in disconnect") spendtx = self.miniwallet.create_self_transfer(from_node=self.nodes[0]) with self.nodes[0].assert_debug_log( ["transaction sent in violation of protocol peer=0"] ): self.nodes[0].p2ps[0].send_message(msg_tx(spendtx["tx"])) self.nodes[0].p2ps[0].wait_for_disconnect() assert_equal(self.nodes[0].getmempoolinfo()["size"], 0) # Remove the disconnected peer del self.nodes[0].p2ps[0] return spendtx["tx"], spendtx["txid"], spendtx["hex"] if __name__ == "__main__": P2PBlocksOnly().main() diff --git a/test/functional/p2p_compactblocks_blocksonly.py b/test/functional/p2p_compactblocks_blocksonly.py index 6c8934d4a..bace0789b 100644 --- a/test/functional/p2p_compactblocks_blocksonly.py +++ b/test/functional/p2p_compactblocks_blocksonly.py @@ -1,153 +1,153 @@ # Copyright (c) 2021-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test that a node in blocksonly mode does not request compact blocks.""" from test_framework.messages import ( MSG_BLOCK, MSG_CMPCT_BLOCK, CBlock, CBlockHeader, CInv, FromHex, msg_block, msg_getdata, msg_headers, msg_sendcmpct, ) from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class P2PCompactBlocksBlocksOnly(BitcoinTestFramework): def set_test_params(self): self.extra_args = [["-blocksonly"], [], [], []] self.num_nodes = 4 def setup_network(self): self.setup_nodes() # Start network with everyone disconnected self.sync_all() def build_block_on_tip(self): blockhash = self.generate(self.nodes[2], 1, sync_fun=self.no_op)[0] block_hex = self.nodes[2].getblock(blockhash=blockhash, verbosity=0) block = FromHex(CBlock(), block_hex) block.rehash() return block def run_test(self): # Nodes will only request hb compact blocks mode when they're out of IBD for node in self.nodes: assert not node.getblockchaininfo()["initialblockdownload"] p2p_conn_blocksonly = self.nodes[0].add_p2p_connection(P2PInterface()) p2p_conn_high_bw = self.nodes[1].add_p2p_connection(P2PInterface()) p2p_conn_low_bw = self.nodes[3].add_p2p_connection(P2PInterface()) for conn in [p2p_conn_blocksonly, p2p_conn_high_bw, p2p_conn_low_bw]: assert_equal(conn.message_count["sendcmpct"], 1) conn.send_and_ping(msg_sendcmpct(announce=False, version=1)) # Nodes: # 0 -> blocksonly # 1 -> high bandwidth # 2 -> miner # 3 -> low bandwidth # # Topology: # p2p_conn_blocksonly ---> node0 # p2p_conn_high_bw ---> node1 # p2p_conn_low_bw ---> node3 # node2 (no connections) # # node2 produces blocks that are passed to the rest of the nodes # through the respective p2p connections. self.log.info( "Test that -blocksonly nodes do not select peers for BIP152 high bandwidth mode" ) block0 = self.build_block_on_tip() # A -blocksonly node should not request BIP152 high bandwidth mode upon # receiving a new valid block at the tip. p2p_conn_blocksonly.send_and_ping(msg_block(block0)) assert_equal(int(self.nodes[0].getbestblockhash(), 16), block0.sha256) assert_equal(p2p_conn_blocksonly.message_count["sendcmpct"], 1) assert_equal(p2p_conn_blocksonly.last_message["sendcmpct"].announce, False) # A normal node participating in transaction relay should request BIP152 # high bandwidth mode upon receiving a new valid block at the tip. p2p_conn_high_bw.send_and_ping(msg_block(block0)) assert_equal(int(self.nodes[1].getbestblockhash(), 16), block0.sha256) p2p_conn_high_bw.wait_until( lambda: p2p_conn_high_bw.message_count["sendcmpct"] == 2 ) assert_equal(p2p_conn_high_bw.last_message["sendcmpct"].announce, True) # Don't send a block from the p2p_conn_low_bw so the low bandwidth node # doesn't select it for BIP152 high bandwidth relay. self.nodes[3].submitblock(block0.serialize().hex()) self.log.info( "Test that -blocksonly nodes send getdata(BLOCK) instead" " of getdata(CMPCT) in BIP152 low bandwidth mode" ) block1 = self.build_block_on_tip() p2p_conn_blocksonly.send_message(msg_headers(headers=[CBlockHeader(block1)])) - p2p_conn_blocksonly.sync_send_with_ping() + p2p_conn_blocksonly.sync_with_ping() assert_equal( p2p_conn_blocksonly.last_message["getdata"].inv, [CInv(MSG_BLOCK, block1.sha256)], ) p2p_conn_high_bw.send_message(msg_headers(headers=[CBlockHeader(block1)])) - p2p_conn_high_bw.sync_send_with_ping() + p2p_conn_high_bw.sync_with_ping() assert_equal( p2p_conn_high_bw.last_message["getdata"].inv, [CInv(MSG_CMPCT_BLOCK, block1.sha256)], ) self.log.info( "Test that getdata(CMPCT) is still sent on BIP152 low bandwidth connections" " when no -blocksonly nodes are involved" ) p2p_conn_low_bw.send_and_ping(msg_headers(headers=[CBlockHeader(block1)])) p2p_conn_low_bw.sync_with_ping() assert_equal( p2p_conn_low_bw.last_message["getdata"].inv, [CInv(MSG_CMPCT_BLOCK, block1.sha256)], ) self.log.info("Test that -blocksonly nodes still serve compact blocks") def test_for_cmpctblock(block): if "cmpctblock" not in p2p_conn_blocksonly.last_message: return False return ( p2p_conn_blocksonly.last_message[ "cmpctblock" ].header_and_shortids.header.rehash() == block.sha256 ) p2p_conn_blocksonly.send_message( msg_getdata([CInv(MSG_CMPCT_BLOCK, block0.sha256)]) ) p2p_conn_blocksonly.wait_until(lambda: test_for_cmpctblock(block0)) # Request BIP152 high bandwidth mode from the -blocksonly node. p2p_conn_blocksonly.send_and_ping(msg_sendcmpct(announce=True, version=1)) block2 = self.build_block_on_tip() self.nodes[0].submitblock(block1.serialize().hex()) self.nodes[0].submitblock(block2.serialize().hex()) p2p_conn_blocksonly.wait_until(lambda: test_for_cmpctblock(block2)) if __name__ == "__main__": P2PCompactBlocksBlocksOnly().main() diff --git a/test/functional/p2p_filter.py b/test/functional/p2p_filter.py index 3b705c35f..13e3c6a41 100644 --- a/test/functional/p2p_filter.py +++ b/test/functional/p2p_filter.py @@ -1,315 +1,315 @@ # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test BIP 37 """ from test_framework.messages import ( COIN, MAX_BLOOM_FILTER_SIZE, MAX_BLOOM_HASH_FUNCS, MSG_BLOCK, MSG_FILTERED_BLOCK, CInv, msg_filteradd, msg_filterclear, msg_filterload, msg_getdata, msg_mempool, msg_version, ) from test_framework.p2p import ( P2P_SERVICES, P2P_SUBVERSION, P2P_VERSION, P2PInterface, p2p_lock, ) from test_framework.script import MAX_SCRIPT_ELEMENT_SIZE from test_framework.test_framework import BitcoinTestFramework from test_framework.wallet import MiniWallet, getnewdestination class P2PBloomFilter(P2PInterface): # This is a P2SH watch-only wallet watch_script_pubkey = bytes.fromhex( "a914ffffffffffffffffffffffffffffffffffffffff87" ) # The initial filter (n=10, fp=0.000001) with just the above scriptPubKey # added watch_filter_init = msg_filterload( data=( b"@\x00\x08\x00\x80\x00\x00 \x00\xc0\x00 \x04\x00\x08$\x00\x04\x80\x00\x00" b" \x00\x00\x00\x00\x80\x00\x00@\x00\x02@ \x00" ), nHashFuncs=19, nTweak=0, nFlags=1, ) def __init__(self): super().__init__() self._tx_received = False self._merkleblock_received = False def on_inv(self, message): want = msg_getdata() for i in message.inv: # inv messages can only contain TX or BLOCK, so translate BLOCK to # FILTERED_BLOCK if i.type == MSG_BLOCK: want.inv.append(CInv(MSG_FILTERED_BLOCK, i.hash)) else: want.inv.append(i) if len(want.inv): self.send_message(want) def on_merkleblock(self, message): self._merkleblock_received = True def on_tx(self, message): self._tx_received = True @property def tx_received(self): with p2p_lock: return self._tx_received @tx_received.setter def tx_received(self, value): with p2p_lock: self._tx_received = value @property def merkleblock_received(self): with p2p_lock: return self._merkleblock_received @merkleblock_received.setter def merkleblock_received(self, value): with p2p_lock: self._merkleblock_received = value class FilterTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [ [ "-peerbloomfilters", "-whitelist=noban@127.0.0.1", # immediate tx relay ] ] def generatetoscriptpubkey(self, scriptpubkey): """Helper to generate a single block to the given scriptPubKey.""" return self.generatetodescriptor( self.nodes[0], 1, f"raw({scriptpubkey.hex()})" )[0] def test_size_limits(self, filter_peer): self.log.info("Check that too large filter is rejected") with self.nodes[0].assert_debug_log(["Misbehaving"]): filter_peer.send_and_ping( msg_filterload(data=b"\xbb" * (MAX_BLOOM_FILTER_SIZE + 1)) ) self.log.info("Check that max size filter is accepted") with self.nodes[0].assert_debug_log([""], unexpected_msgs=["Misbehaving"]): filter_peer.send_and_ping( msg_filterload(data=b"\xbb" * (MAX_BLOOM_FILTER_SIZE)) ) filter_peer.send_and_ping(msg_filterclear()) self.log.info("Check that filter with too many hash functions is rejected") with self.nodes[0].assert_debug_log(["Misbehaving"]): filter_peer.send_and_ping( msg_filterload(data=b"\xaa", nHashFuncs=MAX_BLOOM_HASH_FUNCS + 1) ) self.log.info("Check that filter with max hash functions is accepted") with self.nodes[0].assert_debug_log([""], unexpected_msgs=["Misbehaving"]): filter_peer.send_and_ping( msg_filterload(data=b"\xaa", nHashFuncs=MAX_BLOOM_HASH_FUNCS) ) # Don't send filterclear until next two filteradd checks are done self.log.info( "Check that max size data element to add to the filter is accepted" ) with self.nodes[0].assert_debug_log([""], unexpected_msgs=["Misbehaving"]): filter_peer.send_and_ping( msg_filteradd(data=b"\xcc" * (MAX_SCRIPT_ELEMENT_SIZE)) ) self.log.info( "Check that too large data element to add to the filter is rejected" ) with self.nodes[0].assert_debug_log(["Misbehaving"]): filter_peer.send_and_ping( msg_filteradd(data=b"\xcc" * (MAX_SCRIPT_ELEMENT_SIZE + 1)) ) filter_peer.send_and_ping(msg_filterclear()) def test_msg_mempool(self): self.log.info( "Check that a node with bloom filters enabled services p2p mempool messages" ) filter_peer = P2PBloomFilter() self.log.debug("Create a tx relevant to the peer before connecting") txid, _ = self.wallet.send_to( from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN, ) self.log.debug( "Send a mempool msg after connecting and check that the tx is received" ) self.nodes[0].add_p2p_connection(filter_peer) filter_peer.send_and_ping(filter_peer.watch_filter_init) filter_peer.send_message(msg_mempool()) filter_peer.wait_for_tx(txid) def test_frelay_false(self, filter_peer): self.log.info( "Check that a node with fRelay set to false does not receive invs until the" " filter is set" ) filter_peer.tx_received = False self.wallet.send_to( from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN, ) # Sync to make sure the reason filter_peer doesn't receive the tx is # not p2p delays filter_peer.sync_with_ping() assert not filter_peer.tx_received # Clear the mempool so that this transaction does not impact subsequent # tests self.generate(self.nodes[0], 1) def test_filter(self, filter_peer): # Set the bloomfilter using filterload filter_peer.send_and_ping(filter_peer.watch_filter_init) # If fRelay is not already True, sending filterload sets it to True assert self.nodes[0].getpeerinfo()[0]["relaytxes"] self.log.info( "Check that we receive merkleblock and tx if the filter matches a tx in a" " block" ) block_hash = self.generatetoscriptpubkey(filter_peer.watch_script_pubkey) txid = self.nodes[0].getblock(block_hash)["tx"][0] filter_peer.wait_for_merkleblock(block_hash) filter_peer.wait_for_tx(txid) self.log.info( "Check that we only receive a merkleblock if the filter does not match a tx" " in a block" ) filter_peer.tx_received = False block_hash = self.generatetoscriptpubkey(getnewdestination()[1]) filter_peer.wait_for_merkleblock(block_hash) assert not filter_peer.tx_received self.log.info( "Check that we not receive a tx if the filter does not match a mempool tx" ) filter_peer.merkleblock_received = False filter_peer.tx_received = False self.wallet.send_to( from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=7 * COIN, ) - filter_peer.sync_send_with_ping() + filter_peer.sync_with_ping() assert not filter_peer.merkleblock_received assert not filter_peer.tx_received self.log.info("Check that we receive a tx if the filter matches a mempool tx") filter_peer.merkleblock_received = False txid, _ = self.wallet.send_to( from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN, ) filter_peer.wait_for_tx(txid) assert not filter_peer.merkleblock_received self.log.info("Check that after deleting filter all txs get relayed again") filter_peer.send_and_ping(msg_filterclear()) for _ in range(5): txid, _ = self.wallet.send_to( from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=7 * COIN, ) filter_peer.wait_for_tx(txid) self.log.info( "Check that request for filtered blocks is ignored if no filter is set" ) filter_peer.merkleblock_received = False filter_peer.tx_received = False with self.nodes[0].assert_debug_log(expected_msgs=["received getdata"]): block_hash = self.generatetoscriptpubkey(getnewdestination()[1]) filter_peer.wait_for_inv([CInv(MSG_BLOCK, int(block_hash, 16))]) filter_peer.sync_with_ping() assert not filter_peer.merkleblock_received assert not filter_peer.tx_received self.log.info( 'Check that sending "filteradd" if no filter is set is treated as ' "misbehavior" ) with self.nodes[0].assert_debug_log(["Misbehaving"]): filter_peer.send_and_ping(msg_filteradd(data=b"letsmisbehave")) self.log.info( "Check that division-by-zero remote crash bug [CVE-2013-5700] is fixed" ) filter_peer.send_and_ping(msg_filterload(data=b"", nHashFuncs=1)) filter_peer.send_and_ping(msg_filteradd(data=b"letstrytocrashthisnode")) self.nodes[0].disconnect_p2ps() def run_test(self): self.wallet = MiniWallet(self.nodes[0]) self.wallet.rescan_utxos() filter_peer = self.nodes[0].add_p2p_connection(P2PBloomFilter()) self.log.info("Test filter size limits") self.test_size_limits(filter_peer) self.log.info("Test BIP 37 for a node with fRelay = True (default)") self.test_filter(filter_peer) self.nodes[0].disconnect_p2ps() self.log.info("Test BIP 37 for a node with fRelay = False") # Add peer but do not send version yet filter_peer_without_nrelay = self.nodes[0].add_p2p_connection( P2PBloomFilter(), send_version=False, wait_for_verack=False ) # Send version with relay=False version_without_fRelay = msg_version() version_without_fRelay.nVersion = P2P_VERSION version_without_fRelay.strSubVer = P2P_SUBVERSION version_without_fRelay.nServices = P2P_SERVICES version_without_fRelay.relay = 0 filter_peer_without_nrelay.send_message(version_without_fRelay) filter_peer_without_nrelay.wait_for_verack() assert not self.nodes[0].getpeerinfo()[0]["relaytxes"] self.test_frelay_false(filter_peer_without_nrelay) self.test_filter(filter_peer_without_nrelay) self.test_msg_mempool() if __name__ == "__main__": FilterTest().main() diff --git a/test/functional/p2p_ibd_stalling.py b/test/functional/p2p_ibd_stalling.py index 255bc375f..37af0944a 100644 --- a/test/functional/p2p_ibd_stalling.py +++ b/test/functional/p2p_ibd_stalling.py @@ -1,179 +1,179 @@ # Copyright (c) 2022- The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test stalling logic during IBD """ import time from test_framework.blocktools import create_block, create_coinbase from test_framework.messages import ( MSG_BLOCK, MSG_TYPE_MASK, CBlockHeader, msg_block, msg_headers, ) from test_framework.p2p import P2PDataStore from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class P2PStaller(P2PDataStore): def __init__(self, stall_block): self.stall_block = stall_block super().__init__() def on_getdata(self, message): for inv in message.inv: self.getdata_requests.append(inv.hash) if (inv.type & MSG_TYPE_MASK) == MSG_BLOCK: if inv.hash != self.stall_block: self.send_message(msg_block(self.block_store[inv.hash])) def on_getheaders(self, message): pass class P2PIBDStallingTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): NUM_BLOCKS = 1025 NUM_PEERS = 4 node = self.nodes[0] tip = int(node.getbestblockhash(), 16) blocks = [] height = 1 block_time = node.getblock(node.getbestblockhash())["time"] + 1 self.log.info("Prepare blocks without sending them to the node") block_dict = {} for _ in range(NUM_BLOCKS): blocks.append( create_block(tip, create_coinbase(height), block_time, version=4) ) blocks[-1].solve() tip = blocks[-1].sha256 block_time += 1 height += 1 block_dict[blocks[-1].sha256] = blocks[-1] stall_block = blocks[0].sha256 headers_message = msg_headers() headers_message.headers = [CBlockHeader(b) for b in blocks[: NUM_BLOCKS - 1]] peers = [] self.log.info( "Check that a staller does not get disconnected if the 1024 block lookahead buffer is filled" ) for id_ in range(NUM_PEERS): peers.append( node.add_outbound_p2p_connection( P2PStaller(stall_block), p2p_idx=id_, connection_type="outbound-full-relay", ) ) peers[-1].block_store = block_dict peers[-1].send_message(headers_message) # Need to wait until 1023 blocks are received - the magic total bytes number is # a workaround in lack of an rpc returning the number of downloaded (but not # connected) blocks. 205 bytes x 1023 blocks self.wait_until(lambda: self.total_bytes_recv_for_blocks() == 209715) self.all_sync_send_with_ping(peers) # If there was a peer marked for stalling, it would get disconnected self.mocktime = int(time.time()) + 3 node.setmocktime(self.mocktime) self.all_sync_send_with_ping(peers) assert_equal(node.num_test_p2p_connections(), NUM_PEERS) self.log.info( "Check that increasing the window beyond 1024 blocks triggers stalling logic" ) headers_message.headers = [CBlockHeader(b) for b in blocks] with node.assert_debug_log(expected_msgs=["Stall started"]): for p in peers: p.send_message(headers_message) self.all_sync_send_with_ping(peers) self.log.info("Check that the stalling peer is disconnected after 2 seconds") self.mocktime += 3 node.setmocktime(self.mocktime) peers[0].wait_for_disconnect() assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 1) self.wait_until(lambda: self.is_block_requested(peers, stall_block)) # Make sure that SendMessages() is invoked, which assigns the missing block # to another peer and starts the stalling logic for them self.all_sync_send_with_ping(peers) self.log.info( "Check that the stalling timeout gets doubled to 4 seconds for the next staller" ) # No disconnect after just 3 seconds self.mocktime += 3 node.setmocktime(self.mocktime) self.all_sync_send_with_ping(peers) assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 1) self.mocktime += 2 node.setmocktime(self.mocktime) self.wait_until(lambda: sum(x.is_connected for x in node.p2ps) == NUM_PEERS - 2) self.wait_until(lambda: self.is_block_requested(peers, stall_block)) self.all_sync_send_with_ping(peers) self.log.info( "Check that the stalling timeout gets doubled to 8 seconds for the next staller" ) # No disconnect after just 7 seconds self.mocktime += 7 node.setmocktime(self.mocktime) self.all_sync_send_with_ping(peers) assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 2) self.mocktime += 2 node.setmocktime(self.mocktime) self.wait_until(lambda: sum(x.is_connected for x in node.p2ps) == NUM_PEERS - 3) self.wait_until(lambda: self.is_block_requested(peers, stall_block)) self.all_sync_send_with_ping(peers) self.log.info( "Provide the withheld block and check that stalling timeout gets reduced back to 2 seconds" ) with node.assert_debug_log( expected_msgs=["Decreased stalling timeout to 2 seconds"] ): for p in peers: if p.is_connected and (stall_block in p.getdata_requests): p.send_message(msg_block(block_dict[stall_block])) self.log.info("Check that all outstanding blocks get connected") self.wait_until(lambda: node.getblockcount() == NUM_BLOCKS) def total_bytes_recv_for_blocks(self): total = 0 for info in self.nodes[0].getpeerinfo(): if "block" in info["bytesrecv_per_msg"].keys(): total += info["bytesrecv_per_msg"]["block"] return total @staticmethod def all_sync_send_with_ping(peers): for p in peers: if p.is_connected: - p.sync_send_with_ping() + p.sync_with_ping() @staticmethod def is_block_requested(peers, hash_): for p in peers: if p.is_connected and (hash_ in p.getdata_requests): return True return False if __name__ == "__main__": P2PIBDStallingTest().main() diff --git a/test/functional/test_framework/p2p.py b/test/functional/test_framework/p2p.py index eaf43542e..d19e6a780 100644 --- a/test/functional/test_framework/p2p.py +++ b/test/functional/test_framework/p2p.py @@ -1,979 +1,975 @@ # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test objects for interacting with a bitcoind node over the p2p protocol. The P2PInterface objects interact with the bitcoind nodes under test using the node's p2p interface. They can be used to send messages to the node, and callbacks can be registered that execute when messages are received from the node. Messages are sent to/received from the node on an asyncio event loop. State held inside the objects must be guarded by the p2p_lock to avoid data races between the main testing thread and the event loop. P2PConnection: A low-level connection object to a node's P2P interface P2PInterface: A high-level interface object for communicating to a node over P2P P2PDataStore: A p2p interface class that keeps a store of transactions and blocks and can respond correctly to getdata and getheaders messages P2PTxInvStore: A p2p interface class that inherits from P2PDataStore, and keeps a count of how many times each txid has been announced.""" import asyncio import logging import struct import sys import threading from collections import defaultdict from io import BytesIO from test_framework.messages import ( MAX_HEADERS_RESULTS, MSG_BLOCK, MSG_TX, MSG_TYPE_MASK, NODE_NETWORK, CBlockHeader, msg_addr, msg_addrv2, msg_avahello, msg_avapoll, msg_avaproof, msg_avaproofs, msg_avaproofsreq, msg_block, msg_blocktxn, msg_cfcheckpt, msg_cfheaders, msg_cfilter, msg_cmpctblock, msg_feefilter, msg_filteradd, msg_filterclear, msg_filterload, msg_getaddr, msg_getavaaddr, msg_getavaproofs, msg_getblocks, msg_getblocktxn, msg_getdata, msg_getheaders, msg_headers, msg_inv, msg_mempool, msg_merkleblock, msg_notfound, msg_ping, msg_pong, msg_sendaddrv2, msg_sendcmpct, msg_sendheaders, msg_tcpavaresponse, msg_tx, msg_verack, msg_version, sha256, ) from test_framework.util import MAX_NODES, p2p_port, wait_until_helper logger = logging.getLogger("TestFramework.p2p") # The minimum P2P version that this test framework supports MIN_P2P_VERSION_SUPPORTED = 60001 # The P2P version that this test framework implements and sends in its `version` # message. Past bip-31 for ping/pong P2P_VERSION = 70014 # The services that this test framework offers in its `version` message P2P_SERVICES = NODE_NETWORK # The P2P user agent string that this test framework sends in its `version` # message P2P_SUBVERSION = "/python-p2p-tester:0.0.3/" # Value for relay that this test framework sends in its `version` message P2P_VERSION_RELAY = 1 MESSAGEMAP = { b"addr": msg_addr, b"addrv2": msg_addrv2, b"avapoll": msg_avapoll, b"avaproof": msg_avaproof, b"avaproofs": msg_avaproofs, b"avaproofsreq": msg_avaproofsreq, b"avaresponse": msg_tcpavaresponse, b"avahello": msg_avahello, b"block": msg_block, b"blocktxn": msg_blocktxn, b"cfcheckpt": msg_cfcheckpt, b"cfheaders": msg_cfheaders, b"cfilter": msg_cfilter, b"cmpctblock": msg_cmpctblock, b"feefilter": msg_feefilter, b"filteradd": msg_filteradd, b"filterclear": msg_filterclear, b"filterload": msg_filterload, b"getaddr": msg_getaddr, b"getavaaddr": msg_getavaaddr, b"getavaproofs": msg_getavaproofs, b"getblocks": msg_getblocks, b"getblocktxn": msg_getblocktxn, b"getdata": msg_getdata, b"getheaders": msg_getheaders, b"headers": msg_headers, b"inv": msg_inv, b"mempool": msg_mempool, b"merkleblock": msg_merkleblock, b"notfound": msg_notfound, b"ping": msg_ping, b"pong": msg_pong, b"sendaddrv2": msg_sendaddrv2, b"sendcmpct": msg_sendcmpct, b"sendheaders": msg_sendheaders, b"tx": msg_tx, b"verack": msg_verack, b"version": msg_version, } NET_MAGIC_BYTES = { "mainnet": b"\xe3\xe1\xf3\xe8", "testnet3": b"\xf4\xe5\xf3\xf4", "regtest": b"\xda\xb5\xbf\xfa", } DISK_MAGIC_BYTES = { "mainnet": b"\xf9\xbe\xb4\xd9", "testnet3": b"\x0b\x11\x09\x07", "regtest": b"\xfa\xbf\xb5\xda", } class P2PConnection(asyncio.Protocol): """A low-level connection object to a node's P2P interface. This class is responsible for: - opening and closing the TCP connection to the node - reading bytes from and writing bytes to the socket - deserializing and serializing the P2P message header - logging messages as they are sent and received This class contains no logic for handing the P2P message payloads. It must be sub-classed and the on_message() callback overridden.""" def __init__(self): # The underlying transport of the connection. # Should only call methods on this from the NetworkThread, c.f. # call_soon_threadsafe self._transport = None @property def is_connected(self): return self._transport is not None def peer_connect_helper(self, dstaddr, dstport, net, timeout_factor): assert not self.is_connected self.timeout_factor = timeout_factor self.dstaddr = dstaddr self.dstport = dstport # The initial message to send after the connection was made: self.on_connection_send_msg = None self.on_connection_send_msg_is_raw = False self.recvbuf = b"" self.magic_bytes = NET_MAGIC_BYTES[net] def peer_connect(self, dstaddr, dstport, *, net, timeout_factor): self.peer_connect_helper(dstaddr, dstport, net, timeout_factor) loop = NetworkThread.network_event_loop logger.debug(f"Connecting to Bitcoin ABC Node: {self.dstaddr}:{self.dstport}") coroutine = loop.create_connection( lambda: self, host=self.dstaddr, port=self.dstport ) return lambda: loop.call_soon_threadsafe(loop.create_task, coroutine) def peer_accept_connection( self, connect_id, connect_cb=lambda: None, *, net, timeout_factor ): self.peer_connect_helper("0", 0, net, timeout_factor) logger.debug(f"Listening for Bitcoin ABC Node with id: {connect_id}") return lambda: NetworkThread.listen(self, connect_cb, idx=connect_id) def peer_disconnect(self): # Connection could have already been closed by other end. NetworkThread.network_event_loop.call_soon_threadsafe( lambda: self._transport and self._transport.abort() ) # Connection and disconnection methods def connection_made(self, transport): """asyncio callback when a connection is opened.""" assert not self._transport logger.debug(f"Connected & Listening: {self.dstaddr}:{self.dstport}") self._transport = transport if self.on_connection_send_msg: if self.on_connection_send_msg_is_raw: self.send_raw_message(self.on_connection_send_msg) else: self.send_message(self.on_connection_send_msg) # Never used again self.on_connection_send_msg = None self.on_open() def connection_lost(self, exc): """asyncio callback when a connection is closed.""" if exc: logger.warning( f"Connection lost to {self.dstaddr}:{self.dstport} due to {exc}" ) else: logger.debug(f"Closed connection to: {self.dstaddr}:{self.dstport}") self._transport = None self.recvbuf = b"" self.on_close() # Socket read methods def data_received(self, t): """asyncio callback when data is read from the socket.""" with p2p_lock: if len(t) > 0: self.recvbuf += t while True: msg = self._on_data() if msg is None: break self.on_message(msg) def _on_data(self): """Try to read P2P messages from the recv buffer. This method reads data from the buffer in a loop. It deserializes, parses and verifies the P2P header, then passes the P2P payload to the on_message callback for processing.""" try: with p2p_lock: if len(self.recvbuf) < 4: return None if self.recvbuf[:4] != self.magic_bytes: raise ValueError( "magic bytes mismatch: " f"{self.magic_bytes!r} != {self.recvbuf!r}" ) if len(self.recvbuf) < 4 + 12 + 4 + 4: return None msgtype = self.recvbuf[4 : 4 + 12].split(b"\x00", 1)[0] msglen = struct.unpack(" 500: log_message += "... (msg truncated)" logger.debug(log_message) class P2PInterface(P2PConnection): """A high-level P2P interface class for communicating with a Bitcoin Cash node. This class provides high-level callbacks for processing P2P message payloads, as well as convenience methods for interacting with the node over P2P. Individual testcases should subclass this and override the on_* methods if they want to alter message handling behaviour.""" def __init__(self, support_addrv2=False): super().__init__() # Track number of messages of each type received. # Should be read-only in a test. self.message_count = defaultdict(int) # Track the most recent message of each type. # To wait for a message to be received, pop that message from # this and use self.wait_until. self.last_message = {} # A count of the number of ping messages we've sent to the node self.ping_counter = 1 # The network services received from the peer self.nServices = 0 self.support_addrv2 = support_addrv2 def peer_connect_send_version(self, services): # Send a version msg vt = msg_version() vt.nVersion = P2P_VERSION vt.strSubVer = P2P_SUBVERSION vt.relay = P2P_VERSION_RELAY vt.nServices = services vt.addrTo.ip = self.dstaddr vt.addrTo.port = self.dstport vt.addrFrom.ip = "0.0.0.0" vt.addrFrom.port = 0 # Will be sent in connection_made callback self.on_connection_send_msg = vt def peer_connect(self, *args, services=P2P_SERVICES, send_version=True, **kwargs): create_conn = super().peer_connect(*args, **kwargs) if send_version: self.peer_connect_send_version(services) return create_conn def peer_accept_connection(self, *args, services=NODE_NETWORK, **kwargs): create_conn = super().peer_accept_connection(*args, **kwargs) self.peer_connect_send_version(services) return create_conn # Message receiving methods def on_message(self, message): """Receive message and dispatch message to appropriate callback. We keep a count of how many of each message type has been received and the most recent message of each type.""" with p2p_lock: try: msgtype = message.msgtype.decode("ascii") self.message_count[msgtype] += 1 self.last_message[msgtype] = message getattr(self, f"on_{msgtype}")(message) except Exception: print(f"ERROR delivering {repr(message)} ({sys.exc_info()[0]})") raise # Callback methods. Can be overridden by subclasses in individual test # cases to provide custom message handling behaviour. def on_open(self): pass def on_close(self): pass def on_addr(self, message): pass def on_addrv2(self, message): pass def on_avapoll(self, message): pass def on_avaproof(self, message): pass def on_avaproofs(self, message): pass def on_avaproofsreq(self, message): pass def on_avaresponse(self, message): pass def on_avahello(self, message): pass def on_block(self, message): pass def on_blocktxn(self, message): pass def on_cfcheckpt(self, message): pass def on_cfheaders(self, message): pass def on_cfilter(self, message): pass def on_cmpctblock(self, message): pass def on_feefilter(self, message): pass def on_filteradd(self, message): pass def on_filterclear(self, message): pass def on_filterload(self, message): pass def on_getaddr(self, message): pass def on_getavaaddr(self, message): pass def on_getavaproofs(self, message): pass def on_getblocks(self, message): pass def on_getblocktxn(self, message): pass def on_getdata(self, message): pass def on_getheaders(self, message): pass def on_headers(self, message): pass def on_mempool(self, message): pass def on_merkleblock(self, message): pass def on_notfound(self, message): pass def on_pong(self, message): pass def on_sendaddrv2(self, message): pass def on_sendcmpct(self, message): pass def on_sendheaders(self, message): pass def on_tx(self, message): pass def on_inv(self, message): want = msg_getdata() for i in message.inv: if i.type != 0: want.inv.append(i) if len(want.inv): self.send_message(want) def on_ping(self, message): self.send_message(msg_pong(message.nonce)) def on_verack(self, message): pass def on_version(self, message): assert message.nVersion >= MIN_P2P_VERSION_SUPPORTED, ( f"Version {message.nVersion} received. Test framework only supports " f"versions greater than {MIN_P2P_VERSION_SUPPORTED}" ) self.send_message(msg_verack()) if self.support_addrv2: self.send_message(msg_sendaddrv2()) self.nServices = message.nServices self.send_message(msg_getaddr()) # Connection helper methods def wait_until(self, test_function_in, *, timeout=60, check_connected=True): def test_function(): if check_connected: assert self.is_connected return test_function_in() wait_until_helper( test_function, timeout=timeout, lock=p2p_lock, timeout_factor=self.timeout_factor, ) def wait_for_connect(self, timeout=60): def test_function(): return self.is_connected self.wait_until(test_function, timeout=timeout, check_connected=False) def wait_for_disconnect(self, timeout=60): def test_function(): return not self.is_connected self.wait_until(test_function, timeout=timeout, check_connected=False) # Message receiving helper methods def wait_for_tx(self, txid, timeout=60): def test_function(): if not self.last_message.get("tx"): return False return self.last_message["tx"].tx.rehash() == txid self.wait_until(test_function, timeout=timeout) def wait_for_block(self, blockhash, timeout=60): def test_function(): return ( self.last_message.get("block") and self.last_message["block"].block.rehash() == blockhash ) self.wait_until(test_function, timeout=timeout) def wait_for_header(self, blockhash, timeout=60): def test_function(): last_headers = self.last_message.get("headers") if not last_headers: return False return last_headers.headers[0].rehash() == int(blockhash, 16) self.wait_until(test_function, timeout=timeout) def wait_for_merkleblock(self, blockhash, timeout=60): def test_function(): last_filtered_block = self.last_message.get("merkleblock") if not last_filtered_block: return False return last_filtered_block.merkleblock.header.rehash() == int(blockhash, 16) self.wait_until(test_function, timeout=timeout) def wait_for_getdata(self, hash_list, timeout=60): """Waits for a getdata message. The object hashes in the inventory vector must match the provided hash_list.""" def test_function(): last_data = self.last_message.get("getdata") if not last_data: return False return [x.hash for x in last_data.inv] == hash_list self.wait_until(test_function, timeout=timeout) def wait_for_getheaders(self, timeout=60): """Waits for a getheaders message. Receiving any getheaders message will satisfy the predicate. the last_message["getheaders"] value must be explicitly cleared before calling this method, or this will return immediately with success. TODO: change this method to take a hash value and only return true if the correct block header has been requested.""" def test_function(): return self.last_message.get("getheaders") self.wait_until(test_function, timeout=timeout) def wait_for_inv(self, expected_inv, timeout=60): """Waits for an INV message and checks that the first inv object in the message was as expected.""" if len(expected_inv) > 1: raise NotImplementedError( "wait_for_inv() will only verify the first inv object" ) def test_function(): return ( self.last_message.get("inv") and self.last_message["inv"].inv[0].type == expected_inv[0].type and self.last_message["inv"].inv[0].hash == expected_inv[0].hash ) self.wait_until(test_function, timeout=timeout) def wait_for_verack(self, timeout=60): def test_function(): return "verack" in self.last_message self.wait_until(test_function, timeout=timeout) # Message sending helper functions def send_and_ping(self, message, timeout=60): self.send_message(message) self.sync_with_ping(timeout=timeout) - def sync_send_with_ping(self, timeout=60): - """Ensure SendMessages is called on this connection""" - # Calling sync_with_ping twice requires that the node calls + def sync_with_ping(self, timeout=60): + """Ensure ProcessMessages and SendMessages is called on this connection""" + # Sending two pings back-to-back, requires that the node calls # `ProcessMessage` twice, and thus ensures `SendMessages` must have # been called at least once - self.sync_with_ping() - self.sync_with_ping() - - def sync_with_ping(self, timeout=60): - """Ensure ProcessMessages is called on this connection""" + self.send_message(msg_ping(nonce=0)) self.send_message(msg_ping(nonce=self.ping_counter)) def test_function(): return ( self.last_message.get("pong") and self.last_message["pong"].nonce == self.ping_counter ) self.wait_until(test_function, timeout=timeout) self.ping_counter += 1 # One lock for synchronizing all data access between the networking thread (see # NetworkThread below) and the thread running the test logic. For simplicity, # P2PConnection acquires this lock whenever delivering a message to a P2PInterface. # This lock should be acquired in the thread running the test logic to synchronize # access to any data shared with the P2PInterface or P2PConnection. p2p_lock = threading.Lock() class NetworkThread(threading.Thread): network_event_loop = None def __init__(self): super().__init__(name="NetworkThread") # There is only one event loop and no more than one thread must be # created assert not self.network_event_loop NetworkThread.listeners = {} NetworkThread.protos = {} NetworkThread.network_event_loop = asyncio.new_event_loop() def run(self): """Start the network thread.""" self.network_event_loop.run_forever() def close(self, timeout=10): """Close the connections and network event loop.""" self.network_event_loop.call_soon_threadsafe(self.network_event_loop.stop) wait_until_helper( lambda: not self.network_event_loop.is_running(), timeout=timeout ) self.network_event_loop.close() self.join(timeout) # Safe to remove event loop. NetworkThread.network_event_loop = None @classmethod def listen(cls, p2p, callback, port=None, addr=None, idx=1): """Ensure a listening server is running on the given port, and run the protocol specified by `p2p` on the next connection to it. Once ready for connections, call `callback`.""" if port is None: assert 0 < idx <= MAX_NODES port = p2p_port(MAX_NODES - idx) if addr is None: addr = "127.0.0.1" coroutine = cls.create_listen_server(addr, port, callback, p2p) cls.network_event_loop.call_soon_threadsafe( cls.network_event_loop.create_task, coroutine ) @classmethod async def create_listen_server(cls, addr, port, callback, proto): def peer_protocol(): """Returns a function that does the protocol handling for a new connection. To allow different connections to have different behaviors, the protocol function is first put in the cls.protos dict. When the connection is made, the function removes the protocol function from that dict, and returns it so the event loop can start executing it.""" response = cls.protos.get((addr, port)) cls.protos[(addr, port)] = None return response if (addr, port) not in cls.listeners: # When creating a listener on a given (addr, port) we only need to # do it once. If we want different behaviors for different # connections, we can accomplish this by providing different # `proto` functions listener = await cls.network_event_loop.create_server( peer_protocol, addr, port ) logger.debug(f"Listening server on {addr}:{port} should be started") cls.listeners[(addr, port)] = listener cls.protos[(addr, port)] = proto callback(addr, port) class P2PDataStore(P2PInterface): """A P2P data store class. Keeps a block and transaction store and responds correctly to getdata and getheaders requests. """ def __init__(self): super().__init__() # store of blocks. key is block hash, value is a CBlock object self.block_store = {} self.last_block_hash = "" # store of txs. key is txid, value is a CTransaction object self.tx_store = {} self.getdata_requests = [] def on_getdata(self, message): """Check for the tx/block in our stores and if found, reply with an inv message.""" for inv in message.inv: self.getdata_requests.append(inv.hash) if ( inv.type & MSG_TYPE_MASK ) == MSG_TX and inv.hash in self.tx_store.keys(): self.send_message(msg_tx(self.tx_store[inv.hash])) elif ( inv.type & MSG_TYPE_MASK ) == MSG_BLOCK and inv.hash in self.block_store.keys(): self.send_message(msg_block(self.block_store[inv.hash])) else: logger.debug(f"getdata message type {hex(inv.type)} received.") def on_getheaders(self, message): """Search back through our block store for the locator, and reply with a headers message if found.""" locator, hash_stop = message.locator, message.hashstop # Assume that the most recent block added is the tip if not self.block_store: return headers_list = [self.block_store[self.last_block_hash]] while headers_list[-1].sha256 not in locator.vHave: # Walk back through the block store, adding headers to headers_list # as we go. prev_block_hash = headers_list[-1].hashPrevBlock if prev_block_hash in self.block_store: prev_block_header = CBlockHeader(self.block_store[prev_block_hash]) headers_list.append(prev_block_header) if prev_block_header.sha256 == hash_stop: # if this is the hashstop header, stop here break else: logger.debug( f"block hash {hex(prev_block_hash)} not found in block store" ) break # Truncate the list if there are too many headers headers_list = headers_list[: -MAX_HEADERS_RESULTS - 1 : -1] response = msg_headers(headers_list) if response is not None: self.send_message(response) def send_blocks_and_test( self, blocks, node, *, success=True, force_send=False, reject_reason=None, expect_disconnect=False, timeout=60, ): """Send blocks to test node and test whether the tip advances. - add all blocks to our block_store - send a headers message for the final block - the on_getheaders handler will ensure that any getheaders are responded to - if force_send is False: wait for getdata for each of the blocks. The on_getdata handler will ensure that any getdata messages are responded to. Otherwise send the full block unsolicited. - if success is True: assert that the node's tip advances to the most recent block - if success is False: assert that the node's tip doesn't advance - if reject_reason is set: assert that the correct reject message is logged""" with p2p_lock: for block in blocks: self.block_store[block.sha256] = block self.last_block_hash = block.sha256 def test(): if force_send: for b in blocks: self.send_message(msg_block(block=b)) else: self.send_message( msg_headers([CBlockHeader(block) for block in blocks]) ) self.wait_until( lambda: blocks[-1].sha256 in self.getdata_requests, timeout=timeout, check_connected=success, ) if expect_disconnect: self.wait_for_disconnect(timeout=timeout) else: self.sync_with_ping(timeout=timeout) if success: self.wait_until( lambda: node.getbestblockhash() == blocks[-1].hash, timeout=timeout ) else: assert node.getbestblockhash() != blocks[-1].hash if reject_reason: with node.assert_debug_log(expected_msgs=[reject_reason]): test() else: test() def send_txs_and_test( self, txs, node, *, success=True, expect_disconnect=False, reject_reason=None ): """Send txs to test node and test whether they're accepted to the mempool. - add all txs to our tx_store - send tx messages for all txs - if success is True/False: assert that the txs are/are not accepted to the mempool - if expect_disconnect is True: Skip the sync with ping - if reject_reason is set: assert that the correct reject message is logged.""" with p2p_lock: for tx in txs: self.tx_store[tx.sha256] = tx def test(): for tx in txs: self.send_message(msg_tx(tx)) if expect_disconnect: self.wait_for_disconnect() else: self.sync_with_ping() raw_mempool = node.getrawmempool() if success: # Check that all txs are now in the mempool for tx in txs: assert tx.hash in raw_mempool, f"{tx.hash} not found in mempool" else: # Check that none of the txs are now in the mempool for tx in txs: assert tx.hash not in raw_mempool, f"{tx.hash} tx found in mempool" if reject_reason: with node.assert_debug_log(expected_msgs=[reject_reason]): test() else: test() class P2PTxInvStore(P2PInterface): """A P2PInterface which stores a count of how many times each txid has been announced.""" def __init__(self): super().__init__() self.tx_invs_received = defaultdict(int) def on_inv(self, message): # Send getdata in response. super().on_inv(message) # Store how many times invs have been received for each tx. for i in message.inv: if i.type == MSG_TX: # save txid self.tx_invs_received[i.hash] += 1 def get_invs(self): with p2p_lock: return list(self.tx_invs_received.keys()) def wait_for_broadcast(self, txns, timeout=60): """Waits for the txns (list of txids) to complete initial broadcast. The mempool should mark unbroadcast=False for these transactions. """ # Wait until invs have been received (and getdatas sent) for each txid. self.wait_until( lambda: set(self.tx_invs_received.keys()) == {int(tx, 16) for tx in txns}, timeout=timeout, ) # Flush messages and wait for the getdatas to be processed self.sync_with_ping()