Example #1
0
 def _on_incoming_suppliers_list(self, inp):
     # this packet came from another supplier who belongs to that family also
     incoming_packet = inp['packet']
     if _Debug:
         lg.out(
             _DebugLevel,
             'family_member._on_incoming_suppliers_list with %s' %
             incoming_packet)
     if not self.my_info:
         if _Debug:
             lg.out(_DebugLevel,
                    '    current DHT info is not yet known, skip')
         return p2p_service.SendAck(incoming_packet)
     try:
         another_ecc_map = inp['customer_ecc_map']
         another_suppliers_list = inp['suppliers_list']
         another_revision = int(inp['transaction_revision'])
     except:
         lg.exc()
         return p2p_service.SendFail(incoming_packet,
                                     response=serialization.DictToBytes(
                                         self.my_info))
     if _Debug:
         lg.out(
             _DebugLevel,
             '    another_revision=%d   another_ecc_map=%s   another_suppliers_list=%r'
             % (another_revision, another_ecc_map, another_suppliers_list))
     if another_revision >= int(self.my_info['revision']):
         self.my_info = self._do_create_revision_from_another_supplier(
             another_revision, another_suppliers_list, another_ecc_map)
         lg.info(
             'another supplier have more fresh revision, update my info and raise "family-refresh" event'
         )
         self.automat('family-refresh')
         return p2p_service.SendAck(incoming_packet)
     if my_id.getLocalIDURL() not in another_suppliers_list:
         lg.warn(
             'another supplier is trying to remove my IDURL from the family of customer %s'
             % self.customer_idurl)
         return p2p_service.SendFail(incoming_packet,
                                     response=serialization.DictToBytes(
                                         self.my_info))
     my_position_in_transaction = another_suppliers_list.index(
         my_id.getLocalIDURL())
     my_known_position = self.my_info['suppliers'].index(
         my_id.getLocalIDURL())
     if my_position_in_transaction != my_known_position:
         lg.warn(
             'another supplier is trying to put my IDURL on another position in the family of customer %s'
             % self.customer_idurl)
         return p2p_service.SendFail(incoming_packet,
                                     response=serialization.DictToBytes(
                                         self.my_info))
     return p2p_service.SendAck(incoming_packet)
Example #2
0
def encrypt_json(raw_data, secret_bytes_key, cipher_type='AES'):
    # TODO: add salt to raw_data
    padded_data = Padding.pad(
        data_to_pad=raw_data,
        block_size=AES.block_size,
    )
    if cipher_type == 'AES':
        cipher = AES.new(
            key=secret_bytes_key,
            mode=AES.MODE_CBC,
        )
    elif cipher_type == 'DES3':
        cipher = DES3.new(
            key=secret_bytes_key,
            mode=DES3.MODE_CBC,
        )
    else:
        raise Exception('unsupported cipher type')
    ct_bytes = cipher.encrypt(padded_data)
    dct = {
        'iv': base64.b64encode(cipher.iv).decode('utf-8'),
        'ct': base64.b64encode(ct_bytes).decode('utf-8'),
    }
    encrypted_data = serialization.DictToBytes(dct, encoding='utf-8')
    return encrypted_data
Example #3
0
def SendRequestService(remote_idurl,
                       service_name,
                       json_payload={},
                       wide=False,
                       callbacks={},
                       timeout=60):
    service_info = {
        'name': service_name,
        'payload': json_payload,
    }
    service_info_raw = serialization.DictToBytes(service_info)
    if _Debug:
        lg.out(
            _DebugLevel,
            'p2p_service.SendRequestService "%s" to %s with %d bytes' % (
                service_name,
                remote_idurl,
                len(service_info_raw),
            ))
    result = signed.Packet(
        Command=commands.RequestService(),
        OwnerID=my_id.getLocalID(),
        CreatorID=my_id.getLocalID(),
        PacketID=packetid.UniqueID(),
        Payload=service_info_raw,
        RemoteID=remote_idurl,
    )
    gateway.outbox(result,
                   wide=wide,
                   callbacks=callbacks,
                   response_timeout=timeout)
    return result
