desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Send a tick message :param tick: The message to send :type tick: Tick'
def send_tick(self, tick):
assert isinstance(tick, (Ask, Bid)), type(tick) self._logger.debug('%s send with id: %s for order with id: %s', type(tick), str(tick.message_id), str(tick.order_id)) payload = tick.to_network() payload += ((Ttl.default(),) + self.get_dispersy_address()) meta = self.get_met...
'Create an ask order (sell order) :param price: The price for the order in btc :param price_wallet_id: The type of the price (i.e. EUR, BTC) :param quantity: The quantity of the order :param price_wallet_id: The type of the price (i.e. EUR, BTC) :param timeout: The timeout of the order, when does the order need to be t...
def create_bid(self, price, price_wallet_id, quantity, quantity_wallet_id, timeout):
self.verify_offer_creation(price, price_wallet_id, quantity, quantity_wallet_id) price = Price(price, price_wallet_id) quantity = Quantity(quantity, quantity_wallet_id) timeout = Timeout(timeout) order = self.order_manager.create_bid_order(price, quantity, timeout) self.match(order) tick = T...
'Send a cancel-order message to the community'
def send_cancel_order(self, order):
assert isinstance(order, Order), type(order) message_id = self.order_book.message_repository.next_identity() meta = self.get_meta_message(u'cancel-order') message = meta.impl(authentication=(self.my_member,), distribution=(self.claim_global_time(),), payload=(message_id.trader_id, message_id.message_num...
'Send an offer sync message :param target_candidate: The candidate to send this message to :type: target_candidate: WalkCandidate :param tick: The tick to send :type tick: Tick'
def send_offer_sync(self, target_candidate, tick):
assert isinstance(target_candidate, WalkCandidate), type(target_candidate) assert isinstance(tick, Tick), type(tick) self._logger.debug('Offer sync send with id: %s for order with id: %s', str(tick.message_id), str(tick.order_id)) payload = tick.to_network() trader_ip =...
'Update your tick in the order book according to a specific transaction. Afterwards, send the updated tick.'
def update_ticks(self, transaction, end_transaction_timestamp):
self._logger.debug('Updating own tick and sending it to other traders') self.order_book.trade_tick(transaction.order_id, transaction.partner_order_id, transaction.transferred_quantity, end_transaction_timestamp) if self.order_book.tick_exists(transaction.order_id): tick = sel...
'Abort a specific transaction by releasing all reserved quantity for this order.'
def abort_transaction(self, transaction):
self._logger.error('Aborting transaction %s', transaction.transaction_id) order = self.order_manager.order_repository.find_by_id(transaction.order_id) order.release_quantity_for_tick(transaction.partner_order_id, (transaction.total_quantity - transaction.transferred_quantity)) self.order_manager.o...
'Compute the reputation of peers in the community'
def compute_reputation(self):
if self.tradechain_community: rep_manager = PagerankReputationManager(self.tradechain_community.persistence.get_all_blocks()) self.reputation_dict = rep_manager.compute(self.my_member.public_key)
'Monitor an incoming transaction with a specific id.'
def monitor_transaction(self, payment_id):
self.tc_community.received_payment_message(payment_id) block_id = '.'.join(payment_id.split('.')[:2]) return self.tc_community.wait_for_signature_request(str(block_id))
'Monitor an incoming transaction with a specific ID.'
def monitor_transaction(self, transaction_id):
def on_transaction_done(): self.transaction_history.append({'id': transaction_id, 'outgoing': True, 'from': '', 'to': self.address, 'amount': float(str(transaction_id)), 'fee_amount': 0.0, 'currency': self.get_identifier(), 'timestamp': '', 'description': ''}) self.balance += float(str(transaction_i...
'Generate a random transaction ID'
def generate_txid(self, length=10):
return ''.join((random.choice((string.ascii_uppercase + string.digits)) for _ in range(length)))
'Return the daemon that can be used to send JSON RPC commands to. This method is here so we can unit test this class.'
def get_daemon(self):
from electrum import daemon return daemon
'Create a new bitcoin wallet.'
def create_wallet(self, password=''):
self._logger.info('Creating wallet in %s', self.wallet_dir) def run_on_thread(thread_method): wallet_thread = Thread(target=thread_method, name='ethereum-create-wallet') wallet_thread.setDaemon(False) wallet_thread.start() wallet_thread.join() seed = Mnemonic('en').m...
'Return the balance of the wallet.'
def get_balance(self):
divider = 100000000 if self.created: (confirmed, unconfirmed, unmatured) = self.wallet.get_balance() return succeed({'available': (float(confirmed) / divider), 'pending': (float((unconfirmed + unmatured)) / divider), 'currency': 'BTC'}) else: return succeed({'available': 0, 'pending'...
'Monitor a given transaction ID. Returns a Deferred that fires when the transaction is present.'
def monitor_transaction(self, txid):
monitor_deferred = Deferred() @inlineCallbacks def monitor_loop(): transactions = (yield self.get_transactions()) for transaction in transactions: if (transaction['id'] == txid): self._logger.debug('Found transaction with id %s', txid) ...
'Compute the reputation based on the data in the TradeChain database.'
def compute(self, own_public_key):
raise NotImplementedError()
'Compute the reputation based on the data in the TradeChain database using the PageRank algorithm.'
def compute(self, own_public_key):
nodes = set() G = nx.Graph() for block in self.blocks: nodes.add(block.public_key) nodes.add(block.link_public_key) G.add_edge(block.public_key, block.link_public_key, attr_dict={'weight': block.transaction['asset1_amount']}) G.add_edge(block.link_public_key, block.public_key...
'Return all blocks in the database.'
def get_all_blocks(self):
return self._getall(u'', ())
'Return the upgrade script for a specific version. :param current_version: the version of the script to return.'
def get_upgrade_script(self, current_version):
return None
'Only sign the block if we have a (completed) transaction in the market community with the specific txid.'
def should_sign(self, message):
if (not self.market_community): return False (trader_id_str, transaction_number_str) = message.payload.block.transaction['txid'].split('.') txid = TransactionId(TraderId(trader_id_str), TransactionNumber(int(transaction_number_str))) transaction = self.market_community.transaction_manager.find_b...
'Instantiate a new Circuit data structure :type proxy: TunnelCommunity :param long circuit_id: the id of the candidate circuit :param (str, int) first_hop: the first hop of the circuit :return: Circuit'
def __init__(self, circuit_id, goal_hops=0, first_hop=None, proxy=None, ctype=CIRCUIT_TYPE_DATA, callback=None, required_exit=None, mid=None, info_hash=None):
from Tribler.community.tunnel.hidden_community import HiddenTunnelCommunity assert isinstance(circuit_id, long) assert isinstance(goal_hops, int) assert ((proxy is None) or isinstance(proxy, HiddenTunnelCommunity)) assert ((first_hop is None) or (isinstance(first_hop, tuple) and isinstance(first_hop...
'Return a read only tuple version of the hop-list of this circuit @rtype tuple[Hop]'
@property def hops(self):
return tuple(self._hops)
'Adds a hop to the circuits hop collection @param Hop hop: the hop to add'
def add_hop(self, hop):
self._hops.append(hop)
'The circuit state, can be either: CIRCUIT_STATE_BROKEN, CIRCUIT_STATE_EXTENDING or CIRCUIT_STATE_READY @rtype: str'
@property def state(self):
if self._broken: return CIRCUIT_STATE_BROKEN if (len(self.hops) < self.goal_hops): return CIRCUIT_STATE_EXTENDING else: return CIRCUIT_STATE_READY
'Mark the circuit as active'
def beat_heart(self):
self.last_incoming = time.time()
'Convenience method to tunnel data over this circuit @param (str, int) destination: the destination of the packet @param str payload: the packet\'s payload'
def tunnel_data(self, destination, payload):
self._logger.info('Tunnel data (len %d) to end for circuit %s with ultimate destination %s', len(payload), self.circuit_id, destination) num_bytes = self.proxy.send_data([Candidate(self.first_hop, False)], self.circuit_id, destination, ('0.0.0.0', 0), payload) self.proxy....
'Destroys the circuit and calls the error callback of the circuit\'s deferred if it has not been called before @param str reason: the reason why the circuit is being destroyed'
def destroy(self, reason='unknown'):
self._broken = True
'@param None|LibNaCLPK public_key: public key object of the hop'
def __init__(self, public_key=None):
assert ((public_key is None) or isinstance(public_key, LibNaCLPK)) self.session_keys = None self.dh_first_part = None self.dh_secret = None self.address = None self.public_key = public_key
'The hop\'s hostname'
@property def host(self):
if self.address: return self.address[0] return ' UNKNOWN HOST '
'The hop\'s port'
@property def port(self):
if self.address: return self.address[1] return ' UNKNOWN PORT '
'The hop\'s nodeid'
@property def node_id(self):
if self.public_key: return self.public_key.key_to_hash() raise RuntimeError('nodeid unknown')
'The hop\'s public_key'
@property def node_public_key(self):
if self.public_key: return self.public_key.key_to_bin() raise RuntimeError('public key unknown')
'@type sock_addr: (str, int) @type circuit_id: int @return:'
def __init__(self, circuit_id, sock_addr, rendezvous_relay=False, mid=None):
self.sock_addr = sock_addr self.circuit_id = circuit_id self.creation_time = time.time() self.last_incoming = time.time() self.bytes_up = self.bytes_down = 0 self.rendezvous_relay = rendezvous_relay self.mid = mid
'The destination address as a tuple @rtype: (str, int)'
@property def destination(self):
return (self.destination_host, self.destination_port)
'The destination address as a tuple @rtype: (str, int)'
@property def destination(self):
return (self.destination_host, self.destination_port)
'Try to read a HANDSHAKE request :return: False if command could not been processes due to lack of bytes, True otherwise'
def _try_handshake(self):
(offset, request) = conversion.decode_methods_request(0, self.buffer) if (request is None): return False assert isinstance(request, conversion.MethodRequest), request self.buffer = self.buffer[offset:] if ((request.version != 5) or (0 not in request.methods)): self._logger.error('Cli...
'Try to consume a REQUEST message and respond whether we will accept the request. Will setup a TCP relay or an UDP socket to accommodate TCP RELAY and UDP ASSOCIATE requests. After a TCP relay is set up the handler will deactivate itself and change the Connection to a TcpRelayConnection. Further data will be passed on ...
def _try_request(self):
self._logger.debug('Client has sent PROXY REQUEST') (offset, request) = conversion.decode_request(0, self.buffer) if (request is None): return False self.buffer = self.buffer[offset:] assert isinstance(request, conversion.Request) self.state = ConnectionState.PROXY_REQUEST_RE...
'Deny SOCKS5 request @param Request request: the request to deny'
def deny_request(self, request, reason):
self.state = ConnectionState.CONNECTED response = conversion.encode_reply(5, conversion.REP_COMMAND_NOT_SUPPORTED, 0, conversion.ADDRESS_TYPE_IPV4, '0.0.0.0', 0) self.transport.write(response) self._logger.error(('DENYING SOCKS5 request, reason: %s' % reason))
'When a circuit breaks and it affects our operation we should re-add the peers when a new circuit is available @param Circuit broken_circuit: the circuit that has been broken @return Set with destinations using this circuit'
def circuit_dead(self, broken_circuit):
affected_destinations = set((destination for (destination, tunnel_circuit) in self.destinations.iteritems() if (tunnel_circuit == broken_circuit))) counter = 0 for destination in affected_destinations: if (destination in self.destinations): del self.destinations[destination] ...
'Closes the UDP socket if enabled and cancels all pending deferreds. :return: A deferred that fires once the UDP socket has closed.'
@inlineCallbacks def close(self):
assert isInIOThread() (yield self.wait_for_deferred_tasks()) self.cancel_all_pending_tasks() done_closing_deferred = succeed(None) if self.enabled: done_closing_deferred = maybeDeferred(self.port.stopListening) self.port = None res = (yield done_closing_deferred) returnValue(...
'This method is called when a download is removed. We check here whether we can stop building circuits for a specific number of hops in case it hasn\'t been finished yet.'
def on_download_removed(self, download):
if (download.get_hops() > 0): self.num_hops_by_downloads[download.get_hops()] -= 1 if (self.num_hops_by_downloads[download.get_hops()] == 0): self.circuits_needed[download.get_hops()] = 0
'Create an unmanaged Candidate for a tunnel mechanism with a certain address This avoids candidates being disassociated while they are being used in notifications. :param tunnel: the tunnel object being used :type tunnel: Circuit or RelayRoute or TunnelExitSocket :param sock_addr: the socket address of the candidate :t...
def copy_shallow_candidate(self, tunnel, sock_addr):
assert isinstance(sock_addr, tuple), type(sock_addr) assert (len(sock_addr) == 2), sock_addr assert (isinstance(tunnel, Circuit) or isinstance(tunnel, RelayRoute) or isinstance(tunnel, TunnelExitSocket)) candidate = Candidate(sock_addr, True) member = self.dispersy.get_member(mid=tunnel.mid.decode('...
'Returns the number of people you interacted with (either helped or that have helped you) :param public_key: The public key of the member of which we want the information :return: A tuple of unique number of interactors that helped you and that you have helped respectively'
def get_num_unique_interactors(self, public_key):
peers_you_helped = set() peers_helped_you = set() for block in self.get_latest_blocks(public_key, limit=(-1)): if (int(block.transaction['up']) > 0): peers_you_helped.add(block.link_public_key) if (int(block.transaction['down']) > 0): peers_helped_you.add(block.link_p...
'Return the upgrade script for a specific version. :param current_version: the version of the script to return.'
def get_upgrade_script(self, current_version):
if ((current_version == 2) or (current_version == 3)): return (u'\n DROP TABLE IF EXISTS %s;\n DROP TABLE IF EXISTS option;\n ' % self.db_name)...
'Create an empty next block. :param database: the database to use as information source :param transaction: the transaction to use in this block :param public_key: the public key to use for this block :param link: optionally create the block as a linked block to this block :param link_pk: the public key of the counterp...
@classmethod def create(cls, transaction, database, public_key, link=None, link_pk=None):
blk = database.get_latest(public_key) ret = cls() if link: ret.transaction['up'] = link.transaction['down'] ret.transaction['down'] = link.transaction['up'] ret.link_public_key = link.public_key ret.link_sequence_number = link.sequence_number else: ret.transaction...
'Validates this transaction :param transaction the transaction to validate :param database: the database to check against :return: A tuple consisting of a ValidationResult and a list of user string errors'
def validate_transaction(self, database):
result = [ValidationResult.valid] errors = [] def err(reason): result[0] = ValidationResult.invalid errors.append(reason) if (self.transaction['up'] < 0): err('Up field is negative') if (self.transaction['down'] < 0): err('Down field is negative') ...
'We received a payment message originating from the market community. We set pending bytes so the validator passes when we receive the half block from the counterparty. Note that it might also be possible that the half block has been received already. That\'s why we revalidate the invalid messages again.'
def received_payment_message(self, payment_id):
(pub_key, seq_num, bytes_up, bytes_down) = payment_id.split('.') pub_key = pub_key.decode('hex') pend = self.pending_bytes.get(pub_key) if (not pend): self.pending_bytes[pub_key] = PendingBytes(int(bytes_up), int(bytes_down), None) else: pend.add(int(bytes_up), int(bytes_down)) b...
'Return whether we should sign the block in the passed message. @param message: the message containing a block we want to sign or not.'
def should_sign(self, message):
block = message.payload.block pend = self.pending_bytes.get(block.public_key) if ((not pend) or (not (((pend.up - block.transaction['down']) >= 0) and ((pend.down - block.transaction['up']) >= 0)))): self.logger.info('Request block counter party does not have enough bytes ...
'Returns a dictionary with some statistics regarding the local trustchain database :returns a dictionary with statistics'
@blocking_call_on_reactor_thread def get_statistics(self, public_key=None):
if (public_key is None): public_key = self.my_member.public_key latest_block = self.persistence.get_latest(public_key) statistics = dict() statistics['id'] = public_key.encode('hex') interacts = self.persistence.get_num_unique_interactors(public_key) statistics['peers_that_pk_helped'] = ...
'Handler for the remove event of a tunnel. This function will attempt to create a block for the amounts that were transferred using the tunnel. :param subject: Category of the notifier event :param change_type: Type of the notifier event :param tunnel: The tunnel that was removed (closed) :param candidate: The dispersy...
@blocking_call_on_reactor_thread def on_tunnel_remove(self, subject, change_type, tunnel, candidate):
from Tribler.community.tunnel.tunnel_community import Circuit, RelayRoute, TunnelExitSocket assert (isinstance(tunnel, Circuit) or isinstance(tunnel, RelayRoute) or isinstance(tunnel, TunnelExitSocket)), 'on_tunnel_remove() was called with an object that is not a Circuit, RelayR...
'Get the trust for another member. Currently this is just the amount of MBs exchanged with them. :param member: the member we interacted with :type member: dispersy.member.Member :return: the trust value for this member :rtype: int'
def get_trust(self, member):
block = self.persistence.get_latest(member.public_key) if block: return (block.transaction['total_up'] + block.transaction['total_down']) else: return 1
'Test adding to pending bytes'
def test_add_pending_bytes(self):
pending_bytes = PendingBytes(20, 30) self.assertTrue(pending_bytes.add(20, 30)) self.assertFalse(pending_bytes.add((-100), (-100)))
'Test cleaning of pending bytes'
@blocking_call_on_reactor_thread @inlineCallbacks def test_cleanup_pending_bytes(self):
(node,) = (yield self.create_nodes(1)) node.community.pending_bytes['a'] = 1234 self.assertIn('a', node.community.pending_bytes) node.community.cleanup_pending('a') self.assertNotIn('a', node.community.pending_bytes)
'Test the on_tunnel_remove handler function for a circuit'
@blocking_call_on_reactor_thread @inlineCallbacks def test_on_tunnel_remove(self):
(node, other) = (yield self.create_nodes(2)) tunnel_node = Circuit(long(0), 0) tunnel_other = Circuit(long(0), 0) tunnel_node.bytes_up = tunnel_other.bytes_down = ((12 * 1024) * 1024) tunnel_node.bytes_down = tunnel_other.bytes_up = ((14 * 1024) * 1024) node.call(node.community.on_tunnel_remove,...
'Test the on_tunnel_remove handler function for a circuit'
@blocking_call_on_reactor_thread @inlineCallbacks def test_on_tunnel_remove_small(self):
(node, other) = (yield self.create_nodes(2)) tunnel_node = Circuit(long(0), 0) tunnel_other = Circuit(long(0), 0) tunnel_node.bytes_up = tunnel_other.bytes_down = 1024 tunnel_node.bytes_down = tunnel_other.bytes_up = (2 * 1024) node.call(node.community.on_tunnel_remove, None, None, tunnel_node, ...
'Test the on_tunnel_remove handler function for a circuit'
@blocking_call_on_reactor_thread @inlineCallbacks def test_on_tunnel_remove_append_pending(self):
(node, other) = (yield self.create_nodes(2)) tunnel_node = Circuit(long(0), 0) tunnel_node.bytes_up = ((12 * 1024) * 1024) tunnel_node.bytes_down = ((14 * 1024) * 1024) node.call(node.community.on_tunnel_remove, None, None, tunnel_node, self._create_target(node, other)) node.call(node.community....
'Test the community to receive a request message.'
def test_receive_request_invalid(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) TestTriblerChainCommunity.set_expectation(other, node, 10, 5) transaction = {'up': 10, 'down': 5} node.call(node.community.sign_block, target_other, other.my_member.public_key, transaction) (_, block_req) = othe...
'Test the community to receive a request message twice.'
def test_receive_request_twice(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) transaction = {'up': 10, 'down': 5} TestTriblerChainCommunity.set_expectation(node, other, 50, 50) TestTriblerChainCommunity.set_expectation(other, node, 50, 50) TestTriblerChainCommunity.create_block(node, othe...
'Test the community to receive a request that claims more than we are prepared to sign'
def test_receive_request_too_much(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) TestTriblerChainCommunity.set_expectation(other, node, 3, 3) transaction = {'up': 10, 'down': 5} node.call(node.community.sign_block, target_other, other.my_member.public_key, transaction) other.give_message(oth...
'Test the community to receive a request that claims about a peer we know nothing about'
def test_receive_request_unknown_pend(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) transaction = {'up': 10, 'down': 5} node.call(node.community.sign_block, target_other, other.my_member.public_key, transaction) other.give_message(other.receive_message(names=[HALF_BLOCK]).next()[1], node) self....
'If a block is created between two nodes both should have the correct total_up and total_down of the signature request.'
def test_block_values(self):
(node, other) = self.create_nodes(2) TestTriblerChainCommunity.set_expectation(node, other, 50, 50) TestTriblerChainCommunity.set_expectation(other, node, 50, 50) transaction = {'up': 10, 'down': 5} TestTriblerChainCommunity.create_block(node, other, self._create_target(node, other), transaction) ...
'After a request is sent, a node should update its totals.'
def test_block_values_after_request(self):
(node, other) = self.create_nodes(2) transaction = {'up': 10, 'down': 5} node.call(node.community.sign_block, self._create_target(node, other), other.my_member.public_key, transaction) block = node.call(TriblerChainBlock.create, transaction, node.community.persistence, node.community.my_member.public_ke...
'Test the crawler takes a step when an introduction is made by the walker'
def test_crawler_on_introduction_received(self):
TriblerChainCommunityCrawler.CrawlerDelay = 10000000 crawler = DispersyTestFunc.create_nodes(self, 1, community_class=TriblerChainCommunityCrawler, memory_database=False)[0] (node,) = self.create_nodes(1) node._community.cancel_pending_task('take fast steps') node._community.cancel_pending_tas...
'Test the get_statistics method where last block is none'
def test_get_statistics_no_blocks(self):
(node,) = self.create_nodes(1) statistics = node.community.get_statistics() assert isinstance(statistics, dict), type(statistics) assert (len(statistics) > 0)
'Test the get_statistics method where a last block exists'
def test_get_statistics_with_previous_block(self):
(node, other) = self.create_nodes(2) transaction = {'up': 10, 'down': 5} TestTriblerChainCommunity.create_block(node, other, self._create_target(node, other), transaction) statistics = node.community.get_statistics() assert isinstance(statistics, dict), type(statistics) assert (len(statistics) >...
'Test the get_statistics method where a last block exists'
def test_get_statistics_for_not_self(self):
(node, other) = self.create_nodes(2) transaction = {'up': 10, 'down': 5} TestTriblerChainCommunity.create_block(node, other, self._create_target(node, other), transaction) statistics = node.community.get_statistics(public_key=other.community.my_member.public_key) assert isinstance(statistics, dict),...
'Test that the trust nodes have for each other is the upload + the download total of all blocks.'
def test_get_trust(self):
(node, other) = self.create_nodes(2) transaction = {'up': 10, 'down': 5, 'total_up': 10, 'total_down': 5} TestTriblerChainCommunity.create_block(node, other, self._create_target(node, other), transaction) TestTriblerChainCommunity.create_block(other, node, self._create_target(other, node), transaction) ...
'Test that the trust between nodes without blocks is 1.'
def test_get_default_trust(self):
(node, other) = self.create_nodes(2) node_trust = blockingCallFromThread(reactor, node.community.get_trust, other.community.my_member) other_trust = blockingCallFromThread(reactor, other.community.get_trust, node.community.my_member) self.assertEqual(node_trust, 1) self.assertEqual(other_trust, 1)
'Test whether the right number of interactors is returned'
@blocking_call_on_reactor_thread def test_get_num_interactors(self):
self.block2 = TestBlock(previous=self.block1, transaction={'up': 42, 'down': 42}) self.db.add_block(self.block1) self.db.add_block(self.block2) self.assertEqual((2, 2), self.db.get_num_unique_interactors(self.block1.public_key))
'Test the community to send a signature request message.'
def test_sign_block(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) node.call(node.community.sign_block, target_other, other.my_member.public_key, {'id': 42}) (_, message) = other.receive_message(names=[HALF_BLOCK]).next() self.assertTrue(message)
'Test the sign_block function with a missing member'
def test_sign_block_missing_member(self):
def mocked_publish_sig(*_): raise DelayPacketByMissingMember(node.community, ('a' * 20)) (node, other) = self.create_nodes(2) other.send_identity(node) target_other = self._create_target(node, other) node.community.dispersy.store_update_forward = mocked_publish_sig node.call(node.communi...
'Test the community to publish a signature request message.'
def test_sign_invalid_block(self):
(node, other) = self.create_nodes(2) target_other = self._create_target(node, other) node.call(node.community.sign_block, target_other, ('a' * 10), {'id': 42}) with self.assertRaises(StopIteration): other.receive_message(names=[HALF_BLOCK]).next()
'Test the community to receive a signature request and a signature response message.'
def test_receive_signature_request_and_response(self):
(node, other) = self.create_nodes(2) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) self.assertBlocksInDatabase(other, 2) self.assertBlocksInDatabase(node, 2) self.assertBlocksAreEqual(node, other) block = node.call(node.community.persistence.get_...
'Test that a crawl is requested if the signer cannot validate the previous hash of a request'
def test_crawl_on_partial(self):
(node, other, another) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) node.call(node.community.sign_block, self._create_target(node, another), another.my_member.public_key, {'id': 42}) another.give_message(another.receive_message(na...
'Test that a crawl is not send multiple times when a crawl is already happening as a result of an incoming block'
def test_crawl_not_double(self):
(node, other, another) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) node.call(node.community.sign_block, self._create_target(node, another), another.my_member.public_key, {'id': 42}) message = another.receive_message(names=[HALF_B...
'Test that a crawl is requested and serviced if the signer cannot validate the previous hash of a request'
def test_crawl_on_partial_complete(self):
(node, other, another) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) TestTrustChainCommunity.create_block(node, another, self._create_target(node, another), {'id': 42}) self.assertBlocksInDatabase(node, 4) self.assertBlocksInDa...
'Test the crawler to request the latest block.'
def test_crawl_block_latest(self):
(node, other, crawler) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) TestTrustChainCommunity.crawl_node(crawler, node, self._create_target(crawler, node)) self.assertBlocksInDatabase(node, 2) self.assertBlocksInDatabase(crawler...
'Test the crawler to fetch a block with a specified sequence number.'
def test_crawl_block_specified_sequence_number(self):
(node, other, crawler) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) TestTrustChainCommunity.crawl_node(crawler, node, self._create_target(crawler, node), GENESIS_SEQ) self.assertBlocksInDatabase(node, 2) self.assertBlocksInDat...
'Test the crawler to fetch blocks starting from a negative sequence number.'
def test_crawl_blocks_negative_sequence_number(self):
(node, other, crawler) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {}) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {}) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other)...
'Test crawl without a block.'
def test_crawl_no_block(self):
(node, crawler) = self.create_nodes(2) TestTrustChainCommunity.crawl_node(crawler, node, self._create_target(crawler, node)) self.assertBlocksInDatabase(node, 0) self.assertBlocksInDatabase(crawler, 0)
'Test the crawler to request a known block.'
def test_crawl_block_known(self):
(node, other, crawler) = self.create_nodes(3) TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), {'id': 42}) TestTrustChainCommunity.crawl_node(crawler, other, self._create_target(crawler, other)) TestTrustChainCommunity.crawl_node(crawler, node, self._create_target(craw...
'Test the crawler for fetching multiple blocks in one crawl.'
def test_crawl_batch(self):
(node, other, crawler) = self.create_nodes(3) target_other = self._create_target(node, other) TestTrustChainCommunity.create_block(node, other, target_other, {'id': 42}) TestTrustChainCommunity.create_block(node, other, target_other, {'id': 42}) TestTrustChainCommunity.crawl_node(crawler, node, self...
'Test that the trust nodes have for each other is the sum of the length of both chains.'
def test_get_trust(self):
(node, other) = self.create_nodes(2) transaction = {} TestTrustChainCommunity.create_block(node, other, self._create_target(node, other), transaction) TestTrustChainCommunity.create_block(other, node, self._create_target(other, node), transaction) node_trust = blockingCallFromThread(reactor, node.co...
'Test that the trust between nodes without blocks is 1.'
def test_get_default_trust(self):
(node, other) = self.create_nodes(2) node_trust = blockingCallFromThread(reactor, node.community.get_trust, other.community.my_member) other_trust = blockingCallFromThread(reactor, other.community.get_trust, node.community.my_member) self.assertEqual(node_trust, 1) self.assertEqual(other_trust, 1)
'A node without trust for anyone should still find a candidate.'
def test_live_edge_bootstrapping(self):
(node, other) = self.create_nodes(2) candidate = node.community.create_or_update_walkcandidate(other.my_candidate.sock_addr, other.my_candidate.sock_addr, ('0.0.0.0', 0), other.my_candidate.tunnel, u'unknown') candidate.associate(other.community.my_member) candidate.walk_response(time.time()) intro ...
'Live edges should never include invalid/old candidates.'
def test_live_edge_recommend_valid(self):
(node, other, another) = self.create_nodes(3) node.community.cancel_all_pending_tasks() node.community.reset_live_edges() node.community.candidates.clear() candidate = node.community.create_or_update_walkcandidate(other.my_candidate.sock_addr, other.my_candidate.sock_addr, ('0.0.0.0', 0), other.my_c...
'Test live edges start with my member.'
def test_live_edge_callback_no_candidates(self):
(node,) = self.create_nodes(1) def check_live_edge(edge_id, candidates): self.assertEqual(1, edge_id) self.assertEqual(node.my_member.mid, candidates[0].get_member().mid) check_live_edge.called = True node.community.set_live_edge_callback(check_live_edge) node.community.cancel_al...
'Test creation and handling of a new live edge.'
def test_live_edge_callback(self):
(node, other) = self.create_nodes(2) cache = object.__new__(IntroductionRequestCache) blockingCallFromThread(reactor, IntroductionRequestCache.__init__, cache, node.community, other.my_candidate.sock_addr) cache = blockingCallFromThread(reactor, node.community.request_cache.add, cache) response = ot...
'Test the waiting for an introduction candidate'
@blocking_call_on_reactor_thread @inlineCallbacks def test_wait_for_intro_candidate(self):
mock_candidate = MockObject() mock_candidate.sock_addr = None (node,) = (yield self.create_nodes(1)) deferred = node.community.wait_for_intro_of_candidate(mock_candidate) node.community.expected_intro_responses[mock_candidate.sock_addr].callback(None) (yield deferred)
'Test the waiting for a signature request'
@blocking_call_on_reactor_thread @inlineCallbacks def test_wait_for_signature_request(self):
(node,) = (yield self.create_nodes(1)) deferred = node.community.wait_for_signature_request('a') node.community.expected_sig_requests['a'].callback(None) (yield deferred)
'Function to assertEqual two blocks'
def assertEqual_block(self, expected_block, actual_block):
crypto = ECCrypto() self.assertTrue((expected_block is not None)) self.assertTrue((actual_block is not None)) self.assertTrue(crypto.is_valid_public_bin(expected_block.public_key)) self.assertTrue(crypto.is_valid_public_bin(actual_block.public_key)) self.assertDictEqual(expected_block.transactio...
'Test encoding of a signed message'
def test_encoding_decoding_half_block(self):
meta = self.community.get_meta_message(HALF_BLOCK) message = meta.impl(distribution=(self.community.claim_global_time(),), payload=(self.block,)) encoded_message = self.converter._encode_half_block(message)[0] result = self.converter._decode_half_block(TestPlaceholder(meta), 0, encoded_message)[1] s...
'Test if a responder can send a signature message with big total_up and down.'
def test_encoding_decoding_half_block_big_number(self):
meta = self.community.get_meta_message(HALF_BLOCK) block = TestBlock() block.total_up_requester = pow(2, 63) block.total_down_requester = pow(2, 62) block.total_up_responder = pow(2, 61) block.total_down_responder = pow(2, 60) message = meta.impl(distribution=(self.community.claim_global_tim...
'Test decoding a signature message with wrong size'
def test_decoding_half_block_wrong_size(self):
meta = self.community.get_meta_message(HALF_BLOCK) message = meta.impl(distribution=(self.community.claim_global_time(),), payload=(self.block,)) encoded_message = self.converter._encode_half_block(message)[0] with self.assertRaises(DropPacket): self.converter._decode_half_block(TestPlaceholder(...
'Test if a requester can send a crawl request message.'
def test_encoding_decoding_crawl_request(self):
meta = self.community.get_meta_message(CRAWL) requested_sequence_number = 500 message = meta.impl(distribution=(self.community.claim_global_time(),), payload=(requested_sequence_number,)) encoded_message = self.converter._encode_crawl_request(message)[0] result = self.converter._decode_crawl_request...
'Test if a DropPacket is raised when the crawl request size is wrong.'
def test_decoding_crawl_request_wrong_size(self):
meta = self.community.get_meta_message(CRAWL) requested_sequence_number = 500 message = meta.impl(distribution=(self.community.claim_global_time(),), payload=(requested_sequence_number,)) encoded_message = self.converter._encode_crawl_request(message)[0] with self.assertRaises(DropPacket): s...
'Test if the block can save very large numbers.'
@blocking_call_on_reactor_thread def test_save_large_upload_download_block(self):
self.block1.total_up = long(pow(2, 62)) self.block1.total_down = long(pow(2, 62)) self.db.add_block(self.block1) result = self.db.get_latest(self.block1.public_key) self.assertEqual_block(self.block1, result)
'Test whether a block is correctly represented when converted to a dictionary'
@blocking_call_on_reactor_thread def test_block_to_dictionary(self):
block_dict = dict(self.block1) self.assertDictEqual(block_dict['transaction'], {'id': 42}) self.assertEqual(block_dict['insert_time'], self.block1.insert_time)
'Test whether the should_sign method return False when there is no market community'
def test_should_sign_no_market(self):
(node,) = self.create_nodes(1) self.assertFalse(node.community.should_sign(None))
'Test whether the right methods are called when tunneling data over a circuit'
def test_circuit_tunnel_data(self):
proxy = HiddenTunnelCommunity.__new__(HiddenTunnelCommunity) proxy.stats = {'bytes_up': 0} proxy.send_data = (lambda *_: 3) circuit = Circuit(1234L, 3, proxy=proxy, first_hop=('1.2.3.5', 1235)) circuit.tunnel_data(('1.2.3.4', 1234), 'abcd') proxy.send_data = (lambda *_: 0) circuit.tunnel_dat...
'Test the creation of an introduction point with an unexisting download'
@blocking_call_on_reactor_thread def test_create_intro_no_download(self):
self.tunnel_community.find_download = (lambda _: None) self.tunnel_community.create_introduction_point(('a' * 20))