raw
9982-getdata            1 import time
9982-getdata 2 import binascii
9982-getdata 3 import hashlib
9982-getdata 4 import logging
9982-getdata 5 from message import Message
9982-getdata 6 from message import OUTGOING_MESSAGE_LOGGING_FORMAT
9982-getdata 7 from commands import GETDATA
9982-getdata 8 from commands import DIRECT
9982-getdata 9 from commands import BROADCAST
9982-getdata 10 from commands import COMMAND_LABELS
9982-getdata 11
9982-getdata 12 class GetData(Message):
9982-getdata 13 def __init__(self, original, broken_chain, state=None):
9982-getdata 14 message = {
9982-getdata 15 'command': GETDATA,
9982-getdata 16 'body': original[broken_chain],
9982-getdata 17 'timestamp': int(time.time()),
9982-getdata 18 'speaker': state.get_knob('nick'),
9982-getdata 19 'bounces': 0,
9982-getdata 20 'original': original
9982-getdata 21 }
9982-getdata 22 super(GetData, self).__init__(message, state)
9982-getdata 23
9982-getdata 24 def send(self):
9982-getdata 25 target_peer = (self.state.get_peer_by_handle(self.original['speaker'])
9982-getdata 26 if self.original['command'] == DIRECT
9982-getdata 27 else None)
9982-getdata 28
9982-getdata 29 if self.original['command'] == DIRECT and target_peer == None:
9982-getdata 30 logging.debug("Aborting message: unknown handle: %s" % self.handle)
9982-getdata 31 return
9982-getdata 32
9982-getdata 33 if target_peer and not target_peer.get_key():
9982-getdata 34 logging.debug("No key for peer associated with %s" % self.handle)
9982-getdata 35 return
9982-getdata 36
9982-getdata 37 if self.state.get_knob('nick') is None:
9982-getdata 38 logging.error("unable to pack message due to null speaker value")
9982-getdata 39 return
9982-getdata 40
9982-getdata 41 self.message_bytes = self.get_message_bytes(target_peer)
9982-getdata 42 self.message_hash = hashlib.sha256(self.message_bytes).digest()
9982-getdata 43
9982-getdata 44
9982-getdata 45 if self.original['command'] == DIRECT:
9982-getdata 46 signed_packet_bytes = self.pack(target_peer,
9982-getdata 47 self.command,
9982-getdata 48 self.bounces,
9982-getdata 49 self.message_bytes)
9982-getdata 50 target_peer.send(signed_packet_bytes)
9982-getdata 51 self.log_outgoing(target_peer)
9982-getdata 52
9982-getdata 53 elif self.original['command'] == BROADCAST:
9982-getdata 54 for peer in self.state.get_keyed_peers(exclude_addressless=True):
9982-getdata 55 signed_packet_bytes = self.pack(peer, self.command, self.bounces, self.message_bytes)
9982-getdata 56 peer.send(signed_packet_bytes)
9982-getdata 57 self.log_outgoing(peer)
9982-getdata 58
9982-getdata 59 def log_outgoing(self, peer):
9982-getdata 60 logging.info(OUTGOING_MESSAGE_LOGGING_FORMAT % (peer.address,
9982-getdata 61 peer.port,
9982-getdata 62 peer.handles[0],
9982-getdata 63 COMMAND_LABELS[self.command],
9982-getdata 64 binascii.hexlify(self.body),
9982-getdata 65 self.bounces,
9982-getdata 66 binascii.hexlify(self.message_hash)))