Example #4
0
def SendEvent(remote_idurl, event_id, payload=None,
              producer_id=None, message_id=None, created=None,
              packet_id=None, wide=False, callbacks={}, response_timeout=5):
    if packet_id is None:
        packet_id = packetid.UniqueID()
    e_json = {
        'event_id': event_id,
        'payload': payload,
    }
    if producer_id and message_id:
        e_json['producer_id'] = producer_id
        e_json['message_id'] = message_id
    if created:
        e_json['created'] = created
    e_json_src = serialization.DictToBytes(e_json)
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendEvent to %s with %d bytes message json data" % (
            remote_idurl, len(e_json_src)))
    outpacket = signed.Packet(
        Command=commands.Event(),
        OwnerID=my_id.getLocalID(),
        CreatorID=my_id.getLocalID(),
        PacketID=packet_id,
        Payload=e_json_src,
        RemoteID=remote_idurl,
    )
    gateway.outbox(outpacket, wide=wide, callbacks=callbacks, response_timeout=response_timeout)
    return outpacket
Example #5
0
 def Serialize(self):
     """
     Create a string that stores all data fields of that ``encrypted.Block``
     object.
     """
     return serialization.DictToBytes({
         'c':
         self.CreatorID,
         'b':
         self.BackupID,
         'n':
         self.BlockNumber,
         'e':
         self.LastBlock,
         'k':
         base64.b64encode(self.EncryptedSessionKey).decode('utf-8'),
         't':
         self.SessionKeyType,
         'l':
         self.Length,
         'p':
         self.EncryptedData,
         's':
         self.Signature,
     })
Example #6
0
 def doSendMyListFiles(self, *args, **kwargs):
     """
     Action method.
     """
     json_list_files = backup_fs.Serialize(
         to_json=True,
         filter_cb=lambda path_id, path, info: True if strng.to_text(info.key_id) == strng.to_text(self.key_id) else False,
     )
     # raw_list_files = json.dumps(json_list_files, indent=2, encoding='utf-8')
     raw_list_files = serialization.DictToBytes(json_list_files, keys_to_text=True, values_to_text=True)
     if _Debug:
         lg.out(_DebugLevel, 'shared_access_donor.doSendMyListFiles prepared list of files for %s :\n%s' % (
             self.remote_idurl, raw_list_files))
     block = encrypted.Block(
         CreatorID=my_id.getLocalID(),
         BackupID=self.key_id,
         Data=raw_list_files,
         SessionKey=key.NewSessionKey(),
         EncryptKey=self.key_id,
     )
     encrypted_list_files = block.Serialize()
     packet_id = "%s:%s" % (self.key_id, packetid.UniqueID(), )
     p2p_service.SendFiles(
         idurl=self.remote_idurl,
         raw_list_files_info=encrypted_list_files,
         packet_id=packet_id,
         callbacks={
             commands.Ack(): lambda response, _: self.automat('list-files-ok', response),
             commands.Fail(): lambda response, _: self.automat('fail', Exception(str(response))),
             None: lambda pkt_out: self.automat('fail', Exception('timeout')),
         },
     )
Example #7
0
def SendContacts(remote_idurl, json_payload={}, wide=False, callbacks={}):
    """
    """
    MyID = my_id.getLocalID()
    if _Debug:
        lg.out(
            _DebugLevel,
            "p2p_service.SendContacts to %s" % nameurl.GetName(remote_idurl))
    PacketID = packetid.UniqueID()
    try:
        json_payload['type']
        json_payload['space']
    except:
        lg.err()
        return None
    Payload = serialization.DictToBytes(json_payload)
    result = signed.Packet(
        Command=commands.Contacts(),
        OwnerID=MyID,
        CreatorID=MyID,
        PacketID=PacketID,
        Payload=Payload,
        RemoteID=remote_idurl,
    )
    gateway.outbox(result, wide=wide, callbacks=callbacks)
    return result
Example #8
0
def SendCancelService(remote_idurl,
                      service_name,
                      json_payload={},
                      wide=False,
                      callbacks={}):
    service_info = {
        'name': service_name,
        'payload': json_payload,
    }
    service_info_raw = serialization.DictToBytes(service_info)
    if _Debug:
        lg.out(
            _DebugLevel,
            'p2p_service.SendCancelService "%s" to %s with %d bytes payload' %
            (service_name, remote_idurl, len(service_info_raw)))
    result = signed.Packet(
        commands.CancelService(),
        my_id.getLocalID(),
        my_id.getLocalID(),
        packetid.UniqueID(),
        service_info_raw,
        remote_idurl,
    )
    gateway.outbox(result, wide=wide, callbacks=callbacks)
    return result
Example #9
0
 def _do_send_request_service(self, *args, **kwargs):
     if len(self.request_service_packet_id) >= 10:
         if _Debug:
             lg.warn('too many service requests to %r' % self.router_idurl)
         self.automat('service-refused', *args, **kwargs)
         return
     orig_identity = config.conf().getData('services/proxy-transport/my-original-identity').strip()
     if not orig_identity:
         orig_identity = my_id.getLocalIdentity().serialize(as_text=True)
     service_info = {
         'name': 'service_proxy_server',
         'payload': {
             'identity': orig_identity,
         },
     }
     newpacket = signed.Packet(
         commands.RequestService(),
         my_id.getIDURL(),
         my_id.getIDURL(),
         packetid.UniqueID(),
         serialization.DictToBytes(service_info, values_to_text=True),
         self.router_idurl,
     )
     packet_out.create(
         newpacket,
         wide=False,
         callbacks={
             commands.Ack(): self._on_request_service_ack,
             commands.Fail(): self._on_request_service_fail,
             None: lambda pkt_out: self.automat('request-timeout', pkt_out),
         },
         response_timeout=30,
     )
     self.request_service_packet_id.append(newpacket.PacketID)
Example #10
0
 def Serialize(self):
     """
     Create a string that stores all data fields of that ``encrypted.Block``
     object.
     """
     dct = {
         'c':
         self.CreatorID,
         'b':
         self.BackupID,
         'n':
         self.BlockNumber,
         'e':
         self.LastBlock,
         'k':
         strng.to_text(
             base64.b64encode(strng.to_bin(self.EncryptedSessionKey))),
         't':
         self.SessionKeyType,
         'l':
         self.Length,
         'p':
         self.EncryptedData,
         's':
         self.Signature,
     }
     if _Debug:
         lg.out(_DebugLevel, 'encrypted.Serialize %r' % dct)
     return serialization.DictToBytes(dct, encoding='utf-8')
Example #11
0
def audit_private_key(key_id, untrusted_idurl, timeout=10):
    """
    Be sure remote user posses given private key.
    I need to posses the public key to be able to audit.
    I will generate a random string, encrypt it with given key public key and send encrypted string to him.
    He will decrypt and send me back original string.
    Returns Deferred object.
    """
    if _Debug:
        lg.out(_DebugLevel, 'key_ring.audit_private_key   testing %s from %s' % (key_id, untrusted_idurl))
    result = Deferred()
    recipient_id_obj = identitycache.FromCache(untrusted_idurl)
    if not recipient_id_obj:
        lg.warn('not found "%s" in identity cache' % untrusted_idurl)
        result.errback(Exception('not found "%s" in identity cache' % untrusted_idurl))
        return result
    key_alias, creator_idurl = my_keys.split_key_id(key_id)
    if not key_alias or not creator_idurl:
        lg.warn('wrong key_id')
        result.errback(Exception('wrong key_id'))
        return result
    private_test_sample = key.NewSessionKey()
    if untrusted_idurl == creator_idurl and key_alias == 'master':
        lg.warn('doing audit of master key (private part) of remote user')
        private_test_encrypted_sample = recipient_id_obj.encrypt(private_test_sample)
    else:
        if not my_keys.is_key_registered(key_id):
            lg.warn('unknown key: "%s"' % key_id)
            result.errback(Exception('unknown key: "%s"' % key_id))
            return result
        private_test_encrypted_sample = my_keys.encrypt(key_id, private_test_sample)
    json_payload = {
        'key_id': key_id,
        'audit': {
            'public_sample': '',
            'private_sample': base64.b64encode(private_test_encrypted_sample),
        }
    }
    raw_payload = serialization.DictToBytes(json_payload, values_to_text=True)
    block = encrypted.Block(
        BackupID=key_id,
        Data=raw_payload,
        SessionKey=key.NewSessionKey(),
        # encrypt data using public key of recipient
        EncryptKey=lambda inp: recipient_id_obj.encrypt(inp),
    )
    encrypted_payload = block.Serialize()
    p2p_service.SendAuditKey(
        remote_idurl=recipient_id_obj.getIDURL(),
        encrypted_payload=encrypted_payload,
        packet_id=key_id,
        timeout=timeout,
        callbacks={
            commands.Ack(): lambda response, info:
                _on_audit_private_key_response(response, info, key_id, untrusted_idurl, private_test_sample, result),
            commands.Fail(): lambda response, info: result.errback(Exception(response)),
            None: lambda pkt_out: result.errback(Exception('timeout')),  # timeout
        },
    )
    return result
Example #12
0
 def serialize(self):
     dct = {
         'r': self.recipient,
         's': self.sender,
         'k': self.encrypted_session,
         'p': self.encrypted_body,
     }
     return serialization.DictToBytes(dct, encoding='utf-8')
Example #13
0
 def serialize(self):
     dct = {
         'r': self.recipient,
         's': self.sender,
         'k': strng.to_text(base64.b64encode(strng.to_bin(self.encrypted_session))),
         'p': self.encrypted_body,
     }
     return serialization.DictToBytes(dct, encoding='utf-8')
Example #14
0
def transfer_key(key_id, trusted_idurl, include_private=False, include_signature=False, timeout=10, result=None):
    """
    Actually sending given key to remote user.
    """
    if _Debug:
        lg.out(_DebugLevel, 'key_ring.transfer_key  %s -> %s' % (key_id, trusted_idurl))
    if not result:
        result = Deferred()
    recipient_id_obj = identitycache.FromCache(trusted_idurl)
    if not recipient_id_obj:
        lg.warn('not found "%s" in identity cache' % trusted_idurl)
        result.errback(Exception('not found "%s" in identity cache' % trusted_idurl))
        return result
    key_alias, creator_idurl = my_keys.split_key_id(key_id)
    if not key_alias or not creator_idurl:
        lg.warn('wrong key_id')
        result.errback(Exception('wrong key_id'))
        return result
    if not my_keys.is_key_registered(key_id):
        lg.warn('unknown key: "%s"' % key_id)
        result.errback(Exception('unknown key: "%s"' % key_id))
        return result
    key_object = my_keys.key_obj(key_id)
    try:
        key_json = my_keys.make_key_info(
            key_object,
            key_id=key_id,
            include_private=include_private,
            include_signature=include_signature,
        )
    except Exception as exc:
        lg.exc()
        result.errback(exc)
        return result
    key_data = serialization.DictToBytes(key_json, values_to_text=True)
    block = encrypted.Block(
        BackupID=key_id,
        Data=key_data,
        SessionKey=key.NewSessionKey(session_key_type=key.SessionKeyType()),
        SessionKeyType=key.SessionKeyType(),
        # encrypt data using public key of recipient
        EncryptKey=lambda inp: recipient_id_obj.encrypt(inp),
    )
    encrypted_key_data = block.Serialize()
    p2p_service.SendKey(
        remote_idurl=recipient_id_obj.getIDURL(),
        encrypted_key_data=encrypted_key_data,
        packet_id=key_id,
        callbacks={
            commands.Ack(): lambda response, info: _on_transfer_key_response(response, info, key_id, result),
            commands.Fail(): lambda response, info: _on_transfer_key_response(response, info, key_id, result),
            None: lambda pkt_out: _on_transfer_key_response(None, None, key_id, result),
        },
        timeout=timeout,
    )
    return result
