Пример #1
0
	def sender_verify_forward(self, mailfrom, rcpttos, msg):
		""" Forwards mail to user of our service.
		The criteria for forwarding to user is that there is only 1
		recipient and the sender is a noreply for a supported email service;
		"""

		if len(rcpttos) != 1:
			return

		# Must be using our servername
		prcpt = Address(rcpttos[0])
		username = prcpt.parse_user_address()

		if not username:
			return

		# Must be a user of our service
		userdata = self.db.get_user(username=username)

		if userdata == False:
			return
		
		# Now we can forward 
		user = User(**userdata)

		logging.debug('Forwarding verification mail to service user at %s', \
			      user.get_forwarding_address())

		self.send(mailfrom, [user.get_forwarding_address()], msg)

		return
Пример #2
0
 def createAddr(self, ):
     # eckey = EC_KEY(int(os.urandom(32).encode('hex'), 16))
     pk = EC_KEY(int(os.urandom(32).encode('hex'), 16))
     addr = Address()
     addr.priv = SecretToASecret(getSecret(pk), True)
     addr.addr = getAddrFromPrivateKey(addr.priv)
     self.addresses.append(addr)
Пример #3
0
    def test_mask_address_parts(self):
        index = u'123456'
        country = u'Российская Федерация'
        region = u'Московская область'
        subregion = u'Подольский район'
        settlement = u'Подольск'
        street = u'Малая'
        house = u'234'
        poi = u'Станция Канавка'
        raw_address = 'sdlkjsldjflsdfjksdjffedsjdnv'

        address = Address(
            raw_address=raw_address,
            index=index,
            country=country,
            region=region,
            subregion=subregion,
            settlement=settlement,
            street=street,
            house=house,
            poi=poi
        )

        used_parts = ['index', 'country']
        new = address.mask_address_parts(used_parts)
        expected = Address(raw_address=raw_address,
                           index=index, country=country)
        self.assertEqual(new, expected)

        used_parts = ['region', 'settlement']
        new = address.mask_address_parts(used_parts)
        expected = Address(raw_address=raw_address,
                           region=region, settlement=settlement)
        # import ipdb; ipdb.set_trace()
        self.assertEqual(new, expected)
Пример #4
0
 def test_address_generation(self):
     test_key = 'a' * 32
     address = Address.new(test_key)
     self.assertEqual(address.privkey,
         "5JZB2s2RCtRUunKiqMbb6rAj3Z7TkJwa8zknL1cfTFpWoQArd6n")
     self.assertEqual(address.rawPrivkey(), test_key)
     self.assertTrue(Address.new())
Пример #5
0
def FromStructure(root, address=[]):
	''' Returns an op that inserts the node at address (and its descendants) to root '''
	address = Address(address)

	if len(address) > 0:
		pos = address.position(root)
		return FromNode(address.resolve(root), pos) + address.parent
	else:
		return FromChildren(root)
Пример #6
0
    def test_equal(self):
        addr1 = Address()
        addr2 = Address()
        self.assertEqual(addr1, addr2)

        for key, val in addr1.__dict__.iteritems():
            addr1.__dict__[key] = 'qwerty' + unicode(val)
            self.assertNotEqual(addr1, addr2)
            addr2.__dict__[key] = 'qwerty' + unicode(val)
            self.assertEqual(addr1, addr2)
Пример #7
0
 def test_organisation_address_allocation(self):
     a = Address('Seaburn Road', 'Nottingham')
     a.HouseNumber = '155'
     a.LocalityName = 'Toton'
     a.PostCode = 'NG9 6HF'
     c = Country('United Kingdom')
     a.Country = c
     self.Organisation.Address = a
     
     self.assertEqual(self.Organisation.Address.AddressLine1(),'155, Seaburn Road')
     self.assertEqual(self.Organisation.Address.AddressLine2(), 'Toton')
     self.assertEqual(self.Organisation.Address.Town, 'Nottingham')
     self.assertEqual(self.Organisation.Address.PostCode, 'NG9 6HF')
     self.assertEqual(self.Organisation.Address.Country.Name, 'United Kingdom')
Пример #8
0
 def fromproto(self, value):
     """ Sets properties from list. """
     # TODO: type checking
     value = list(value)
     self.code = value[0]
     self.address = Address(value[1])
     self.additional = value[2:]
Пример #9
0
class CreditCard:
    def __init__(self):
        self.name = ""
        self.number = ""
        self.mailing_address = Address()
        self.billing_address = Address()

    def display(self):
        print(self.name)
        print(self.number)

        print("Mailing Address:")
        self.mailing_address.display()

        print("Billing Address:")
        self.billing_address.display()
Пример #10
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        user = users.get_current_user()
        query = Address.query()
        data = query.fetch()

        if user == None:
            template_values = {
                'login_url': users.create_login_url(self.request.uri),
                'addresses': data
            }

            template = JINJA_ENVIRONMENT.get_template('mainpage_guest.html')
            self.response.write(template.render(template_values))
            return

        myuser_key = ndb.Key('MyUser', user.user_id())
        myuser = myuser_key.get()
        if myuser == None:
            myuser = MyUser(id=user.user_id())
            myuser.put()

        template_values = {
            'logout_url': users.create_logout_url(self.request.uri),
            'addresses': data
        }
        template = JINJA_ENVIRONMENT.get_template('view.html')
        self.response.write(template.render(template_values))

        if self.request.get('button') == 'Cancel':
            self.redirect('/')
