Example #1
0
 def __init__(self):
     Envelope.__init__(self)
     self.header = MockHeaderSegment()
     self.trailer = MockTrailerSegment()
     self.items = self.body
     self.items.append(MockBDYHeaderSegment())
     self.items.append(MockBDZTrailerSegment())
Example #2
0
 def __init__(self):
     Envelope.__init__(self)
     self.header = MockHeaderSegment()
     self.trailer = MockTrailerSegment()
     self.items = self.body
     self.items.append(MockBDYHeaderSegment())
     self.items.append(MockBDZTrailerSegment())
Example #3
0
    def messages(self, topic, maxposts, before=None):
        """Get all messages in a topic, no later than `before`"""
        if topic != 'all':
            if isinstance(topic, str):
                topics = []
                topics.append(server.sorttopic(topic))
            elif isinstance(topic, list):
                topics = []
                for t in topic:
                    topics.append(server.sorttopic(t))
            sorttopic = {'envelope.local.sorttopic': {'$in': topics}}
        else:
            sorttopic = {'envelope.local.sorttopic': {'$exists': True}}

        # Don't do this in the def, so that our cache is respected.
        if before is None:
            before = TavernUtils.inttime()

        # Append our search topic query.
        subjects = []
        search = {'envelope.payload.class': 'message',
                  'envelope.payload.regarding': {'$exists': False},
                  'envelope.local.time_added': {'$lt': before}}
        search.update(sorttopic)
        for envelope in server.db.unsafe.find('envelopes', search, limit=maxposts, sortkey='envelope.local.time_added', sortdirection='descending'):
            e = Envelope()
            e.loaddict(envelope)
            subjects.append(e)

        return subjects
Example #4
0
 def getUsersPosts(self, pubkey, limit=1000):
     envelopes = []
     for envelope in self.db.safe.find('envelopes', {'envelope.local.author.pubkey': pubkey, 'envelope.payload.class': 'message'}, limit=limit, sortkey='envelope.local.time_added', sortdirection='descending'):
         messagetext = json.dumps(envelope, separators=(',', ':'))
         e = Envelope()
         e.loadstring(messagetext)
         envelopes.append(e)
     return envelopes
Example #5
0
    def getOriginalMessage(self, messageid):

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            if env.dict['envelope']['payload']['class'] == 'message':
                return env.dict['envelope']['local']['payload_sha512']
            else:
                return env.dict['envelope']['payload']['regarding']

        return None
Example #6
0
    def getOriginalMessage(self, messageid):

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            if env.dict['envelope']['payload']['class'] == 'message':
                return env.dict['envelope']['local']['payload_sha512']
            else:
                return env.dict['envelope']['payload']['regarding']

        return None
Example #7
0
    def _get_envelope(self, email_number):
        logging.info("loading email {}".format(email_number))
        response, email_data = self.mail.uid("fetch", email_number, "(RFC822.HEADER)")
        message = email.message_from_bytes(email_data[0][1])

        envelope = Envelope()
        envelope.number = email_number
        envelope.time = message["Date"]
        envelope.sender = self._decode(message["From"])
        envelope.subject = self._decode(message["Subject"])
        logging.info("loaded {}".format(envelope))
        return envelope
Example #8
0
 def getUsersPosts(self, pubkey, limit=1000):
     envelopes = []
     for envelope in self.db.safe.find('envelopes', {
             'envelope.local.author.pubkey': pubkey,
             'envelope.payload.class': 'message'
     },
                                       limit=limit,
                                       sortkey='envelope.local.time_added',
                                       sortdirection='descending'):
         messagetext = json.dumps(envelope, separators=(',', ':'))
         e = Envelope()
         e.loadstring(messagetext)
         envelopes.append(e)
     return envelopes
Example #9
0
def loaddir(directory=None, topic='sitecontent'):
    """Load in a directory full of Tavern Messages."""
    if directory is None:
        directory = msgsdir + topic
    print("Using directory: " + directory)

    listing = os.listdir(directory)
    e = Envelope()
    for infile in listing:
        print(infile)
        e.loadfile(directory + "/" + infile)
        if args.verbose:
            print(e.text())
        # Send to the server. Don't bother to validate it first, the server
        # will do it.
        server.receiveEnvelope(env=e)
Example #10
0
def loaddir(directory=None, topic='sitecontent'):
    """Load in a directory full of Tavern Messages."""
    if directory is None:
        directory = msgsdir + topic
    print("Using directory: " + directory)

    listing = os.listdir(directory)
    e = Envelope()
    for infile in listing:
        print(infile)
        e.loadfile(directory + "/" + infile)
        if args.verbose:
            print(e.text())
        # Send to the server. Don't bother to validate it first, the server
        # will do it.
        server.receiveEnvelope(env=e)