Example #15
0
def do_send_message(json_data, recipient_global_id, packet_id, message_ack_timeout, result_defer=None, fire_callbacks=True):
    global _OutgoingMessageCallbacks
    remote_idurl = global_id.GlobalUserToIDURL(recipient_global_id, as_field=False)
    if not remote_idurl:
        raise Exception('invalid recipient')
    remote_identity = identitycache.FromCache(remote_idurl)
    if not remote_identity:
        raise Exception('remote identity object not exist in cache')
    message_body = serialization.DictToBytes(
        json_data,
        pack_types=True,
        encoding='utf-8',
    )
    if _Debug:
        lg.out(_DebugLevel, "message.do_send_message to %s with %d bytes message ack_timeout=%s" % (
            recipient_global_id, len(message_body), message_ack_timeout))
    try:
        private_message_object = PrivateMessage(recipient=recipient_global_id)
        private_message_object.encrypt(message_body)
    except:
        lg.exc()
        raise Exception('message encryption failed')
    payload = private_message_object.serialize()
    if _Debug:
        lg.out(_DebugLevel, "        payload is %d bytes, remote idurl is %s" % (len(payload), remote_idurl))
    callbacks = {}
    if message_ack_timeout:
        callbacks = {
            commands.Ack(): lambda response, info: on_message_delivered(
                remote_idurl, json_data, recipient_global_id, packet_id, response, info, result_defer, ),
            commands.Fail(): lambda response, info: on_message_failed(
                remote_idurl, json_data, recipient_global_id, packet_id, response, info,
                result_defer=result_defer, error='fail received'),
            None: lambda pkt_out: on_message_failed(
                remote_idurl, json_data, recipient_global_id, packet_id, None, None,
                result_defer=result_defer, error='timeout', ),
            'failed': lambda pkt_out, errmsg: on_message_failed(
                remote_idurl, json_data, recipient_global_id, packet_id, None, None,
                result_defer=result_defer, error=errmsg, ),
        }
    result, outpacket = p2p_service.SendMessage(
        remote_idurl=remote_idurl,
        packet_id=packet_id,
        payload=payload,
        callbacks=callbacks,
        response_timeout=message_ack_timeout,
    )
    if fire_callbacks:
        try:
            for cp in _OutgoingMessageCallbacks:
                cp(json_data, private_message_object, remote_identity, outpacket, result)
        except:
            lg.exc()
            raise Exception('failed sending message')
    return result
Example #16
0
def SendCoin(remote_idurl, coins, packet_id=None, wide=False, callbacks={}):
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendCoin to %s with %d records" % (remote_idurl, len(coins)))
    if packet_id is None:
        packet_id = packetid.UniqueID()
    outpacket = signed.Packet(
        commands.Coin(), my_id.getLocalID(),
        my_id.getLocalID(), packet_id,
        serialization.DictToBytes(coins), remote_idurl)
    gateway.outbox(outpacket, wide=wide, callbacks=callbacks)
    return outpacket
Example #17
0
 def test_serialization(self):
     data1 = os.urandom(1024)
     dct1 = {
         'd': {
             'data': data1,
         },
     }
     raw = serialization.DictToBytes(dct1, encoding='latin1')
     dct2 = serialization.BytesToDict(raw, encoding='latin1')
     data2 = dct2['d']['data']
     self.assertEqual(data1, data2)
Example #18
0
 def test_serialization(self):
     from lib import serialization
     data1 = os.urandom(1024)
     dct1 = {
         'd': {
             'data': data1,
         },
     }
     raw = serialization.DictToBytes(dct1)
     dct2 = serialization.BytesToDict(raw)
     data2 = dct2['d']['data']
     self.assertEqual(data1, data2)
Example #19
0
def push(json_data):
    global _WebSocketTransport
    if not _WebSocketTransport:
        return False
    raw_bytes = serialization.DictToBytes(json_data)
    _WebSocketTransport.write(raw_bytes)
    if _Debug:
        lg.dbg(_DebugLevel, 'sent %d bytes to web socket: %r' % (len(raw_bytes), json_data))
    if _Debug:
        lg.out(0, '***   API WS PUSH  %d bytes : %r' % (len(json_data), json_data, ))
    if _APILogFileEnabled:
        lg.out(0, '*** WS PUSH  %d bytes : %r' % (len(json_data), json_data, ), log_name='api', showtime=True)
    return True
Example #20
0
def encrypt_json(raw_data, secret_16bytes_key):
    # TODO: add salt to raw_data
    cipher = AES.new(
        key=secret_16bytes_key,
        mode=AES.MODE_CBC,
    )
    ct_bytes = cipher.encrypt(Padding.pad(raw_data, AES.block_size))
    dct = {
        'iv': base64.b64encode(cipher.iv).decode('utf-8'),
        'ct': base64.b64encode(ct_bytes).decode('utf-8'),
    }
    raw = serialization.DictToBytes(dct)
    return raw
Example #21
0
def SendRetrieveCoin(remote_idurl, query, wide=False, callbacks={}):
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendRetrieveCoin to %s" % remote_idurl)
    outpacket = signed.Packet(
        commands.RetrieveCoin(),
        my_id.getLocalID(),
        my_id.getLocalID(),
        packetid.UniqueID(),
        serialization.DictToBytes(query),
        remote_idurl,
    )
    gateway.outbox(outpacket, wide=wide, callbacks=callbacks)
    return outpacket
Example #22
0
def SendRetrieveCoin(remote_idurl, query, wide=False, callbacks={}):
    if _Debug:
        lg.out(_DebugLevel,
               "p2p_service.SendRetrieveCoin to %s" % remote_idurl)
    outpacket = signed.Packet(
        Command=commands.RetrieveCoin(),
        OwnerID=my_id.getIDURL(),
        CreatorID=my_id.getIDURL(),
        PacketID=packetid.UniqueID(),
        Payload=serialization.DictToBytes(query),
        RemoteID=remote_idurl,
    )
    gateway.outbox(outpacket, wide=wide, callbacks=callbacks)
    return outpacket
Example #23
0
def SendCoin(remote_idurl, coins, packet_id=None, wide=False, callbacks={}):
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendCoin to %s with %d records" % (remote_idurl, len(coins)))
    if packet_id is None:
        packet_id = packetid.UniqueID()
    outpacket = signed.Packet(
        Command=commands.Coin(),
        OwnerID=my_id.getLocalID(),
        CreatorID=my_id.getLocalID(),
        PacketID=packet_id,
        Payload=serialization.DictToBytes(coins, keys_to_text=True),
        RemoteID=remote_idurl,
    )
    gateway.outbox(outpacket, wide=wide, callbacks=callbacks)
    return outpacket
Example #24
0
 def doSendCancelService(self, *args, **kwargs):
     """
     Action method.
     """
     newpacket = signed.Packet(
         commands.CancelService(),
         my_id.getIDURL(),
         my_id.getIDURL(),
         packetid.UniqueID(),
         serialization.DictToBytes({'name': 'service_proxy_server', }),
         self.router_idurl,
     )
     packet_out.create(newpacket, wide=True, callbacks={
         commands.Ack(): self._on_request_service_ack,
         commands.Fail(): self._on_request_service_fail,
     })
Example #25
0
def encrypt_json(raw_data, secret_16bytes_key):
    # TODO: add salt to raw_data
    padded_data = Padding.pad(
        data_to_pad=raw_data,
        block_size=AES.block_size,
    )
    cipher = AES.new(
        key=secret_16bytes_key,
        mode=AES.MODE_CBC,
    )
    ct_bytes = cipher.encrypt(padded_data)
    dct = {
        'iv': base64.b64encode(cipher.iv).decode('utf-8'),
        'ct': base64.b64encode(ct_bytes).decode('utf-8'),
    }
    encrypted_data = serialization.DictToBytes(dct, encoding='utf-8')
    return encrypted_data
Example #26
0
 def _write_route(self, user_id):
     src = config.conf().getData('services/proxy-server/current-routes')
     try:
         dct = serialization.BytesToDict(strng.to_bin(src),
                                         keys_to_text=True,
                                         values_to_text=True)
     except:
         dct = {}
     dct[user_id] = self.routes[user_id]
     newsrc = strng.to_text(
         serialization.DictToBytes(dct,
                                   keys_to_text=True,
                                   values_to_text=True))
     config.conf().setData('services/proxy-server/current-routes', newsrc)
     if _Debug:
         lg.out(_DebugLevel,
                'proxy_router._write_route %d bytes wrote' % len(newsrc))
Example #27
0
def push_signed_message(producer_id, queue_id, data, creation_time=None):
    try:
        signed_data = signed.Packet(
            Command=commands.Event(),
            OwnerID=producer_id,
            CreatorID=producer_id,
            PacketID=packetid.UniqueID(),
            Payload=serialization.DictToBytes(data, keys_to_text=True),
            RemoteID=queue_id,
            KeyID=producer_id,
        )
    except:
        lg.exc()
        raise Exception('sign message failed')
    return push_message(producer_id,
                        queue_id,
                        data=signed_data.Serialize(),
                        creation_time=creation_time)