Пример #11
0
def menu():
    global run
    print('-' * 40)
    print(
        'Please select option \n (1)  Create user\n (2)  List users\n (3)  Exit'
    )

    choice = input('Your choice: ').lower()

    if choice in ('1', '2', '3'):
        if int(choice) == 1:  # create user
            print('-' * 40)
            new_user_fname = input('Enter first name: ')
            new_user_lname = input('Enter last name: ')
            new_user_age = int(input('Enter age: '))
            new_user_street = input('Enter street: ')
            new_user_city = input('Enter city: ')

            #  create address object
            new_user_address = Address(new_user_street, new_user_city)

            #  create user object
            myuserdatabase.create_user(new_user_fname, new_user_lname,
                                       new_user_age, new_user_address)
            print('-' * 40)
        if int(choice) == 2:
            print(myuserdatabase)
        if int(choice) == 3:
            run = False
            print('Exiting...')
    else:
        print('Invalid choice')
Пример #12
0
def viewJob(id):
    session['message'] = None
    if (session.get("account") is None):
        return render_template('error.html')

    job = Job.getJobInfo(conn, id)
    acceptor = Job.getAcceptor(conn, id)
    # Only the owner of this Job and the acceptor of this job can view the detail of this job
    if (job['requestoremail'] == session['account']['email']
            or (acceptor is not None
                and acceptor['acceptoremail'] == session['account']['email'])):
        trans = Job.getAllTransactions(conn, id)
        rate = Job.getRating(conn, id)
        messages = Message.getAllMessages(conn, id)
        validAddress = Address.getAllAddressInCityState(
            conn, job['requestoremail'], job['jobcity'], job['jobstate'])
        acc = Job.getAcceptedTransaction(conn, id)
        return render_template('job.html',
                               job=job,
                               trans=trans,
                               messages=messages,
                               rate=rate,
                               validAddress=validAddress,
                               acc=acc)

    return render_template('error.html')
Пример #13
0
    def purge_old_versions(self):
        """Remove from the cache DODAGs whose version has been updated"""
        # retrieves all unique DODAG IDs
        dodagIDs = set()
        for dodag in self.__dodag_cache:
            dodagIDs.add(dodag.dodagID)

        for dodagID in dodagIDs:
            # it could probably be optimized, as I go through the cache 3 times in total
            latest_version = None
            for dodag in self.__dodag_cache: # find the more recent cache entry for this DODAG
                if dodag.dodagID == dodagID:
                    if latest_version is None:
                        latest_version = dodag.version
                    elif dodag.version > latest_version:
                        latest_version = dodag.version

            # remove all old DODAG
            for (index, dodag) in reversed(list(enumerate(self.__dodag_cache))):
                if dodag.dodagID == dodagID \
                   and dodag.version < latest_version:
                    # this DODAG should already have been migrated (because
                    # there is a new version), thus it has no reason to still
                    # be active
                    assert not dodag.active
                    logger.debug("Removing old DODAG %s (version %d)" % (repr(Address(dodag.dodagID)), dodag.version.get_val()))
                    dodag.poison()
                    dodag.cleanup()
                    del self.__dodag_cache[index]
                    del dodag
 def test_step10_work_and_address_not_eq(self):
     from address import Address
     from work_address import WorkAddress
     first = Address("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66")
     second = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska",
                          "6/66", "Hobbit sp. z o.o.")
     self.assertNotEqual(first, second)
Пример #15
0
    def __str__(self):
        string = "address: %s\n" % self.address
        string += "rank: %d\n" % self.rank
        string += "interface: %s\n" % self.iface
        string += "dodag: %s" % repr(Address(self.dodag.dodagID))

        return string
Пример #16
0
 def test_login(self):
     '''
   test  to login into our credentials
   '''
     self.new_address.save_address()
     test_address = Address("Ronah", "*****@*****.**", "ronah123")
     self.assertTrue(self.new_address.email)
Пример #17
0
    def receive(self, size):
        assert (size > 0)

        if self.socket is None:
            return False

        try:
            data, addr = self.socket.recvfrom(size)
            if not data:
                return False

            deserialized = pickle.loads(data)

            val = socket.inet_aton(addr[0])
            a = int(val[0])
            b = int(val[1])
            c = int(val[2])
            d = int(val[3])

            sender = Address(a=a, b=b, c=c, d=d, port=addr[1])
        except Exception as e:
            # print("Exception:",e)
            deserialized = None
            sender = None

        return deserialized, sender
Пример #18
0
 def store(self, seg_name, n_bytes, replica=0):
     if not os.path.isdir(CACHE_DIR):
         os.mkdir(CACHE_DIR)
     self.conn.sendall('OK'.encode())
     chunk = 0
     data = b''
     # data = self.conn.recv(8 * 1024)
     while True:
         data += self.conn.recv(int(n_bytes))
         # data += self.conn.recv(8*1024)
         chunk = len(data)
         if chunk == int(n_bytes):
             break
     print('file recieved')
     self.conn.sendall(str(len(data)).encode())
     print('writing file')
     f = open('{}/{}'.format(CACHE_DIR, seg_name), 'wb+')
     f.write(data)
     print('file written')
     f.close()
     if not int(replica):
         ip, port = self.state.successor.ip, self.state.successor.port
         s = self.send(Address(ip, port),
                       'store {} {} {}'.format(seg_name, n_bytes, 1))
         if s.recv(512).decode('utf-8') == 'OK':
             f = open('{}/{}'.format(CACHE_DIR, seg_name), 'rb+')
             print("sending replica...")
             s.sendfile(f, 0, int(n_bytes))
             print("waiting for ack...")
             data = s.recv(1024).decode('utf-8')
             print('ack received')
             s.close()
             f.close()