Example #11
0
 def addEnvelope(self, name, desc=''):
     logging.info("Adding envelope with name %s, id will be %d", name, self.__maxId())
     if name.lower() in (v.name.lower() for v in self.envelopes.values()):
         raise RuntimeError("Envelope with given name already exists")
     e = Envelope.fromData(self.__maxId() + 1, name, desc)
     self.__envelopes[e.id] = e
     self.__saveAllEnvelopes()
     return e
Example #12
0
File: Seal.py Project: evukelic/NOS
class Seal:
    """
    Class Seal represents digital seal.
    It combines digital envelope and digital signature.
    """
    def __init__(self, encryption_algorithm, key_type, rsa_key_size, message,
                 mode, sha_type):
        """
        Initialization method.
        :param encryption_algorithm: which symmetric algorithm will be used
        :param key_type: key size for the symmetric algorithm
        :param rsa_key_size: key size for the asymmetric algorithm
        :param message: encryption data
        :param mode: mode of the symmetric algorithm
        :param sha_type: SHA-2 type
        """
        self._sha = sha_type
        self._rsa_key = rsa_key_size
        # generate envelope
        self._envelope = Envelope(encryption_algorithm, key_type, rsa_key_size,
                                  message, mode)
        self._signature = None
        # envelope encryption result
        self._env_res = None

    def seal(self):
        """
        Seal method.
        """
        self._env_res = self._envelope.encrypt()
        message = str(self._envelope.cipher) + str(self._envelope.crypt_key)
        self._signature = Signature(self._sha, self._rsa_key, message)
        self._signature.sign()

    def unseal(self):
        """
        Unseal method.
        :return: original message
        """
        msg = self._envelope.decrypt(self._env_res)
        # verifies the signature
        verification = self._signature.verify()
        return msg, verification
Example #13
0
File: Seal.py Project: evukelic/NOS
 def __init__(self, encryption_algorithm, key_type, rsa_key_size, message,
              mode, sha_type):
     """
     Initialization method.
     :param encryption_algorithm: which symmetric algorithm will be used
     :param key_type: key size for the symmetric algorithm
     :param rsa_key_size: key size for the asymmetric algorithm
     :param message: encryption data
     :param mode: mode of the symmetric algorithm
     :param sha_type: SHA-2 type
     """
     self._sha = sha_type
     self._rsa_key = rsa_key_size
     # generate envelope
     self._envelope = Envelope(encryption_algorithm, key_type, rsa_key_size,
                               message, mode)
     self._signature = None
     # envelope encryption result
     self._env_res = None
Example #14
0
    def __loadSavedEnvelopes(self):
        try:
            doc = etree.parse(EnvelopeManager.__envelopeFileName)
        except Exception as e:
            print(e)
            return

        for el in doc.xpath("//Envelope"):
            try:
                env = Envelope.fromXml(el)
                self.__envelopes[env.id] = env
            except Exception as e:
                print(e)
Example #15
0
    def getTopMessage(self, messageid):
        # Find the top level of a post that we currently have.

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            # If we have no references, congrats, we're the top.
            if not 'regarding' in env.dict['envelope']['payload']:
                return env.dict['envelope']['local']['payload_sha512']
            if env.dict['envelope']['payload']['regarding'] is None:
                return env.dict['envelope']['local']['payload_sha512']
            # If we're here, it means we have a parent.
            # Recurse upstream
            result = self.getTopMessage(
                env.dict['envelope']['payload']['regarding'])

            # Don't blindly return it, since it might be None in broken chains.
            # In that case, return yourself.
            if result is not None:
                return result
            else:
                return env.dict['envelope']['local']['payload_sha512']
        else:
            return None
Example #16
0
    def getTopMessage(self, messageid):
        # Find the top level of a post that we currently have.

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            # If we have no references, congrats, we're the top.
            if not 'regarding' in env.dict['envelope']['payload']:
                return env.dict['envelope']['local']['payload_sha512']
            if env.dict['envelope']['payload']['regarding'] is None:
                return env.dict['envelope']['local']['payload_sha512']
            # If we're here, it means we have a parent.
            # Recurse upstream
            result = self.getTopMessage(
                env.dict['envelope']['payload']['regarding'])

            # Don't blindly return it, since it might be None in broken chains.
            # In that case, return yourself.
            if result is not None:
                return result
            else:
                return env.dict['envelope']['local']['payload_sha512']
        else:
            return None