Example #28
0
 def _do_send_message_to_broker(self, json_payload=None, packet_id=None):
     if packet_id is None:
         packet_id = packetid.UniqueID()
     if _Debug:
         lg.args(_DebugLevel,
                 json_payload=json_payload,
                 packet_id=packet_id)
     raw_payload = serialization.DictToBytes(
         json_payload,
         pack_types=True,
         encoding='utf-8',
     )
     try:
         private_message_object = message.GroupMessage(
             recipient=self.group_key_id,
             sender=self.producer_id,
         )
         private_message_object.encrypt(raw_payload)
     except:
         lg.exc()
         raise Exception('message encryption failed')
     encrypted_payload = private_message_object.serialize()
     d = message.send_message(
         json_data={
             'msg_type': 'queue_message',
             'action': 'produce',
             'created': utime.get_sec1970(),
             'payload': encrypted_payload,
             'queue_id': self.active_queue_id,
             'producer_id': self.producer_id,
         },
         recipient_global_id=self.active_broker_id,
         packet_id=packetid.MakeQueueMessagePacketID(
             self.active_queue_id, packet_id),
         message_ack_timeout=config.conf().getInt(
             'services/private-groups/message-ack-timeout'),
         skip_handshake=True,
         fire_callbacks=False,
     )
     if _Debug:
         d.addErrback(lg.errback,
                      debug=_Debug,
                      debug_level=_DebugLevel,
                      method='message_producer._do_send_message_to_broker')
Example #29
0
def SendListFiles(target_supplier, customer_idurl=None, key_id=None, query_items=[], wide=False, callbacks={}, timeout=None):
    """
    This is used as a request method from your supplier : if you send him a ListFiles() packet
    he will reply you with a list of stored files in a Files() packet.
    """
    MyID = my_id.getLocalID()
    if not customer_idurl:
        customer_idurl = MyID
    if not str(target_supplier).isdigit():
        RemoteID = target_supplier
    else:
        RemoteID = contactsdb.supplier(target_supplier, customer_idurl=customer_idurl)
    if not RemoteID:
        lg.warn("RemoteID is empty target_supplier=%s" % str(target_supplier))
        return None
    if not key_id:
        # key_id = global_id.MakeGlobalID(idurl=customer_idurl, key_alias='customer')
        # TODO: due to issue with "customer" key backup/restore decided to always use my "master" key
        # to retrieve my list files info from supplier
        # expect remote user always poses my master public key from my identity.
        # probably require more work to build more reliable solution without using my master key at all
        # when my identity rotated supplier first needs to receive my new identity and then sending ListFiles()
        key_id = my_id.getGlobalID(key_alias='master')
    if not my_keys.is_key_registered(key_id) or not my_keys.is_key_private(key_id):
        lg.warn('key %r not exist or public, my "master" key to be used with ListFiles() packet' % key_id)
        key_id = my_id.getGlobalID(key_alias='master')
    PacketID = "%s:%s" % (key_id, packetid.UniqueID(), )
    if not query_items:
        query_items = ['*', ]
    Payload = serialization.DictToBytes({'items': query_items, })
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendListFiles %r to %s with query : %r" % (
            PacketID, nameurl.GetName(RemoteID), query_items, ))
    result = signed.Packet(
        Command=commands.ListFiles(),
        OwnerID=MyID,
        CreatorID=MyID,
        PacketID=PacketID,
        Payload=Payload,
        RemoteID=RemoteID,
    )
    gateway.outbox(result, wide=wide, callbacks=callbacks, response_timeout=timeout)
    return result
Example #30
0
 def Serialize(self):
     """
     Create a string from packet object.
     This is useful when need to save the packet on disk or send via network.
     """
     dct = {
         'm': self.Command,
         'o': self.OwnerID,
         'c': self.CreatorID,
         'i': self.PacketID,
         'd': self.Date,
         'p': self.Payload,
         'r': self.RemoteID,
         'k': self.KeyID,
         's': self.Signature,
     }        
     if _Debug:
         lg.out(_DebugLevel, 'signed.Serialize %r' % dct)
     src = serialization.DictToBytes(dct)
     return src