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 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
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
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
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)
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 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)
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
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
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 #############
def addEnvelope(self, name, amountSpent): newEnvelope = Envelope(name, amountSpent) self.envelopes.append(newEnvelope)
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))
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']
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()
def addEnvelope(self, name, value): self.envelopes.append(Envelope(name, value))
def addPot(self, name, value): self.pots.append(Envelope(name, value))
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: