Пример #1
0
Файл: node.py Проект: the07/PC4
    def __init__(
        self,
        private_key=None
    ):  #TODO Raise mining request, approved by existing miners then can mine.

        if private_key is None:
            print("Starting a new chain\n")
            print("Generating Genesis User Key Pair")
            self.key = Key()
            print("Generating Genesis User")
            print("Network Key: {}".format(self.key.get_private_key()))
            #TODO: store the information in config file
            user = User(self.key.get_public_key(), "Network",
                        "*****@*****.**", '3')
            self.peoplechain = Peoplechain()
            self.peoplechain.add_user(user)
            print("Peoplechain Created.")
            print(self.peoplechain.users)
        else:
            print("Generating key pair from private key")
            self.key = Key(private_key)
            self.request_nodes_from_all()
            if not self.discover_user(self.key.get_public_key()):
                raise Exception()
            remote_chain = self.download()
            self.peoplechain = Peoplechain(remote_chain)
            self.node = self.get_my_node()
            self.broadcast_node(self.node)
            self.full_nodes.union([self.node])

        print("\n -------------- Starting Full Node Server -------------- \n")
        self.app.run('0.0.0.0', self.FULL_NODE_PORT)
Пример #2
0
 def __init__(self):
     self.label: int = 0   # identifier string, eg. a number
     self.name = ''   # full name of this v
     self.sname = ''   # short name
     self.meter = Meter()   # meter
     self.meter0 = Meter()   # meter
     self.meter1 = Meter()   # meter
     self.key = Key()   # keysig
     self.key0 = Key()   # keysig
     self.key1 = Key()   # keysig
     self.stems = 0   # +1 or -1 to force stem direction
     self.staves = 0
     self.brace = 0
     self.bracket = 0
     self.do_gch = 0   # 1 to output gchords for this v
     self.sep = 0.0   # for space to next v below
     self.syms = list()    # number of music
     self.nsym = len(self.syms)
     self.draw = False   # flag if want to draw this v
     self.select = True   # flag if selected for output
     self.insert_btype = B_INVIS
     self.insert_num = 0   # to split bars over linebreaks
     self.insert_bnum = 0   # same for bar number
     self.insert_space = 0.0   # space to insert after init syms
     self.end_slur = 0   # for a-b slurs
     self.insert_text = ''   # string over inserted barline
     self.timeinit = 0.0   # carryover time between parts
Пример #3
0
    def get_key(self,
                key_name,
                headers=None,
                version_id=None,
                key_type=Key.KEY_REGULAR_FILE):
        """
        Check to see if a particular key exists within the bucket.
        Returns: An instance of a Key object or None

        :type key_name: string
        :param key_name: The name of the key to retrieve

        :type version_id: string
        :param version_id: Unused in this subclass.

        :type stream_type: integer
        :param stream_type: Type of the Key - Regular File or input/output Stream

        :rtype: :class:`boto.file.key.Key`
        :returns: A Key object from this bucket.
        """
        if key_name == '-':
            return Key(self.name, '-', key_type=Key.KEY_STREAM_READABLE)
        else:
            fp = open(key_name, 'rb')
            return Key(self.name, key_name, fp)