Пример #19
0
    def process_request(self, command, request):
        # default : "" = not respond anything
        result = json.dumps("")
        if command == 'get_successor':
            successor = self.successor()
            result = json.dumps(
                (successor.address_.ip, successor.address_.port))
        if command == 'get_predecessor':
            # we can only reply if we have a predecessor
            pred = self.predecessor_
            if pred != None:
                predecessor = pred
                result = json.dumps(
                    (predecessor.address_.ip, predecessor.address_.port))
        if command == 'find_successor':
            successor = self.find_successor(int(request))
            result = json.dumps(
                (successor.address_.ip, successor.address_.port))
        if command == 'closest_preceding_finger':
            closest = self.closest_preceding_finger(int(request))
            result = json.dumps((closest.address_.ip, closest.address_.port))
        if command == 'notify':
            npredecessor = Address(
                request.split(' ')[0], int(request.split(' ')[1]))
            self.notify(Remote(npredecessor))
        if command == 'get_successors':
            result = json.dumps(self.get_successors())

        # or it could be a user specified operation
        for t in self.command_:
            if command == t[0]:
                result = t[1](request)
            self.log('sending response: ' + result)

        return result
Пример #20
0
 def from_json(self, json):
     required = ['address_list']
     if not all(k in json for k in required):
         logging.warning('value missing in ["address_list"]')
         return False
     address_list = json["address_list"]
     if not isinstance(address_list, list):
         logging.warning('address_list should be type<list>')
         return False
     for address in address_list:
         a = Address()
         if a.from_json(address):
             self.add_address(a)
         else:
             return False
     return self.valid()
Пример #21
0
    def send_segment(self, file_, seg_id, start, n_bytes, seg_given=False):
        if seg_given:  # entire segment (and thus its name) was given
            seg_name = '{}'.format(file_.split('/',
                                               1)[-1])  # strip "cache/" prefix
        else:  # file is being dispersed, so we must create segment name
            seg_name = '{}_{}'.format(file_.split('/')[-1:][0], seg_id)

        # Find the chord node in which to store the given segment,
        # and send a request to that node.
        ip, port = self.find_successor(hash_(seg_name)).split(':')
        s = self.send(Address(ip, port),
                      'store {} {}'.format(seg_name, n_bytes))

        if s.recv(512).decode('utf-8') == 'OK':
            f = open(file_, 'rb+')
            print("sending file...")
            s.sendfile(f, int(start), int(n_bytes))
            print("waiting for ack...")
            data = s.recv(1024).decode('utf-8')
            print('ack received')
            s.close()
            f.close()
            return 'segment {}: {} bytes sent, {} recieved'.format(
                seg_id, n_bytes, data)
        else:
            s.close()
            return 'Error sending segment {} to {}:{}'.format(seg_id, ip, port)
Пример #22
0
 def __init__(self, address=None, group=None, network=None, connection=None):
     """Initialize instance of Node class"""
     
     # Address
     self.address = address
     if address is None:
         self.address = Address()
     
     # Group
     self.group = group
     if group is None:
         self.group = Group(None, address, [])
     
     # Network
     self.network = network
     if network is None:
         self.network = Network()
     
     # Connection
     self.connection = connection
     if connection is None:
         self.connection = Connection()
     
     # Dictionary of sent messages waiting for an ack
     # Key: Message identifier
     # Value: 
     self.waiting_for_ack = dict()
Пример #23
0
def get_user_input():
    prompts = ["Enter a package ID: ", "Enter delivery address: ", "Enter delivery city: ", "Enter delivery zip code: ", "Enter delivery state: ", "Enter delivery deadline: ", "Enter package weight: "]
    input_parameters = ['27', '1060 Dalton Ave S', 'Salt Lake City', '84104', 'UT', 'EOD', '5']
    # input_parameters = ['9', '300 State St', 'Salt Lake City', '84103', 'UT', 'EOD', '2']
    input_parameters = []
    print("Enter the following information for the package:")
    for prompt_index in range(len(prompts)):
        user_input = input(prompts[prompt_index])
        input_parameters.append(user_input)

    input_address = Address(input_parameters[1], input_parameters[2], input_parameters[3], input_parameters[4])
    input_package = Package(int(input_parameters[0]), input_address, float(input_parameters[6]))

    str_time = input_parameters[5]
    valid_selection = False
    while not valid_selection:
        if ':' in str_time:
            split_time = input_parameters[5].split(':')
            hour = split_time[0]
            minute = split_time[1]
            if not hour.isnumeric() or not minute.isnumeric():
                str_time = input("Invalid time. Please, re-enter time (HH:MM): ")
            elif int(hour) <= 0 or int(hour) > 23 or int(minute) < 0 or int(minute) > 60:
                str_time = input("Invalid time. Please, re-enter time (HH:MM): ")
            else:
                deadline = time(int(hour), int(minute, 0))
                valid_selection = True
        elif str_time == 'EOD':
            deadline = time(23, 0, 0)
            valid_selection = True

    input_package.deadline = deadline
    return input_package
Пример #24
0
    def load_addresses(self, passKey):
        '''Load wallet from a json file
         {
            'keys':[{'addr':unicode,
                     'priv':unicode,
                     'label':unicode,
                     'doubleEncrypted': bool,
                     'sharedKey':unicode},
                     'tag':int,
                     'balance':int,
                     'txs:[],]
            'wallet': {'balance': int}
         }'''

        with open(
            os.path.join(os.path.expanduser('~'),
                         '.bitpurse.wallet'), 'rb') as fh:
            payload = fh.read()

            payload = json.loads(self.decrypt(passKey,
                                              payload.decode('base64',
                                                             'strict')))
            self.settings.passKey = passKey

            self.addresses = [Address(jsondict=address)
                              for address in payload['keys']]

            self.balance = payload['balance']