Example #17
0
def writetopic(topic, since=0, limit=0, skip=0, directory=None):
    """Write a topic out to .7z files."""
    e = Envelope()
    if topic == 'all':
        envelopes = server.db.safe.find('envelopes')
    else:
        envelopes = server.db.safe.find('envelopes', {
            'envelope.local.time_added': {
                '$gt': since
            },
            'envelope.payload.topic': topic
        },
                                        limit=limit,
                                        skip=skip)

    for envelope in envelopes:
        if args.verbose:
            print(envelope)

        id = envelope['envelope']['local']['payload_sha512']
        e.loadmongo(id)
        e.validate()

        if 'topic' in e.payload.dict:
            topic = e.payload.dict['topic']
        else:
            topic = 'none'

        if directory is None:
            topicdir = msgsdir + topic
        else:
            topicdir = directory

        # Make a dir if nec.
        if not os.path.isdir(topicdir):
            os.makedirs(topicdir)

        if not os.path.exists(topicdir + "/" + e.payload.hash() +
                              ".7zTavernEnvelope"):
            e.savefile(topicdir)
Example #18
0
def writetopic(topic, since=0, limit=0, skip=0, directory=None):
    """Write a topic out to .7z files."""
    e = Envelope()
    if topic == 'all':
        envelopes = server.db.safe.find('envelopes')
    else:
        envelopes = server.db.safe.find(
            'envelopes',
            {'envelope.local.time_added': {'$gt': since},
             'envelope.payload.topic': topic},
            limit=limit,
            skip=skip)

    for envelope in envelopes:
        if args.verbose:
            print(envelope)

        id = envelope['envelope']['local']['payload_sha512']
        e.loadmongo(id)
        e.validate()

        if 'topic' in e.payload.dict:
            topic = e.payload.dict['topic']
        else:
            topic = 'none'

        if directory is None:
            topicdir = msgsdir + topic
        else:
            topicdir = directory

        # Make a dir if nec.
        if not os.path.isdir(topicdir):
            os.makedirs(topicdir)

        if not os.path.exists(topicdir + "/" + e.payload.hash() + ".7zTavernEnvelope"):
            e.savefile(topicdir)
Example #19
0
 def __init__(self):
     Envelope.__init__(self)
     self.header = MockHeaderSegment()
     self.trailer = MockTrailerSegment()
Example #20
0
def run_states(seed):

    # this function should take a seed and return a number of conflicts
    r.seed(seed)

    # INPUT
    x_s = 34  #28
    y_s = 9  #9
    z_s = 34  #28

    mytick = 105
    ticks = 100

    # random points generator
    points = []

    for i in range(18):
        x = r.randint(0, x_s)
        y = r.randint(0, y_s)
        z = r.randint(0, z_s)

        point = (x, y, z)
        points.append(point)

    ####################################################

    #need_dictionary = get_need_dictionary()

    # BEFORE starting the time loop
    # we need to create the Envelope and the People outside the time LOOP

    # ENVELOPE
    e = Envelope(x_s, y_s, z_s)

    # PEOPLE
    names_and_schedules = people_dictionary()
    people_classes = []
    index_counter = 0

    # CREATING PEOPLE
    for name in names_and_schedules:
        #print name
        person = Person(name,
                        (points[index_counter][0], points[index_counter][1],
                         points[index_counter][2]), e)
        people_classes.append(person)
        index_counter += 1

    #############

    # STARTING THE TIME LOOP
    for tick in range(ticks):

        # [STEP 1]: Updating people

        # introduce_person
        for person in people_classes:
            person.introduce_person()

        # UPDATE POSITION
        # based on the evaluation of previous iteration
        # (for the first iteration we take the initial position)
        for person in people_classes:
            person.update_position()

        # UPDATE ACTIVITY
        # This factor is for determining how often we change activity!
        #factor = 1 # it means every x iteration
        for person in people_classes:
            #print("After factor time is ", tick)
            person.update_activity_pattern_to(mytick)
            #person.update_activity_pattern_to(int(tick/factor))

        # [STEP 2]: Placing the poeple in the envelope
        # Update the envelope and claimed cells by placing people
        e.place_people(people_classes)

        #print("num_of_needed_cells: " , e.num_of_needed_cells)
        #print("num_of_claimed_cells", )
        #print("num_of_empty_cells", len(e.empty_cells()))

        # [STEP 3]: People Evaluation of what they got!

        # a - evaluating Satisfaction
        # we did not write this part yet

        # b - evaluating Position

        # the evaluation can be based on need or desire
        # every person will evaluate its current position
        # if it needs to move it will return a movement vector
        for person in people_classes:
            person.evaluate_position(value)

        # [STEP 4]: outputting
        # every iteration we output the current state of the envelope and people!
        # all as OBJECTS/CLASSES
        envelope = e  # envelope as a state of the machine
        people = people_classes  # outputting people!

        ##### outputting conflicts number

    conflicts_num = len(envelope.cells_in_conflict())
    conflict_dict = e.cells_in_conflict()
    #conflict_list = []
    conflict_list_need = []
    conflict_list_desire = []

    for key in conflict_dict:
        if conflict_dict[key][0] == 100:
            conflict_list_need.append(key.position)

    conflict_need_number = len(conflict_list_need)

    #return conflicts_num
    return conflict_need_number
Example #21
0
File: GUI.py Project: evukelic/NOS
def run_selected():
    new_window = Toplevel(root)
    new_window.geometry("400x270")
    calc_side_geometry(new_window)
    noError = True

    if button_value.get() == 1:
        algorithm = cat1
        mode = cat1_2
        rsa = cat1_3
    elif button_value.get() == 2:
        sha = cat2
        rsa = cat2_2
    else:
        algorithm = cat3
        mode = cat3_2
        rsa = cat3_3
        sha = cat3_4

    # check if everything is selected
    if button_value.get() == 1:
        task = 'Digitalna omotnica'
        if algorithm.get() == 'Select' or mode.get() == 'Select' or rsa.get(
        ) == 'Select':
            messagebox.showerror('Error', "Niste odabrali sve vrijednosti!")
            new_window.destroy()
            noError = False
    elif button_value.get() == 2:
        task = 'Digitalni potpis'
        if sha.get() == 'Select' or rsa.get() == 'Select':
            messagebox.showerror('Error', "Niste odabrali sve vrijednosti!")
            new_window.destroy()
            noError = False
    elif button_value.get() == 3:
        task = 'Digitalni pečat'
        if algorithm.get() == 'Select' or mode.get() == 'Select' or rsa.get(
        ) == 'Select' or sha.get() == 'Select':
            messagebox.showerror('Error', "Niste odabrali sve vrijednosti!")
            new_window.destroy()
            noError = False

    if text.get() == "" and noError:
        messagebox.showerror('Error', "Niste unijeli tekst!")
        new_window.destroy()
        noError = False

    if noError:
        Label(new_window, text=task.upper(),
              font=font_style_2).pack(pady=(2, 5))
        Label(new_window, text="Tekst koji ste unijeli:",
              font=font_style).pack(pady=(40, 5))
        Label(new_window, text=text.get()).pack()

        if button_value.get() == 1:
            Label(new_window,
                  text="Tekst koji je dobiven dekriptiranjem:",
                  font=font_style).pack(pady=(40, 5))
            envelope = Envelope(algorithm.get().split()[0],
                                algorithm.get().split()[1],
                                int(rsa.get().split()[1]), text.get(),
                                mode.get())
            sym_obj = envelope.encrypt()
            decrypted = envelope.decrypt(sym_obj)
            Label(new_window, text=decrypted).pack()

        elif button_value.get() == 2:
            Label(new_window,
                  text="Ishod digitalnog potpisivanja:",
                  font=font_style).pack(pady=(40, 5))
            signature = Signature(sha.get()[3:], int(rsa.get().split()[1]),
                                  text.get())
            signature.sign()
            verification = signature.verify()
            Label(new_window, text=verification).pack()

        else:
            seal = Seal(algorithm.get().split()[0],
                        algorithm.get().split()[1], int(rsa.get().split()[1]),
                        text.get(), mode.get(),
                        sha.get()[3:])
            seal.seal()
            decrypted, verification = seal.unseal()
            Label(new_window,
                  text="Tekst koji je dobiven dekriptiranjem:",
                  font=font_style).pack(pady=(20, 5))
            Label(new_window, text=decrypted).pack()
            Label(new_window,
                  text="Ishod digitalnog potpisivanja:",
                  font=font_style).pack(pady=(20, 5))
            Label(new_window, text=verification).pack()
    point = (x, y, z)
    points.append(point)

#print(points)


####################################################

#need_dictionary = get_need_dictionary()

# BEFORE starting the time loop
# we need to create the Envelope and the People outside the time LOOP

# ENVELOPE
e = Envelope(x_s, y_s, z_s)

# PEOPLE
names_and_schedules = people_dictionary()
people_classes = []
index_counter = 0

# CREATING PEOPLE
for name in names_and_schedules:
    #print name
    person = Person(name, (points[index_counter][0], points[index_counter][1],points[index_counter][2]), e )
    people_classes.append(person)
    index_counter += 1