Пример #4
0
def getKeys(length):
    n_min = 1 << (length - 1)
    n_max = (1 << length) - 1

    start = 1 << (length // 2 - 1)
    stop = 1 << (length // 2 + 1)
    primes = getPrimes(start, stop)

    while primes:
        p = random.choice(primes)
        primes.remove(p)
        q_candidates = [q for q in primes if n_min <= p * q <= n_max]
        if q_candidates:
            q = random.choice(q_candidates)
            break

    stop = (p - 1) * (q - 1)
    for e in range(3, stop, 2):
        if areRelativelyPrime(e, stop):
            break

    for d in range(3, stop, 2):
        if d * e % stop == 1:
            break

    return Key(p * q, e), Key(p * q, d)
Пример #5
0
 def insertKey(end, key):
     if end[key%100] is not None:
         p = end[key%100]                
         while(p.getProx()):
             p = p.getProx()                
         p.prox = Key(key)                   
     else:
         end[key%100] = Key(key)  
Пример #6
0
 def break_the_key(self):
     A = bt.phi(self.public_key.get_modulus())
     list_of_euclidean = bt.euclidean_algorithm(
         self.public_key.get_exponent(), A)
     inverse_list = bt.extended_euclidean_algorithm(list_of_euclidean)
     if len(inverse_list) % 2 == 1:
         self.private_key = Key(self.public_key.get_modulus(),
                                inverse_list[-1][2] + A)
     else:
         self.private_key = Key(self.public_key.get_modulus(),
                                inverse_list[-1][0])
Пример #7
0
    def test_dataset_prefix(self):
        key = Key(dataset=Dataset('dset'))
        protokey = key.to_protobuf()
        self.assertEqual('s~dset', protokey.partition_id.dataset_id)

        key = Key(dataset=Dataset('s~dset'))
        protokey = key.to_protobuf()
        self.assertEqual('s~dset', protokey.partition_id.dataset_id)

        key = Key(dataset=Dataset('e~dset'))
        protokey = key.to_protobuf()
        self.assertEqual('e~dset', protokey.partition_id.dataset_id)
Пример #8
0
	def recursive_crack(self,p):
		

		
		stime = time()
		lolz=[]
		parent = ""
		champion = ""
		candidate = ""
		fr_score = 0
		for x in range(0,p):
			parent = parent + 'a'
		for y in range(0,p):
			for combo in product(ascii_lowercase, repeat=1):
				liste = list(parent)
				liste[y] = ''.join(combo)
				candidate = ''.join(liste)
				temp = Key(candidate)
				lolz = decode_it(self.sliced,temp)
				stringer = "".join(lolz)
				if (letter_score(stringer)>fr_score):
					champion = candidate
					fr_score = letter_score(stringer)
			fr_score = 0
			parent = champion
			
		for z in range(0,p):
			for combo in product(ascii_lowercase, repeat=1):
				liste = list(parent)
				liste[p-(1+z)] = ''.join(combo)
				candidate = ''.join(liste)
				temp = Key(candidate)
				lolz = decode_it(self.sliced,temp)
				stringer = "".join(lolz)
				if (letter_score(stringer)>fr_score):
					champion = candidate
					fr_score = letter_score(stringer)
			fr_score = 0
			parent = champion
		
			
		print "The key found: %s\n" % parent
		puk = Key(parent)
		lolek = decode_it(self.sliced,puk)
		print "Decrypted message: %s\n" % " ".join(lolek)
		summ = open('summary.txt','a')
		f = open('test_recursive.txt','w')
		f.close()
		etime = time()
		summ.write("\nRecursive Test:\nTime elapsed: %s\nMax_key_lenght: %s\nFile size: %s\n"% (str(etime-stime),p,os.path.getsize("test_recursive.txt")))
		summ.close()
		return True
Пример #9
0
    def updatefinger(self, newnode, firstnode):
        '''

        UPdate finger table for all ring in a clockwise around successor fashion

        finger is an array of dict {resp, key}

            `resp` is the Node responsible for `key`

        @param newnode: new node which imply this update

        @param firstnode: node which launch the update

        '''

        for i in range(0, self.uid.idlength):

            fingerkey = self.calcfinger(i)

            resp = self.lookup(fingerkey, useOnlySucc=True)

            self.finger[i] = {"resp": resp, "key": Key(fingerkey)}

            #self.finger[i] = self.lookupfinger(i, useOnlySucc=True)

        if firstnode is not self.successor:

            self.successor.updatefinger(newnode, firstnode)
Пример #10
0
def decode(file_path, out_path):

    if out_path == "":
        out_path = file_path.replace('.pi', '')

    print("Generating array from encryption key...")
    encryption_key = Key('data/pi.dat')

    CHUNK_SIZE = 1

    print("Reading file to decrypt...")
    with open(file_path, 'rb') as infile:
        indexes = infile.read().split(',')

    print("Decrypting file...")
    pointer_array = map(encryption_key.get_data, indexes)

    print("Dumping decrypted file...")
    with open(out_path, 'a') as outfile:

        b64string = ''.join(map(chr, pointer_array))

        missing_padding = 4 - len(b64string) % 4
        if missing_padding:
            b64string += b'=' * missing_padding

        outfile.write(base64.decodestring(b64string))

    os.remove('cache.db')
Пример #11
0
def enter():
    global map
    map = Map()
    game_world.add_object(map, 0)

    global horn
    horn = Horn()
    game_world.add_object(horn, 1)

    global boss
    boss = Boss()
    game_world.add_object(boss, 1)

    global character
    character = Character()
    game_world.add_object(character, 1)

    global butterflys
    butterflys = [Butterfly(character) for i in range(7)]
    game_world.add_objects(butterflys, 1)

    key = Key()
    game_world.add_object(key, 1)

    map.set_center_object(character)
    character.set_background(map)
    horn.set_background(map)
    boss.set_background(map)
Пример #12
0
    def setNote(self, noteabout, note=""):
        # Format the Key.
        key = Key(pub=noteabout)
        noteabout = key.pubkey

        newnote = {
            "user": self.Keys['master'].pubkey,
            "noteabout": noteabout,
            "note": note
        }

        # Retrieve any existing note, so that the _id is the same. Then, we'll
        # gut it, and put in our own values.
        newnote = self.server.db.unsafe.find_one('notes', {
            "user": self.Keys['master'].pubkey,
            "noteabout": noteabout
        })
        if newnote is None:
            newnote = {
                "user": self.Keys['master'].pubkey,
                "noteabout": noteabout,
                "note": note
            }
        newnote['note'] = note
        self.server.db.unsafe.save('notes', newnote)
        self.getNote(noteabout=noteabout, invalidate=True)
Пример #13
0
    def verify_password(self, guessed_password, tryinverted=True):
        """Check a proposed password, to see if it's able to open and load a
        user's account."""

        # The cleanest way to see if the password is accurate is to see if it successfully decodes the content in the account.
        # We can do this by attempting to decode the private key.
        # We can then verify it decoded properly, by re-deriving the public key, and seeing if they match.

        test_passkey = self.Keys['master'].get_passkey(guessed_password)
        byteprivatekey = base64.b64decode(
            self.encryptedprivkey.encode('utf-8'))

        # We decoded something. Check to see if we can recreate the pubkey using this.
        if byteprivatekey is None:
            return False
        else:
            test_key = Key()
            test_key.gpg.import_keys(byteprivatekey)
            reconstituted_pubkey = test_key.gpg.export_keys(
                test_key.gpg.list_keys()[0]['fingerprint'])
            test_key.pubkey = reconstituted_pubkey
            test_key._format_keys()

            if test_key.pubkey == user.pubkey:
                return True

            # Let's try one other variation before we give up.
            # It's possible the user has caps lock on, and so their keys are inverted.
            # Testing this doesn't substantially decrease security, but it does help make things easier for users who had a long day.
            # Based on the FB-technique, as described at http://blog.agilebits.com/2011/09/13/facebook-and-caps-lock-unintuitive-security/

            if tryinverted:
                return self.verify_password(
                    guessed_password=guessed_password.swapcase(),
                    tryinverted=False)
Пример #14
0
    def __init__(self):
        self.rooms = []
        self.currentRoom = 0
        self.inventory = []

        firstRoom = Room(
            1,
            "Je staat in de keuken. Er staan een aanrecht en een koelkast, en er is 1 deur.",
            [Door(123, 1)],
            [Key(123, "woonkamersleutel"),
             Key(321, "schatkistsleutel")])
        secondRoom = Room(2, "Je staat in de woonkamer, er is een deur",
                          [Door(123, 0)], [])
        self.rooms.append(firstRoom)
        self.rooms.append(secondRoom)
        print(self.rooms[self.currentRoom].description)
Пример #15
0
def get_key(file_in):
    """
    Estimates the key and scale for an audio file.
    """
    loader = streaming.MonoLoader(filename=file_in)
    framecutter = streaming.FrameCutter()
    windowing = streaming.Windowing(type="blackmanharris62")
    spectrum = streaming.Spectrum()
    spectralpeaks = streaming.SpectralPeaks(orderBy="magnitude",
                                            magnitudeThreshold=1e-05,
                                            minFrequency=40,
                                            maxFrequency=5000,
                                            maxPeaks=10000)
    pool = Pool()
    hpcp = streaming.HPCP()
    key = streaming.Key()

    loader.audio >> framecutter.signal
    framecutter.frame >> windowing.frame >> spectrum.frame
    spectrum.spectrum >> spectralpeaks.spectrum
    spectralpeaks.magnitudes >> hpcp.magnitudes
    spectralpeaks.frequencies >> hpcp.frequencies
    hpcp.hpcp >> key.pcp
    key.key >> (pool, 'tonal.key_key')
    key.scale >> (pool, 'tonal.key_scale')
    key.strength >> (pool, 'tonal.key_strength')

    run(loader)

    return Key(pool['tonal.key_key'], pool['tonal.key_scale'])
Пример #16
0
    def list(self, prefix=None, delimiter=None, marker=None, limit=None):
        """ List objects of the bucket.

        Keyword arguments:
        prefix - Limits the response to keys that begin with the specified prefix
        delimiter - A character you use to group keys
        marker - Specifies the key to start with when listing objects
        limit - The count of objects that the request returns
        """
        params = {}
        if prefix:
            params["prefix"] = prefix
        if delimiter:
            params["delimiter"] = delimiter
        if marker:
            params["marker"] = marker
        if limit:
            params["limit"] = str(limit)
        response = self.connection.make_request("GET",
                                                self.name,
                                                params=params)
        if response.status == 200:
            resp = json.loads(response.read())
            result_set = []
            for k in resp["keys"]:
                key = Key(self, k["key"])
                key.content_type = k["mime_type"]
                result_set.append(key)
            return result_set
        else:
            err = get_response_error(response)
            raise err
Пример #17
0
def key_exchange(conn) -> tuple[int, int]:
    client_public_key = conn.recv(2048).decode('utf-8')
    print("Received client public key: " +
          client_public_key.replace('\n', " "))

    client_public_key = client_public_key.split('\n')
    calc_key_client = Key(create_param(), int(client_public_key[0]),
                          int(client_public_key[1]))
    B_attr_server = str(calc_key_client.AB) + '\n'
    conn.send(B_attr_server.encode('utf-8'))
    print("Sent server B attribute to the client: " +
          B_attr_server.replace('\n', " "))

    server_public_key = read_key("public_key_server.pem")
    conn.send(server_public_key.encode('utf-8'))
    print('Sent server public key to the client: ' +
          server_public_key.replace('\n', " "))

    B_attr_client = conn.recv(2048).decode('utf-8')
    print("Received client B attribute key: " +
          B_attr_client.replace('\n', " "))
    B_attr_client = B_attr_client.split('\n')

    server_private_key = read_key("private_key_server.pem").split('\n')
    server_public_key = server_public_key.split('\n')

    K_client = create_sym_key(calc_key_client.ab, int(client_public_key[2]),
                              calc_key_client.p)
    print('Calculated common private key for the client: ' + str(K_client))
    K_server = create_sym_key(int(server_private_key[0]),
                              int(B_attr_client[0]), int(server_public_key[1]))
    print('Calculated common private key for the server: ' + str(K_server))

    return K_client, K_server
Пример #18
0
 def send_create_account_tx(self, new_account_id, base_block_hash=None):
     self.prep_tx()
     new_key = Key(new_account_id, self.key.pk, self.key.sk)
     tx = sign_create_account_with_full_access_key_and_balance_tx(
         self.key, new_account_id, new_key, 100 * NEAR_BASE, self.nonce,
         base_block_hash or self.base_block_hash)
     return self.send_tx(tx)
Пример #19
0
    def parse_header(self, header_lines):
        for line in header_lines:
            value = line.strip('\n').split(':')
            if value[0] == 'K':
                # self.sigkey = Key(value[1])
                self.sigkey = Key('C')
                self.sigkey.calculate_scales()
            elif value[0] == 'M':
                if 'C' in value[1]:
                    if '|' in line[1]:
                        self.meter = [2, 2]
                    else:
                        self.meter = [4, 4]
                else:
                    a, b = value[1].split('/')
                    self.meter = [int(a), int(b)]
            elif value[0] == 'V':
                voice = value[1].split()[0]
                if voice not in self.voices:
                    self.voices += [voice]
            elif value[0] == 'L':
                self.length = value[1].split()[0]

        if self.voices == []:
            self.voices += ['V1']
            header_lines.insert(-1, 'V:V1 treble\n')
        self.voices += ['V2']
        header_lines += ['V:V2 treble\n']

        return header_lines
    def __init__(self, world):
        self.__world = world
        self.__platforms = pg.sprite.Group()
        self.__items = pg.sprite.Group()
        self.__exit = pg.sprite.Group()
        self.__bg = (BLUE)

        row_count = 0
        for row in self.__world:
            col_count = 0
            for tile in row:
                if tile == 1:
                    wall = Platform(col_count * TILE_SIZE_W,
                                    row_count * TILE_SIZE_H, TILE_SIZE_W,
                                    TILE_SIZE_H, BLUE)
                    self.__platforms.add(wall)
                    #tile = (wall.image, wall.rect)
                elif tile == 2:
                    grogu = Key(col_count * TILE_SIZE_W,
                                row_count * TILE_SIZE_H, 20, 20, GREEN)
                    self.__items.add(grogu)
                elif tile == 3:
                    ship = Extraction_point(col_count * TILE_SIZE_W,
                                            row_count * TILE_SIZE_H,
                                            TILE_SIZE_W, TILE_SIZE_H, PURPLE)
                    self.__exit.add(ship)
                col_count += 1
            row_count += 1

        self.__spawn_point = ((WIDTH, HEIGHT))
Пример #21
0
 def test_constructor(self):
     k = Key()
     self.assertEqual(k.sf, 0)
     self.assertEqual(k.key_type, constants.TREBLE)
     self.assertEqual(k.add_pitch, 0)
     self.assertEqual(k.root, 2)
     self.assertEqual(k.root_acc, constants.A_NT)
Пример #22
0
def trySerialize(obj):
    if isinstance(obj, basestring):
        return Key(obj).serialize()
    if hasattr(obj, 'serialize'):
        return obj.serialize()
    else:
        return obj
Пример #23
0
    def shack(self):
        room = Room()
        lantern = Item('lantern')
        lantern.effects['description'] = 'You would light up the room but the lantern was too sick.'
        room.inventory.add(lantern)
        kitchenKey = Item("kitchen key")
        kitchenKey.shortname = 'key'
        kitchenKey.movable = True
        kitchenKey.key = Key("kitchen key", "The door is unlocked.")
        kitchenKey.effects['description'] = "It's a key to the kitchen."
        room.inventory.add(kitchenKey)
        room.long_description = """You are in a small shack. It has a creaky floor, leaky roof and you are scared.oh not of the room but the cage with a lion in it."""
        room.short_description = """A small wooden shack."""
        room.name = "Shack"
        #room.exits = {'e': 1, 'w': -3}
        room.exits = {
                'e': Connection(1), 
                'w': Connection( 3,
                    'kitchen door',
                    'locked',
                    kitchenKey, 
                    'The kitchen door is firmly locked. There should be a key somewhere around.') }
        #room.locked = {'w': }

        return room
Пример #24
0
 def kitchen2(self):
     room = Room()
     moldyCheese = Item('moldy cheese')
     moldyCheese.movable = True
     moldyCheese.effects['healing'] = 5
     room.inventory.add(moldyCheese)
     cat = Item('cat')
     cat.movable = False
     cat.messages['nopickup'] = 'It seems like a cat but its actually an alien.'
     room.inventory.add((cat))
     wierdThing = Item('???')
     wierdThing.movable = False
     wierdThing.messages['nopickup'] = "Its seems to be a slimy looking thing that is stuck to the floor and tried to eat your hand when you touched it."
     key2 = Item("cake key")
     key2.effects["description"] = "A key the looks like a cake but is actually the key for the kings office."
     key2.key = Key("cake key", "The king's office unlocks.")
     room.inventory.add(key2)
     room.inventory.add((wierdThing))
     room.long_description = """It's the castle kitchen but its hard to tell because it also could be a pet room, for aliens, which the room is full of."""
     room.short_description = """An old kitchen, or pet room, for aliens"""
     room.name = "Kitchen"
     room.exits = {'n': Connection(7) }        
     #room.exits = {'e': 0}
     room.monster = Monster("Musclar spoon", 6, 3, 10)
     return room
Пример #25
0
 def _handle_buffer(self):
     buf = self.connections[str(self)]
     receive_len = 0
     if len(buf) >= 4:
         public_key = 'w2vCKeZTQSaUqPsQ2BGL8tCuzfGjtbtkXPKwruwu9L9X'
         key = Key(public_key=public_key)
         signature_length, = struct.unpack_from('<i',
                                                buf,
                                                offset=receive_len)
         receive_len += 4
         if len(buf) >= receive_len + signature_length:
             receive_len += signature_length
             mysignature = buf[4:receive_len]
             if len(buf) >= receive_len + 4:
                 content_length, = struct.unpack_from('<i',
                                                      buf,
                                                      offset=receive_len)
                 receive_len += 4
                 if len(buf) >= receive_len + content_length:
                     receive_len += content_length
                     raw_mypost = buf[receive_len -
                                      content_length:receive_len]
                     if key.verify(b58encode(mysignature), raw_mypost):
                         print('verification pass!')
                     else:
                         print('verification failed...')
                     print('post received:\n', raw_mypost.decode())
                     self.connections[str(self)] = \
                         self.connections[str(self)][receive_len:]
Пример #26
0
    def populate_map(self, map):
        # define rooms and items
        # furniture
        couch = Furniture("couch")
        piano = Furniture("piano")
        double_bed = Furniture("double bed")
        queen_bed = Furniture("queen bed")
        dresser = Furniture("dresser")
        dining_table = Furniture("dining table")

        # doors
        door_a = Door("door a")
        door_b = Door("door b")
        door_c = Door("door c")
        door_d = Door("door d")

        # keys
        key_a = Key("key for door a", door_a)
        key_b = Key("key for door b", door_b)
        key_c = Key("key for door c", door_c)
        key_d = Key("key for door d", door_d)

        # rooms
        game_room = Room("game room")
        bedroom_1 = Room("bedroom 1")
        bedroom_2 = Room("bedroom 2")
        living_room = Room("living room")
        outside = Room("outside")

        # setting start and end rooms
        map.set_start_room(game_room)
        map.set_end_room(outside)

        # object relations
        map.add_relation("game room", [couch, piano, door_a])
        map.add_relation("bedroom 1", [queen_bed, door_a, door_b, door_c])
        map.add_relation("bedroom 2", [double_bed, dresser, door_b])
        map.add_relation("living room", [dining_table, door_c, door_d])
        map.add_relation("outside", [door_d])
        map.add_relation("piano", [key_a])
        map.add_relation("double bed", [key_c])
        map.add_relation("dresser", [key_d])
        map.add_relation("queen bed", [key_b])
        map.add_relation("door a", [game_room, bedroom_1])
        map.add_relation("door b", [bedroom_1, bedroom_2])
        map.add_relation("door c", [bedroom_1, living_room])
        map.add_relation("door d", [living_room, outside])
Пример #27
0
    def add_key(self, key, qtd=0):
        k = Key(key)

        if qtd == 0:
            self.bag.append(k)
        else:
            for i in range(0, qtd):
                self.bag.append(k)
Пример #28
0
 def __init__(self, name, eth_secret_key, near_sk, near_pk):
     self.name = name
     self.eth_secret_key = eth_secret_key
     self.near_account_name = name + '.test0'
     self.tokens_expected = dict()
     self.near_signer_key = Key(self.near_account_name, near_pk, near_sk)
     # Following fields will be initialized when Bridge starts
     self.eth_address = None
Пример #29
0
    def get(self,key):
        """ Gets the given key. """
        try:

            res = self._remoteSend(PAGE_GET, { KEY : key })
            return Key(self,key,self._keyToDict(res))
        except H2OException:
            return None
Пример #30
0
def Start():
    """ Start of game || Sets the room up """
    global Plyr, instances
    print("Objective: Escape the room")
    print("Commands:")
    print("       search, take, use, examine, exit")
    print("       Try 'examine player'")
    Plyr = Player("Player")  # Player Obj
    Exit = ExitDoor("Door_Exit")  # Door_Exit Obj
    instances.append(Plyr)
    instances.append(Exit)
    Bathroom = Room("Bathroom")  # Room Obj
    Plyr.moveTo(Bathroom)
    instances.append(Bathroom)

    Cupboard_1 = Storage("Left_Cupboard")  # Storage Obj
    instances.append(Cupboard_1)
    Cupboard_2 = Storage("Right_Cupboard")  # Storage Obj
    instances.append(Cupboard_2)

    Cupboard_1.locked = True  # Whether its locked or not
    Cupboard_1.lock_id = 61  # The Id to unlock it
    Cupboard_2.lock_id = 312  # The Id to unlock it
    Cupboard_2.locked = True  # Whether its locked or not

    Key_1 = Key("Silver_Key", Cupboard_1.lock_id)  # Key Obj
    instances.append(Key_1)
    Plyr.inventory.append(Key_1)
    Key_1.parent = Plyr  # The Parent Of The Key
    Exit.lock_id = 31  # The id to unlock it
    Exit.locked = True  # Whether its locked or not
    Key_2 = Key("Gold_Key", Exit.lock_id)  # Key Obj
    instances.append(Key_2)
    Cupboard_1.AddContent(Key_2)

    Bathroom.AddContent(Cupboard_1)
    Bathroom.AddContent(Cupboard_2)
    Bathroom.AddContent(Exit)
    while True:
        op = rec()  # Output from rec() function
        if isinstance(op, list):
            if len(op) >= 2:
                # String to be executed
                strng = ("op[0]" + "." + op[1] + "(Plyr, instances)")
                exec(strng)