Пример #25
0
def create_customer():
    """
    Menu entry 1: Create Customer
    """
    c = Customer('', '', Address('', '', '', '', '', '', '', ''), '', '', 0,
                 '', {})
    c.input_customer()
Пример #26
0
def get_address_from_user():  #import us addresses?
    ''' Returns a Address class with the data entered from user '''
    return Address(
        name=get_name_from_user(),
        street=input('Street Address? ').capitalize(),
        city=input('City? ').upper(),  #import cities in funct?
        state=input('State? ').upper(),  #import states
        zipcode=get_zip())
Пример #27
0
 def test_valid_address(self):
     """Test the address generation goes through:
     from https://en.bitcoin.it/wiki/Private_key
     5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF
     maps to 1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj
     """
     address = Address(*self.keys)
     self.assertTrue(address)
Пример #28
0
    def predecessor(self):
        self.send('get_predecessor')

        response = self.recv()
        if response == "":
            return None
        response = json.loads(response)
        return Remote(Address(response[0], response[1]))
Пример #29
0
class CreditCard:
    """ Contains a credit card that has two addresses"""
    def __init__(self):
        self.name = ""
        self.number = ""
        self.mailing_address = Address()
        self.billing_address = Address()

    def display(self):
        print(self.name)
        print(self.number)

        print("Mailing Address:")
        self.mailing_address.display()

        print("Billing Address:")
        self.billing_address.display()
Пример #30
0
    def _get_reference(self):
        """ Returns a reference to this object suitable for binding. """

        reference = Reference(
            class_name=self.__class__.__name__,
            addresses=[Address(type='py_context', content=self.namespace)])

        return reference
Пример #31
0
 def test_master_key_address_generation(self):
     test_master_key = '0' * 32
     color_string = '0'
     index = 0
     address = Address.fromMasterKey(test_master_key, color_string, index)
     self.assertEqual(
         address.privkey,
         '5KjWca2NdTm5DMdPC1WBzEtaZ86wVL1Sd7FNnKBvF6H782HgABK')
Пример #32
0
def profile():
    #Only WORKER can access this page
    if (session.get("account") is None):
        return render_template('error.html')

    email = session['account']['email']
    addresses = Address.getAllAddress(conn, email)
    return render_template('profile.html', addresses=addresses)
Пример #33
0
    def importFromBlockchainInfoWallet(self, passKey, guid, key,
                                       skey, doubleKey=''):
        '''Import wallet from BlockChain.info MyWallet services'''

        # Test if password match at least for the first key
        if doubleKey:
            self.testDoublePK(doubleKey)

        req = 'https://blockchain.info/wallet/' \
              + '%s?format=json&resend_code=false' % (guid)

        # opener = urllib2.build_opener()
        # fh = opener.open(req)
        # encryptedWallet = json.loads(fh.read())['payload']
        encryptedWallet = getDataFromChainblock(req)['payload']

        try:
            data = self.decrypt(key,
                                encryptedWallet.decode('base64', 'strict'))
        except:
            raise WrongPassword('Unknow login')

        try:
            data = json.loads(data)
        except:
            raise WrongPassword('Incorrect password')

        if 'double_encryption' in data:
            isDoubleEncrypted = bool(data['double_encryption'])
        else:
            isDoubleEncrypted = False

        if 'sharedKey' in data:
            sharedKey = data['sharedKey']
        else:
            sharedKey = 'BitPurse'

        for address in data['keys']:
            if not self.isMine(address['addr']):
                address['sharedKey'] = sharedKey
                address['doubleEncrypted'] = isDoubleEncrypted
                if 'tag' not in address:
                    address['tag'] = 0

                if isDoubleEncrypted:
                    address['priv'] = self.decryptPK(address['priv'],
                                                     skey, sharedKey)
                    address['doubleEncrypted'] = False
                    if doubleKey:
                        address['priv'] = self.encryptPK(address['priv'],
                                                         doubleKey,
                                                         address['sharedKey'])
                        address['doubleEncrypted'] = True

                self.addresses.append(Address(jsondict=address))

        print 'Importing Blockchain.info MyWallet'
        self.store(passKey)
Пример #34
0
    def __init__(self, iface, address, dodag, rank, dtsn):
        self.iface = iface
        self.address = address
        self.rank = rank
        self.dodag = dodag
        self.preferred = False
        self.dtsn = Lollipop(dtsn)

        assert Address(self.address).is_linklocal()
Пример #35
0
	def run(self):
		# should have a threadpool here :/
		# listen to incomming connections
		self.socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket_.bind((self.address_.ip, int(self.address_.port)))
		self.socket_.listen(10)

		while 1:
			self.log("run loop")
			try:
				conn, addr = self.socket_.accept()
			except socket.error:
				self.shutdown_ = True
				break

			request = read_from_socket(conn)
			command = request.split(' ')[0]

			# we take the command out
			request = request[len(command) + 1:]

			# defaul : "" = not respond anything
			result = json.dumps("")
			if command == 'get_successor':
				successor = self.successor()
				result = json.dumps((successor.address_.ip, successor.address_.port))
			if command == 'get_predecessor':
				# we can only reply if we have a predecessor
				if self.predecessor_ != None:
					predecessor = self.predecessor_
					result = json.dumps((predecessor.address_.ip, predecessor.address_.port))
			if command == 'find_successor':
				successor = self.find_successor(int(request))
				result = json.dumps((successor.address_.ip, successor.address_.port))
			if command == 'closest_preceding_finger':
				closest = self.closest_preceding_finger(int(request))
				result = json.dumps((closest.address_.ip, closest.address_.port))
			if command == 'notify':
				npredecessor = Address(request.split(' ')[0], int(request.split(' ')[1]))
				self.notify(Remote(npredecessor))
			if command == 'get_successors':
				result = json.dumps(self.get_successors())

			# or it could be a user specified operation
			for t in self.command_:
				if command == t[0]:
					result = t[1](request)

			send_to_socket(conn, result)
			conn.close()

			if command == 'shutdown':
				self.socket_.close()
				self.shutdown_ = True
				self.log("shutdown started")
				break
		self.log("execution terminated")