#############
Example #23
0
    def setup(self):
        num_nodes = 10

        messages_per_server = 100

        # Ensure we have conf files for all our simulated nodes.
        # In particular, we want to make sure they all write to separate databases.

        for i in range(0, num_nodes):
            ss = ServerSettings.ServerSettings(settingsfile='tmpnode-' +
                                               str(i))
            # Give them each a unique DB
            ss.settings['dbname'] = 'tmp' + str(i)
            ss.settings['hostname'] = 'tmp' + str(i)
            ss.saveconfig()
            del (ss)

        # Create array of Nodes
        nodes = []
        for i in range(0, num_nodes):

            print("Creating server " + str(i))
            node = Node()
            node.server = Server.Server(settingsfile='tmpnode-' + str(i),
                                        slot=i)

            node.server.debug = False
            node.server.logger.setLevel("INFO")
            node.servernum = i
            nodes.append(node)

        for node in nodes:

            node.server.start()

            print("We have node - " + str(node.servernum))
            SHA512 = hashlib.sha512()
            SHA512.update(node.server.ServerKeys.pubkey.encode('utf-8'))
            print("Our keyhash is - " + SHA512.hexdigest())

            for count in range(0, messages_per_server):
                e = Envelope(srv=node.server)

                # Inserting the time so that each message is different.
                e.payload.dict[
                    'body'] = """This env was inserted into server: """ + str(
                        node.servernum) + """
                at """ + str(time.time()) + """
                This is message #""" + str(count) + """
                Thanks!!
                """
                e.payload.dict['formatting'] = "markdown"
                e.payload.dict['class'] = "message"
                e.payload.dict['topic'] = "testmessage"
                e.payload.dict['subject'] = "Test from server: " + str(
                    node.servernum)

                user = User()
                user.generate(AllowGuestKey=False)

                e.payload.dict['author'] = OrderedDict()
                e.payload.dict['author']['replyto'] = user.Keys['posted'][
                    -1].pubkey
                e.payload.dict['author']['friendlyname'] = user.UserSettings[
                    'friendlyname']

                e.addStamp(stampclass='author',
                           friendlyname=user.UserSettings['friendlyname'],
                           keys=user.Keys['master'],
                           passkey=user.passkey)

                msgid = node.server.receiveEnvelope(env=e)
                print("Sent " + msgid + "to server- " + str(node.servernum))
Example #24
0
URL_ENVELOPE = '{http://www.opengis.net/gml}Envelope'
URL_FEATURE_MEMBER = '{http://www.opengis.net/gml}featureMember'
URL_ID = '{http://www.opengis.net/gml}id'

ATTRB_SRS_NAME = 'srsName'
ATTRB_SRS_DIMENSION = 'srsDimension'
ENVELOPE_LOWER_CORNER = 'lowerCorner'
ENVELOPE_UPPER_CORNER = 'upperCorner'

ENVELOPE_INSTANCE_PREFIX = 'Envelope_of_'
EPSG_4326 = 'EPSG:4326'
EPSG_27700 = 'EPSG:27700'
"""Declared a variable for creating a graph model"""
g = Graph()
envelope = Envelope()
"""Creates a context for parsing when the GML file name and tag is given"""


def get_context(file_name, tag):
    return etree.iterparse(file_name, events=('end', ), tag=tag)


"""Parses the following attributes of GML envelope and returns the envelope
- srsName
- srsDimension
"""


def get_envelope(context):
    for event, elem in context:
Example #25
0
    def error_envelope(self, subject="Error", topic="sitecontent", body=None):

        if body is None:
            body = """
            Oh my, something seems to have happened that we weren't expecting.
            Hopefully this will get cleared up relatively quickly.
            If not, you might want to send a note to [email protected], with the URL, and notes on how you got here :/

            So sorry for the trouble.
            -The Barkeep
            """
        e = Envelope()
        e.dict['envelope']['payload'] = OrderedDict()
        e.dict['envelope']['payload']['subject'] = subject
        e.dict['envelope']['payload']['topic'] = topic
        e.dict['envelope']['payload']['formatting'] = "markdown"
        e.dict['envelope']['payload']['class'] = "message"
        e.dict['envelope']['payload'][
            'body'] = body
        e.dict['envelope']['payload']['author'] = OrderedDict()
        e.dict['envelope']['payload']['author']['pubkey'] = "1234"
        e.dict['envelope']['payload']['author']['friendlyname'] = "ERROR!"
        e.dict['envelope']['payload']['author']['useragent'] = "Error Agent"
        e.dict['envelope']['payload']['author']['friendlyname'] = "Error"
        e.addStamp(
            stampclass='author',
            keys=self.ServerKeys,
            friendlyname=defaultsettings.settings['hostname'])
        e.flatten()
        e.munge()
        e.dict['envelope']['local']['time_added'] = 1297396876
        e.dict['envelope']['local'][
            'author_wordhash'] = "Automatically generated message"
        e.dict['envelope']['local']['sorttopic'] = "error"
        e.dict['envelope']['local']['payload_sha512'] = e.payload.hash()
        return e
 def addEnvelope(self, name, amountSpent):
     newEnvelope = Envelope(name, amountSpent)
     self.envelopes.append(newEnvelope)
