import time import binascii import hashlib import logging from message import Message from message import OUTGOING_MESSAGE_LOGGING_FORMAT from commands import GETDATA from commands import DIRECT from commands import BROADCAST from commands import COMMAND_LABELS class GetData(Message): def __init__(self, original, broken_chain, state=None): message = { 'command': GETDATA, 'body': original[broken_chain], 'timestamp': int(time.time()), 'speaker': state.get_knob('nick'), 'bounces': 0, 'original': original } super(GetData, self).__init__(message, state) def send(self): target_peer = (self.state.get_peer_by_handle(self.original['speaker']) if self.original['command'] == DIRECT else None) if self.original['command'] == DIRECT and target_peer == None: logging.debug("Aborting message: unknown handle: %s" % self.handle) return if target_peer and not target_peer.get_key(): logging.debug("No key for peer associated with %s" % self.handle) return if self.state.get_knob('nick') is None: logging.error("unable to pack message due to null speaker value") return self.message_bytes = self.get_message_bytes(target_peer) self.message_hash = hashlib.sha256(self.message_bytes).digest() if self.original['command'] == DIRECT: signed_packet_bytes = self.pack(target_peer, self.command, self.bounces, self.message_bytes) target_peer.send(signed_packet_bytes) self.log_outgoing(target_peer) elif self.original['command'] == BROADCAST: for peer in self.state.get_keyed_peers(exclude_addressless=True): signed_packet_bytes = self.pack(peer, self.command, self.bounces, self.message_bytes) peer.send(signed_packet_bytes) self.log_outgoing(peer) def log_outgoing(self, peer): logging.info(OUTGOING_MESSAGE_LOGGING_FORMAT % (peer.address, peer.port, peer.handles[0], COMMAND_LABELS[self.command], binascii.hexlify(self.body), self.bounces, binascii.hexlify(self.message_hash)))