Пример #36
0
def main():
    usage = """
        FUSEDFS: A filesystem implemented on top of a DHT.
    """ + fuse.Fuse.fusage

    if len(sys.argv) == 2:
        local = Local(Address("127.0.0.1", sys.argv[1]))
    else:
        local = Local(Address("127.0.0.1", sys.argv[1]),
                      Address("127.0.0.1", sys.argv[2]))

    local.start()
    server = FUSEDFS(local,
                     version="%prog " + fuse.__version__,
                     usage=usage,
                     dash_s_do='setsingle')
    server.parse(errex=1)
    server.main()
Пример #37
0
 def to_address(self, testnet=False):
     # TODO maybe pass script type ?
     if self.is_p2pkh_script_pubkey():
         h160 = self.cmds[2]
         prefix = P2PKH_TEST_PREFIX if testnet else P2PKH_MAIN_PREFIX
         return Address(encode_base58_checksum(prefix + h160))
     elif self.is_p2sh_script_pubkey():
         h160 = self.cmds[1]
         prefix = P2SH_TEST_PREFIX if testnet else P2SH_MAIN_PREFIX
         return Address(encode_base58_checksum(prefix + h160))
     elif self.is_p2wpkh_script_pubkey():
         h160 = self.cmds[1]
         return Address(h160_to_p2wpkh(h160, witver=0, testnet=testnet))
     elif self.is_p2wsh_script_pubkey():
         h256 = self.cmds[1]
         return Address(h256_to_p2wsh(h256, witver=0, testnet=testnet))
     else:
         return None
Пример #38
0
def handleDIS(interfaces, message):
    """Handler for DIS messages"""
    dis = DIS()
    payload = dis.parse(message.msg)

    if gv.dodag_cache.is_empty():
        logger.debug(
            "Dropping DIS message: the node does not belong to any DODAG")
        return

    # the following line returns None when no Solicited Information Option is
    # present
    solicited_information = findOption(payload,
                                       RPL_Option_Solicited_Information)

    version = None
    instanceID = None
    dodagID = None
    if solicited_information:
        if solicited_information.V:
            version = solicited_information.version

        if solicited_information.I:
            instanceID = solicited_information.instanceID

        if solicited_information.D:
            dodagID = solicited_information.DODAGID

    if Address(message.dst).is_RPL_all_nodes():
        # if there is no Solicited Information option, the trickle timer
        # records an inconsistency
        # or
        # if the Solicited Information option is set and it matches
        # one or more DODAG in the cache, the trickle timer associated
        # to these DODAG records an inconsistency

        logger.debug("DIS request is a multicast, "\
                      "sending DIO on all registered interfaces")

        dodags = gv.dodag_cache.get_dodag(dodagID, version, instanceID)

        for dodag in dodags:
            dodag.DIOtimer.hear_inconsistent()

    else:  # this is a unicast DIS
        if solicited_information:
            dodags = gv.dodag_cache.get_dodag(dodagID, version, instanceID)
            logger.debug("DIS request is unicast, with solicited information, "\
                          "sending unicast DIO(s)")
            for dodag in dodags:
                dodag.sendDIO(message.iface, message.src)
        else:  # this might not be in the RFC, but it makes sense to only send DIO from the active DODAG
            logger.debug("DIS request is unicast, with no solicited information, "\
                          "sending unicast DIO")
            dodag = gv.dodag_cache.get_active_dodag()
            if dodag:
                dodag.sendDIO(message.iface, message.src)
Пример #39
0
class TurBoDebugger:

    option = 0
    rc = 0
    proc = 0

    def __init__(self, proc_name):

        self.mw = MemWorker(proc_name)

    def run_game(self, path):

        self.rc = subprocess.Popen(path, shell=True)

    def options(self):

        print("what to do?")
        print("  1 search for text")
        print("  2 go to offset")
        self.option = int(input("    1 or 2 :> "))

        if self.option == 1:
            self.search_text()
        elif self.option == 2:
            self.go_offset()

    def search_text(self):

        text = input("Text search :> ")

        l = [x for x in self.mw.mem_search(text)]

        a = [x for x in l]

        print(l)
        print(a)

        val = int(input("Select Offset :> "))

        a[val].dump()

    def go_offset(self):

        self.offset = input("offset :> ")
        print("go for %s" % self.offset)

        self.proc = self.mw.get_process()

        self.address = Address(self.offset, self.proc)

        data = self.address.read(type="bytes")

        print(int(data))
Пример #40
0
    def go_offset(self):

        self.offset = input("offset :> ")
        print("go for %s" % self.offset)

        self.proc = self.mw.get_process()

        self.address = Address(self.offset, self.proc)

        data = self.address.read(type="bytes")

        print(int(data))