Example #27
0
    def receiveEnvelope(self, envstr=None, env=None):
        """Receive an envelope for processing in the server.

        Can take either a string, or an envelope obj.

        """
        if envstr is None and env is None:
            raise Exception(
                'receiveEnvelope MUST receive an envelope. Really! ;)')

        if env is not None:
            # If we get an envelope, flatten it - The caller may not have.
            c = env.flatten()
        else:
            c = Envelope()
            c.loadstring(importstring=envstr)

        # Fill-out the message's local fields.
        c.munge()
        # Make sure the message is valid, meets our standards, and is good to
        # accept and save.
        if not c.validate():
            self.logger.info(
                "Received an Envelope which does not validate-  " + c.payload.hash())
            self.logger.debug(c.text())
            return False

        utctime = time.time()

        existing = self.db.unsafe.find_one(
            'envelopes', {'envelope.local.payload_sha512': c.dict['envelope']['local']['payload_sha512']})

        if existing is not None:
            self.logger.debug("We already have that msg.")
            return c.dict['envelope']['local']['payload_sha512']

        # Sign the message to saw we saw it.
        if self.serversettings.settings['mark-seen']:
            c.addStamp(
                stampclass='server',
                keys=self.ServerKeys,
                hostname=defaultsettings.settings['hostname'])

        # Store the time, in full UTC (with precision). This is used to skip
        # pages in the viewer later.
        c.dict['envelope']['local']['time_added'] = utctime

        if c.dict['envelope']['payload']['class'] == "message":

            # If the message referenes anyone, mark the original, for ease of finding it later.
            # Do this in the 'local' block, so we don't waste bits passing this on to others.
            # Partners can calculate this when they receive it.

            if 'regarding' in c.dict['envelope']['payload']:
                repliedTo = Envelope()
                if repliedTo.loadmongo(mongo_id=c.dict['envelope']['payload']['regarding']):
                    self.logger.debug(
                        " I am :: " + c.dict['envelope']['local']['payload_sha512'])
                    self.logger.debug(
                        " Adding a cite on my parent :: " +
                        repliedTo.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    repliedTo.addcite(
                        c.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    c.addAncestor(c.dict['envelope']['payload']['regarding'])

            print("id is :" + c.dict['envelope']['local']['payload_sha512'])

            # It could also be that this message is cited BY others we already have!
            # Sometimes we received them out of order. Better check.
            for citedict in self.db.unsafe.find('envelopes', {'envelope.payload.regarding': c.dict['envelope']['local']['payload_sha512']}):
                self.logger.debug('found existing cite, bad order. ')
                self.logger.debug(
                    " I am :: " + c.dict['envelope']['local']['payload_sha512'])
                self.logger.debug(" Found pre-existing cite at :: " +
                                  citedict['envelope']['local']['payload_sha512'])

                # If it's a message, write that in the reply, and in me.
                if citedict['envelope']['payload']['class'] == 'message':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    c.addcite(
                        citedme.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    citedme.addAncestor(
                        c.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    citedme.saveMongo()

                # If it's an edit, write that in me.
                elif citedict['envelope']['payload']['class'] == 'messagerevision':
                    c.addEdit(citedict['envelope']['local']['payload_sha512'])

                elif citedict['envelope']['payload']['class'] == 'messagerating':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    citedme.dict[
                        'envelope'][
                        'local'][
                        'regardingAuthor'] = c.dict[
                        'envelope'][
                        'payload'][
                        'author']
                    citedme.saveMongo()

        elif c.dict['envelope']['payload']['class'] == "messagerating":
            # If this is a rating, cache the AUTHOR of the rated message.
            regardingPost = self.db.unsafe.find_one(
                'envelopes',
                {'envelope.local.payload_sha512': c.dict['envelope']['payload']['regarding']})
            if regardingPost is not None:
                c.dict[
                    'envelope'][
                    'local'][
                    'regardingAuthor'] = regardingPost[
                    'envelope'][
                    'payload'][
                    'author']

        elif c.dict['envelope']['payload']['class'] == "messagerevision":
            # This is an edit to an existing message.

            regardingPost = self.db.unsafe.find_one(
                'envelopes',
                {'envelope.local.payload_sha512': c.dict['envelope']['payload']['regarding']})
            if regardingPost is not None:
                if 'priority' in c.dict['envelope']['payload']:
                    c.dict[
                        'envelope'][
                        'local'][
                        'priority'] = c.dict[
                        'envelope'][
                        'payload'][
                        'priority']
                else:
                    c.dict['envelope']['local']['priority'] = 0

                # Store this edit.
                # Save this message out to mongo, so we can then retrieve it in
                # addEdit().
                c.saveMongo()

                # Modify the original message.
                r = Envelope()
                r.loaddict(regardingPost)
                r.addEdit(c.dict['envelope']['local']['payload_sha512'])

                # Ensure we have the freshest version in memory.
                c.reloadmongo()
            else:
                self.logger.debug("Received an edit without the original")

        # Store our Envelope
        c.saveMongo()

        return c.dict['envelope']['local']['payload_sha512']
Example #28
0
 def addEnvelope(self, name, value):
     self.envelopes.append(Envelope(name, value))
Example #29
0
 def __init__(self):
     Envelope.__init__(self)
     self.header = MockHeaderSegment()
     self.trailer = MockTrailerSegment()
Example #30
0
    def setup(self):
        num_nodes = 10

        messages_per_server = 100

        # Ensure we have conf files for all our simulated nodes.
        # In particular, we want to make sure they all write to separate databases.

        for i in range(0,num_nodes):
            ss = ServerSettings.ServerSettings(settingsfile='tmpnode-'+str(i))
            # Give them each a unique DB
            ss.settings['dbname'] = 'tmp' + str(i)
            ss.settings['hostname'] = 'tmp' + str(i)
            ss.saveconfig()
            del(ss)

        # Create array of Nodes
        nodes = []
        for i in range(0,num_nodes):

            print("Creating server " + str(i))
            node = Node()
            node.server = Server.Server(settingsfile='tmpnode-'+str(i),slot=i)

            node.server.debug = False
            node.server.logger.setLevel("INFO")
            node.servernum = i
            nodes.append(node)



        for node in nodes:

            node.server.start()

            print("We have node - " + str(node.servernum))
            SHA512 = hashlib.sha512()
            SHA512.update(node.server.ServerKeys.pubkey.encode('utf-8'))
            print("Our keyhash is - " + SHA512.hexdigest())

            for count in range(0,messages_per_server):
                e = Envelope(srv=node.server)

                # Inserting the time so that each message is different.
                e.payload.dict['body'] = """This env was inserted into server: """ + str(node.servernum) + """
                at """ + str(time.time()) + """
                This is message #""" + str(count) + """
                Thanks!!
                """
                e.payload.dict['formatting'] = "markdown"
                e.payload.dict['class'] = "message"
                e.payload.dict['topic'] = "testmessage"
                e.payload.dict['subject'] = "Test from server: " + str(node.servernum)

                user = User()
                user.generate(AllowGuestKey=False)

                e.payload.dict['author'] = OrderedDict()
                e.payload.dict['author']['replyto'] = user.Keys['posted'][-1].pubkey
                e.payload.dict['author']['friendlyname'] = user.UserSettings['friendlyname']

                e.addStamp(stampclass='author',friendlyname=user.UserSettings['friendlyname'],keys=user.Keys['master'],passkey=user.passkey)

                msgid = node.server.receiveEnvelope(env=e)
                print("Sent " + msgid + "to server- " + str(node.servernum))
Example #31
0
    def receiveEnvelope(self, envstr=None, env=None):
        """Receive an envelope for processing in the server.

        Can take either a string, or an envelope obj.

        """
        if envstr is None and env is None:
            raise Exception(
                'receiveEnvelope MUST receive an envelope. Really! ;)')

        if env is not None:
            # If we get an envelope, flatten it - The caller may not have.
            c = env.flatten()
        else:
            c = Envelope()
            c.loadstring(importstring=envstr)

        # Fill-out the message's local fields.
        c.munge()
        # Make sure the message is valid, meets our standards, and is good to
        # accept and save.
        if not c.validate():
            self.logger.info(
                "Received an Envelope which does not validate-  " +
                c.payload.hash())
            self.logger.debug(c.text())
            return False

        utctime = time.time()

        existing = self.db.unsafe.find_one(
            'envelopes', {
                'envelope.local.payload_sha512':
                c.dict['envelope']['local']['payload_sha512']
            })

        if existing is not None:
            self.logger.debug("We already have that msg.")
            return c.dict['envelope']['local']['payload_sha512']

        # Sign the message to saw we saw it.
        if self.serversettings.settings['mark-seen']:
            c.addStamp(stampclass='server',
                       keys=self.ServerKeys,
                       hostname=defaultsettings.settings['hostname'])

        # Store the time, in full UTC (with precision). This is used to skip
        # pages in the viewer later.
        c.dict['envelope']['local']['time_added'] = utctime

        if c.dict['envelope']['payload']['class'] == "message":

            # If the message referenes anyone, mark the original, for ease of finding it later.
            # Do this in the 'local' block, so we don't waste bits passing this on to others.
            # Partners can calculate this when they receive it.

            if 'regarding' in c.dict['envelope']['payload']:
                repliedTo = Envelope()
                if repliedTo.loadmongo(
                        mongo_id=c.dict['envelope']['payload']['regarding']):
                    self.logger.debug(
                        " I am :: " +
                        c.dict['envelope']['local']['payload_sha512'])
                    self.logger.debug(
                        " Adding a cite on my parent :: " +
                        repliedTo.dict['envelope']['local']['payload_sha512'])
                    repliedTo.addcite(
                        c.dict['envelope']['local']['payload_sha512'])
                    c.addAncestor(c.dict['envelope']['payload']['regarding'])

            print("id is :" + c.dict['envelope']['local']['payload_sha512'])

            # It could also be that this message is cited BY others we already have!
            # Sometimes we received them out of order. Better check.
            for citedict in self.db.unsafe.find(
                    'envelopes', {
                        'envelope.payload.regarding':
                        c.dict['envelope']['local']['payload_sha512']
                    }):
                self.logger.debug('found existing cite, bad order. ')
                self.logger.debug(
                    " I am :: " +
                    c.dict['envelope']['local']['payload_sha512'])
                self.logger.debug(
                    " Found pre-existing cite at :: " +
                    citedict['envelope']['local']['payload_sha512'])

                # If it's a message, write that in the reply, and in me.
                if citedict['envelope']['payload']['class'] == 'message':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    c.addcite(
                        citedme.dict['envelope']['local']['payload_sha512'])
                    citedme.addAncestor(
                        c.dict['envelope']['local']['payload_sha512'])
                    citedme.saveMongo()

                # If it's an edit, write that in me.
                elif citedict['envelope']['payload'][
                        'class'] == 'messagerevision':
                    c.addEdit(citedict['envelope']['local']['payload_sha512'])

                elif citedict['envelope']['payload'][
                        'class'] == 'messagerating':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    citedme.dict['envelope']['local'][
                        'regardingAuthor'] = c.dict['envelope']['payload'][
                            'author']
                    citedme.saveMongo()

        elif c.dict['envelope']['payload']['class'] == "messagerating":
            # If this is a rating, cache the AUTHOR of the rated message.
            regardingPost = self.db.unsafe.find_one(
                'envelopes', {
                    'envelope.local.payload_sha512':
                    c.dict['envelope']['payload']['regarding']
                })
            if regardingPost is not None:
                c.dict['envelope']['local']['regardingAuthor'] = regardingPost[
                    'envelope']['payload']['author']

        elif c.dict['envelope']['payload']['class'] == "messagerevision":
            # This is an edit to an existing message.

            regardingPost = self.db.unsafe.find_one(
                'envelopes', {
                    'envelope.local.payload_sha512':
                    c.dict['envelope']['payload']['regarding']
                })
            if regardingPost is not None:
                if 'priority' in c.dict['envelope']['payload']:
                    c.dict['envelope']['local']['priority'] = c.dict[
                        'envelope']['payload']['priority']
                else:
                    c.dict['envelope']['local']['priority'] = 0

                # Store this edit.
                # Save this message out to mongo, so we can then retrieve it in
                # addEdit().
                c.saveMongo()

                # Modify the original message.
                r = Envelope()
                r.loaddict(regardingPost)
                r.addEdit(c.dict['envelope']['local']['payload_sha512'])

                # Ensure we have the freshest version in memory.
                c.reloadmongo()
            else:
                self.logger.debug("Received an edit without the original")

        # Store our Envelope
        c.saveMongo()

        return c.dict['envelope']['local']['payload_sha512']
Example #32
0
 def addPot(self, name, value):
     self.pots.append(Envelope(name, value))
Example #33
0
    def error_envelope(self, subject="Error", topic="sitecontent", body=None):

        if body is None:
            body = """
            Oh my, something seems to have happened that we weren't expecting.
            Hopefully this will get cleared up relatively quickly.
            If not, you might want to send a note to [email protected], with the URL, and notes on how you got here :/

            So sorry for the trouble.
            -The Barkeep
            """
        e = Envelope()
        e.dict['envelope']['payload'] = OrderedDict()
        e.dict['envelope']['payload']['subject'] = subject
        e.dict['envelope']['payload']['topic'] = topic
        e.dict['envelope']['payload']['formatting'] = "markdown"
        e.dict['envelope']['payload']['class'] = "message"
        e.dict['envelope']['payload']['body'] = body
        e.dict['envelope']['payload']['author'] = OrderedDict()
        e.dict['envelope']['payload']['author']['pubkey'] = "1234"
        e.dict['envelope']['payload']['author']['friendlyname'] = "ERROR!"
        e.dict['envelope']['payload']['author']['useragent'] = "Error Agent"
        e.dict['envelope']['payload']['author']['friendlyname'] = "Error"
        e.addStamp(stampclass='author',
                   keys=self.ServerKeys,
                   friendlyname=defaultsettings.settings['hostname'])
        e.flatten()
        e.munge()
        e.dict['envelope']['local']['time_added'] = 1297396876
        e.dict['envelope']['local'][
            'author_wordhash'] = "Automatically generated message"
        e.dict['envelope']['local']['sorttopic'] = "error"
        e.dict['envelope']['local']['payload_sha512'] = e.payload.hash()
        return e