Пример #41
0
class venue_address_test(unittest.TestCase):
    def setUp(self):
        self.parser = Address()

    def test_expression_examples(self):
        for test in corpus:
            result = self.parser.parse(test)
            self.assertNotEqual(result, None, "No match for: {}".format(test))
            self.assertTrue(any(result), "No match for: {}".format(test))

    def test_expressions(self):
        with open("parse/address/expressions.yaml", 'r') as f:
            check_expression(self, yaml.load(f))
Пример #42
0
	def __init__(self, local_address, remote_address = None):
		self.address_ = Address(quick_lazy_ip(),local_address.port)
		self.local_addr =  local_address
		print("self id = %s" % self.id())
		self.shutdown_ = False
		# list of successors
		self.successors_ = []
		# join the DHT
		self.join(remote_address)
		# we don't have deamons until we start
		self.daemons_ = {}
		# initially no commands
		self.command_ = []
Пример #43
0
def main():
    print '-- Geo Ingestion Python Script Starting --'

    f = open('map.osm', 'r')
    map_xml_text = f.read()
    tree = ET.parse('map.osm')
    root = tree.getroot()

    complete_address_count = 0
    partial_address_count = 0

    for leaf in root:
        if leaf.tag == 'node':
            address = Address(leaf)

            if address.is_valid_address():

                complete_address_count += 1

                print address

                url = 'http://localhost:9200/geo/osm/%s' % address.id
                r = requests.put(url, data=json.dumps(address.to_json()))
                if r.status_code in (200, 201, 202):
                    print 'Success!'
                else:
                    print 'Failure...'
            elif address.is_partial_valid_address():

                partial_address_count += 1

                print 'Partial address found!', address

    print 'Total Complete Address Counts: ', complete_address_count
    print 'Total Partial Address Counts: ', partial_address_count

    print '-- Completed Script --'
Пример #44
0
    def test_subaddress_of(self):
        addr1 = Address()
        addr2 = Address()
        self.assertTrue(addr1.subaddress_of(addr2))

        # import ipdb; ipdb.set_trace()
        for key, val in addr1.__dict__.iteritems():
            if key == '_raw_address':
                continue
            addr1.__dict__[key] = 'qwerty' + unicode(val)
            self.assertTrue(addr2.subaddress_of(addr1))
            self.assertFalse(addr1.subaddress_of(addr2))
            addr2.__dict__[key] = 'qwerty' + unicode(val)
Пример #45
0
    def importWatchOnly(self, passKey, address, label='Undefined'):
        addr = Address()
        addr.addr = address
        addr.sharedKey = 'BitPurse'
        addr.watchOnly = True
        addr.priv = ''
        addr.label = label

        self.addresses.append(addr)
        self.store(passKey)
Пример #46
0
 def init_new_wallet(self):
     """Initialize the configuration if this is the first time
     we're creating addresses in this wallet.
     Returns the "dwam" part of the configuration.
     """
     if not 'dw_master_key' in self.config:
         # privkey is in WIF format. not exactly
         # what we want, but passable, I guess
         master_key = Address.new().privkey
         self.config['dw_master_key'] = master_key
     dwam_params = {
         'genesis_color_sets': [],
         'color_set_states': []
         }
     self.config['dwam'] = dwam_params
     return dwam_params
Пример #47
0
def fake_transaction(model=None):
    key = ecdsa.SigningKey.from_string(
        "\xe8\x00\xb8\xd4\xa1b\xb7o\x0f;\xf2\xcf\xca\xfd\x1a$\xb9\xa9"
        "\xeb\x0b\x08X\x9f}9C\xe4\x88\xfdD\x11b", curve=ecdsa.curves.SECP256k1)

    address = Address.fromPrivkey(key)
    script = tools.compile(
        "OP_DUP OP_HASH160 {0} OP_EQUALVERIFY OP_CHECKSIG".format(
            address.rawPubkey()[1:-4].encode("hex"))).encode("hex")
    utxo = utxodb.UTXO("D34DB33F", 0, 1, script)
    utxo.address_rec = object()
    utxo.address_rec = AddressRec(address)
    txin = txspec.ComposedTxSpec.TxIn(utxo)
    txout = txspec.ComposedTxSpec.TxOut(1, address.pubkey)
    composed = txspec.ComposedTxSpec([txin], [txout])
    return txcons.SignedTxSpec(model, composed, False), address
Пример #48
0
    def from_json(cls, json_blob):
        blob = copy.deepcopy(json_blob)

        json = blob.pop("data", blob)
        obj = json.pop("ASSET", json)

        result = {}
        for k, v in obj.iteritems():
            t = k.lower()
            result[t] = v

        a = cls(result["tag"], result)

        # set ipmi object
        a.ipmi = IPMI.from_json(json.pop("IPMI"))

        # set Address (IP Address)
        a.addresses = Address.from_json(json.pop("ADDRESSES"))

        return a
Пример #49
0
    def createAddr(self, doubleKey):
        if doubleKey:
            self.testDoublePK(doubleKey)

        # eckey = EC_KEY(int(os.urandom(32).encode('hex'), 16))
        pk = EC_KEY(int(os.urandom(32).encode('hex'), 16))
        addr = Address()
        addr.priv = SecretToASecret(getSecret(pk), True)
        addr.addr = getAddrFromPrivateKey(addr.priv)
        addr.sharedKey = 'BitPurse'
        if doubleKey:
            addr.priv = self.encryptPK(addr.priv, doubleKey, addr.sharedKey)
            addr.doubleEncrypted = True

        self.addresses.append(addr)
Пример #50
0
 def start(self, addr="0.0.0.0", port=None):
     # Check if radio connected
     destaddr, error = None, False
     assert(self.radioconnected() ), "RadioRx and RadioTx have not been connected to Channel!"
     # Start server
     if port is None: port = self.options.channel_port
     self.impl.start(addr, port)
     # Get server address
     # wait for server and client to start running
     while (not self.impl.server_running() ): time.sleep(0.5)
     while (not self.impl.client_running() ): time.sleep(0.5)
     # should probably update this with correct IP address for matching
     self.addr = self.impl.recv_addr()
     self.port = self.impl.recv_port()
     print "[CHANNEL]: server and client are running, recv_addr =", (self.addr, self.port)
     # Connect to address server and register
     self.addrclient = AddrClient(self.options)
     regaddr, regport = Address.get_ip_address(ifname=self.options.ifname, ntoa=True), self.port
     if (self.addrclient.connect()<0):
         sys.stderr.write("[CHANNEL]: Could not connect with address server!\n")
         error = True
     elif (self.addrclient.register(regaddr, regport)<0):
         sys.stderr.write("[CHANNEL]: Could not connect with address server!\n")
         error = True
     else:
         destaddr = self.addrclient.get_dest_addr()
         if (destaddr < 0):
             sys.stderr.write("[CHANNEL]: Error getting destination address\n")
             error = True
     sys.stderr.write("[CHANNEL]: Destination address = %s\n"%(str(destaddr) ) )
     self.addrclient.close()
     # connect to remote destination
     if not error:
         sys.stderr.write("[CHANNEL]: Connecting  channel client to destination\n")
         self.impl.connect_client(destaddr[0], destaddr[1])
     else:
         self.stop()
         return -1
Пример #51
0
	def decode_address(self, document):
		assert document["_type"] == "address"
		address = Address(document['_id'], self.converter)
		address.miningCount = document["miningCount"]
		
		for txM in document['tx_mining']:
			address.tx_mining.append(self.getTransaction(txM))

		for txP in document['tx_payment']:
			address.tx_payment.append(self.getTransaction(txP))
	
		for txC in document['tx_credit']:
			address.tx_credit.append(self.getTransaction(txC))
	
		address.totBitCoinMined = document['totBitCoinMined']
		address.totDollarMined = document['totDollarMined']
		address.currentBitCoin = document['currentBitCoin']
		address.totFees = document['totFees']

		return address
Пример #52
0
    def importFromPrivateKey(self, passKey, privateKey,
                             label='Undefined', doubleKey=''):

        # Test if password match at least for the first key
        if doubleKey:
            self.testDoublePK(doubleKey)

        privateKey = privateKey.strip('\n')
        bc = getAddrFromPrivateKey(privateKey)
        if bc in self.getAddrAddresses():
            raise DataError('This private key is already in the wallet')

        addr = Address()
        addr.addr = bc
        addr.sharedKey = 'BitPurse'
        if doubleKey:
            privateKey = self.encryptPK(privateKey, doubleKey, addr.sharedKey)
            addr.doubleEncrypted = True
        addr.priv = privateKey
        addr.label = label

        self.addresses.append(addr)
        self.store(passKey)
Пример #53
0
 def setUp(self):
     self.Address = Address('Barrack Lane','Nottingham')
     self.Address.HouseNumber = '1'
     self.Address.PostCode = 'NG7 9AN'
Пример #54
0
 def load_from_row(row):
     return Account.get_or_create(name=row[0],
                                  type=row[1],
                                  phone=row[2],
                                  billing_address=Address.load_from_array(row[3:9]),
                                  shipping_address=Address.load_from_array(row[9:15]))
Пример #55
0
class TestAddress(unittest.TestCase):
    def setUp(self):
        self.Address = Address('Barrack Lane','Nottingham')
        self.Address.HouseNumber = '1'
        self.Address.PostCode = 'NG7 9AN'
        
    def tearDown(self):
        self.Address = None
        
    def test_address_initialisation(self):
        self.assertEqual(self.Address.StreetName, 'Barrack Lane')
        self.assertEqual(self.Address.Town, 'Nottingham')
        self.assertFalse(self.Address.IsPAFValidated())
        
    def test_paf_validation(self):
        self.assertFalse(self.Address.IsPAFValidated())        
        self.Address.SetPAFValidated()
        self.assertTrue(self.Address.IsPAFValidated())        
        
    def test_address_line_1_house_number(self):
        self.assertEqual(self.Address.AddressLine1(),'1, Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(), None)
        self.assertEqual(self.Address.AddressLine3(), None) 
        self.assertEqual(self.Address.AddressLine4(), None) 
        
    def test_address_line_1_house_name(self):        
        self.Address.HouseName = 'Maitland Flats'
        self.assertEqual(self.Address.AddressLine1(),'Maitland Flats, Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(), None)   
        self.assertEqual(self.Address.AddressLine3(), None)
        self.assertEqual(self.Address.AddressLine4(), None) 
        
    def test_address_line_1_flat_name(self):        
        self.Address.FlatName = 'Flat 5'    
        self.assertEqual(self.Address.AddressLine1(),'Flat 5, 1 Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(), None) 
        self.assertEqual(self.Address.AddressLine3(), None) 
        self.assertEqual(self.Address.AddressLine4(), None) 
        
    def test_address_line_1_flat_name_house_name(self):        
        self.Address.FlatName = 'Flat 5'    
        self.Address.HouseName = 'Maitland Flats'        
        self.assertEqual(self.Address.AddressLine1(),'Flat 5, Maitland Flats')
        self.assertEqual(self.Address.AddressLine2(),'1, Barrack Lane') 
        self.assertEqual(self.Address.AddressLine3(), None) 
        self.assertEqual(self.Address.AddressLine4(), None) 
        
    def test_address_line_2_house_number_locality(self):
        self.Address.LocalityName = 'Lenton'
        self.assertEqual(self.Address.AddressLine1(),'1, Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(), 'Lenton')
        self.assertEqual(self.Address.AddressLine3(), None)
        self.assertEqual(self.Address.AddressLine4(), None) 

    def test_address_line_2_house_name_locality(self):        
        self.Address.HouseName = 'Maitland Flats'
        self.Address.LocalityName = 'Lenton'        
        self.assertEqual(self.Address.AddressLine1(),'Maitland Flats, Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(), 'Lenton')  
        self.assertEqual(self.Address.AddressLine3(), None)   
        self.assertEqual(self.Address.AddressLine4(), None)         
        
    def test_address_line_2_flat_name_locality(self):
        self.Address.FlatName = 'Flat 5' 
        self.Address.LocalityName = 'Lenton'          
        self.assertEqual(self.Address.AddressLine1(),'Flat 5, 1 Barrack Lane')
        self.assertEqual(self.Address.AddressLine2(),'Lenton')   
        self.assertEqual(self.Address.AddressLine3(), None)         
        self.assertEqual(self.Address.AddressLine4(), None)      
        
    def test_address_line_2_flat_name_house_name_locality(self):        
        self.Address.FlatName = 'Flat 5'    
        self.Address.HouseName = 'Maitland Flats' 
        self.Address.LocalityName = 'Lenton'           
        self.assertEqual(self.Address.AddressLine1(),'Flat 5, Maitland Flats')
        self.assertEqual(self.Address.AddressLine2(),'1, Barrack Lane') 
        self.assertEqual(self.Address.AddressLine3(), 'Lenton') 
        self.assertEqual(self.Address.AddressLine4(), None)         
        
    def test_country_allocation(self):
        self.Address.Country = Country('United Kingdom')
        self.assertEqual(self.Address.Country.Name, 'United Kingdom')        
        
    def test_serialise(self):
        self.Address.Country.Name = 'United Kingdom'
        exp = '{"Town": "Nottingham", "Country": "{\\"Name\\": \\"United Kingdom\\"}", "FlatName": null, "PAFValidationDate": null, "County": null, "HouseNumber": "1", "PostCode": "NG7 9AN", "LocalityName": null, "HouseName": null, "StreetName": "Barrack Lane", "AddressLines": []}'
        s = self.Address.to_JSON()
        self.assertEqual(s,exp)
        
    def test_deserialise(self):
        self.Address.Country.Name = 'United Kingdom'        
        s = self.Address.to_JSON()
        a = Address()   
        a.LoadFromJSON(s)
        self.assertEqual(a.HouseNumber, self.Address.HouseNumber)          
        self.assertEqual(a.StreetName, self.Address.StreetName) 
        self.assertEqual(a.Town, self.Address.Town) 
        self.assertEqual(a.PostCode, self.Address.PostCode)    
        self.assertEqual(a.Country.Name, self.Address.Country.Name)           
Пример #56
0
    def test_check_zip(self):
	      addr = Address(None, self.parser)
	      addr.check_zip('12345')
	      self.assertEqual('12345', addr.zip_code)
Пример #57
0
    def test_init(self):
        index = u'123456'
        country = u'Российская Федерация'
        region = u'Московская область'
        subregion = u'Подольский район'
        settlement = u'Подольск'
        street = u'Малая'
        house = u'234'

        address = Address(
            index=index,
            country=country,
            region=region,
            subregion=subregion,
            settlement=settlement,
            street=street,
            house=house
        )

        expected = ','.join([
            index, country, region, subregion,
            settlement, street, house
        ])
        got = ','.join([
            address.index, address.country,
            address.region, address.subregion,
            address.settlement, address.street,
            address.house
        ])
        self.assertEqual(got, expected)

        address = Address()
        address.raw_address = expected + 'qwerty'
        self.assertEqual(address.raw_address, expected + 'qwerty')

        address = Address()
        address.index = index
        address.country = country
        address.region = region
        address.subregion = subregion
        address.settlement = settlement
        address.street = street
        address.house = house
        got = ','.join([
            address.index, address.country,
            address.region, address.subregion,
            address.settlement, address.street,
            address.house
        ])

        self.assertEqual(got, expected)
Пример #58
0
 def to_address(self):
     return Address.from_public_key(self.to_public_key())
Пример #59
0
    def test_init(self):
        index = u'123456'
        country = u'Российская Федерация'
        region = u'Московская область'
        subregion = u'Подольский район'
        city = u'Подольск'
        subcity = u'район Зеленый'
        street = u'Малая'
        house = u'234'
        poi = u'Станция Канавка'

        address = Address(
            index=index,
            country=country,
            region=region,
            subregion=subregion,
            city=city,
            subcity=subcity,
            street=street,
            house=house,
            poi=poi
        )

        expected = ','.join([
            index, country, region, subregion,
            city, subcity, street, house, poi
        ])
        got = ','.join([
            address.index, address.country,
            address.region, address.subregion,
            address.city, address.subcity, address.street,
            address.house, address.poi
        ])
        self.assertEqual(got, expected)

        address = Address()
        address.raw_address = expected + 'qwerty'
        self.assertEqual(address.raw_address, expected + 'qwerty')

        address = Address()
        address.index = index
        address.country = country
        address.region = region
        address.subregion = subregion
        address.city = city
        address.subcity = subcity
        address.street = street
        address.house = house
        address.poi = poi
        got = ','.join([
            address.index, address.country,
            address.region, address.subregion,
            address.city, address.subcity,
            address.street,
            address.house, address.poi
        ])

        self.assertEqual(got, expected)