Ejemplo n.º 1
0
 def setUp(self):
     self.username = helpers.make_random_string()
     self.list = ToDoList(item_type=FakeItem,
                          username=self.username,
                          db=mock.Mock())
     self.middle_char = all_chars[len(all_chars) / 2]
     print self.list
Ejemplo n.º 2
0
 def __make_token(self):
     token = make_random_string(32)
     try:
         User_ForgetPassword.objects.get(token=token)
     except User_ForgetPassword.DoesNotExist:
         self.token = token
         return
     self.__make_token()
Ejemplo n.º 3
0
 def __make_activation_code(self):
     activation_code = make_random_string(32)
     try:
         User_Activation.objects.get(activation_code=activation_code)
     except User_Activation.DoesNotExist:
         self.activation_code = activation_code
         return
     self.__make_activation_code()
Ejemplo n.º 4
0
 def __make_api_key(self):
     api_key = make_random_string(60)
     try:
         Website.objects.get(api_key=api_key)
     except Website.DoesNotExist:
         self.api_key = api_key
         return
     self.__make_api_key()
Ejemplo n.º 5
0
    def save(self):
        if not self.remember_token:
            self.remember_token = make_random_string(32)

        # clean any expired autologins of this user
        now = datetime.datetime.now()
        for ua in User_AutoLogin.objects.filter(user=self.user):
            if ua.expires_at < now:
                ua.delete()

        super(User_AutoLogin, self).save()
Ejemplo n.º 6
0
def site_screenshot(url):
    random_string = make_random_string(32)
    path = settings.TMP_IMAGES_FOLDER + random_string + '.png'
    try:
        subprocess.check_call([settings.CAPTY,\
            url,\
            path])
    except subprocess.CalledProcessError:
        return None
    data = open(path,'rd').read()
    os.remove(path)
    return data
Ejemplo n.º 7
0
def create_property(bc, host='registrar'):
    """Creates property on demand"""
    headers = {'content-type': 'application/json'}
    registrar_txn_url = 'http://{}:58336/jsonrpc'.format(host)

    input_list = [choice(list(DATABASE_WALLETS.keys()))]

    property_addr = input('New property address?')
    num_outputs = int(input('Number of new owners?'))
    total_value = 0
    output_list = list()
    btc_txn_hash = None
    for idx in range(num_outputs):
        value_i = int(input('Value to owner #' + str(idx + 1) + '?'))
        wallet_addr = input('Wallet address of owner #' + str(idx + 1) + '?')
        script = make_random_string()

        if value_i <= 0:
            print('Non-positive value invalid')
            raise ValueError('Non-positive value invalid')
        total_value += value_i

        output = Output(wallet_addr, property_addr, value_i, idx, script)
        output_list.append(output)

    if total_value != 100:
        print('Total value not equal 100, try again')
        raise ValueError('Total value not equal 100, try again')

    # create transaction
    new_transaction = Transaction(input_list, output_list, 'propGen',
                                  btc_txn_hash)
    print('Transaction hash (own chain):')
    print(new_transaction.transaction_hash)

    # send transaction to registrar
    payload = new_transaction.to_dict()
    requests.post(registrar_txn_url, data=json.dumps(payload), headers=headers)
    print('Property creation request sent to registrar: ' + property_addr)
Ejemplo n.º 8
0
 def make_random_output(cls, index, value, property_addr=None):
     wallet_addr = random.choice(list(DATABASE_WALLETS.keys()))
     if property_addr is None:
         property_addr = FAKE.address().replace('\n', ', ')
     script = make_random_string()
     return cls(wallet_addr, property_addr, value, index, script)
Ejemplo n.º 9
0
def signup(request):
    if request.method == 'POST': 
        form = SignupForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            fullname = form.cleaned_data['fullname']
            password = form.cleaned_data['password']
            url = str(form.cleaned_data['url']).lower()
            # creating the fresh user
            user = User(fullname=fullname, email=email, password=password, type=1)
            user.save()
            # creating activation record for the fresh user
            User_Activation(user=user).save()
            
            description =''
            res = get_http_response(url)
            # saving website's description
            if res:
                description=get_site_description(res)[0:510]
                if len(description) >= 507:
                    description=description[0:507]+'...'
                    
            name=extract_website_name(remove_landing_url(url))
            
            # insert the url to websites table in an unverified state 
            # associated to the fresh user -- custom validator made sure that no
            # record with same url is verified yet
            website = Website(url=url, name=name, description=description, type=1)
            website.save()
            
            # saving website's icon
            favicon_url = get_site_favicon_url(remove_landing_url(url)) or ''
            if favicon_url:
                favicon_content = http_read(favicon_url) or ''
                if favicon_content:
                    filename32 = make_random_string(32)+'.png'
                    filename48 = make_random_string(32)+'.png'
                    filename64 = make_random_string(32)+'.png'
                    favicon32 = ContentFile(normalize_img((32,32),favicon_content))
                    favicon48 = ContentFile(normalize_img((48,48),favicon_content))
                    favicon64 = ContentFile(normalize_img((64,64),favicon_content))
                    website.favicon32.save(filename32, favicon32)
                    website.favicon48.save(filename48, favicon48)
                    website.favicon64.save(filename64, favicon64)
            
            # first site screenshot insertion
            screenshot_name = make_random_string(32)+'.png'
            
            screenshot_image_content = site_screenshot(url)
            if screenshot_image_content:
                p = ImageFile.Parser()
                p.feed(screenshot_image_content)
                im=p.close()
                screenshot_image_content = ContentFile(normalize_img((im.size[0]/2,im.size[1]/2),screenshot_image_content))
                wi = Website_Image(name=name, website=website)
                wi.image.save(screenshot_name, screenshot_image_content)
            # the actual user-website association creation
            User_Website(user=user,website=website).save()
            response = HttpResponse('Signup successful, please activate via email')
            return response
    # request.method is GET
    else:
        form = SignupForm() # An unbound form
        
    return render_form('signup_form.html', form, '', request)
Ejemplo n.º 10
0
 def __encrypt_password(self, password):
     if not self.salt:
         self.salt = make_random_string(16)
     self.encrypted_password = hashlib.sha1(self.salt + password).hexdigest()
Ejemplo n.º 11
0
def transact_property(bc, host='registrar'):
    """Transacts property on demand"""
    headers = {'content-type': 'application/json'}
    registrar_input_url = 'http://{}:58335/jsonrpc'.format(host)
    registrar_txn_url = 'http://{}:58336/jsonrpc'.format(host)
    wallet_privkeys = [
        'cPZa7oEsR6GBuyrUH1s64meMZB31nxxPbhCVc4HZot55kgFGhWUg',
        'cQ8RV14JvX8X9sNg2VAp98tGT1kG4BaG1NBy75T3jNeX8YYGAWUf',
        'cQ6PpZDZQmffjo9X1PAriUCX7asMog8kM8t8tBf1WoqLwomkvkh9',
        'cV88fZveSBQjcGZkfnDbY8akcBPEM3L1CCLehb8D4Kc8dHNLmzTG'
    ]

    input_hash = input('Hash of input to spend?')
    candidate_input = bc.unspent_output_dict[input_hash][0]

    payload = candidate_input.to_dict()
    return_data = requests.post(registrar_input_url,
                                data=json.dumps(payload),
                                headers=headers).json()
    if return_data['Status'] != 'Unspent':
        print('Attempted to create propTx with invalid input')
        raise ValueError('Attempted to create propTx with invalid input')
    input_list = [candidate_input]

    # generate random number of outputs
    property_addr = candidate_input.property_addr
    input_value = candidate_input.value
    print('Input value to spend: ' + str(input_value))

    num_outputs = int(input('Number of new owners?'))

    output_list = list()
    total_value = 0
    for idx in range(num_outputs):
        wallet_addr = input('Wallet address of owner #' + str(idx + 1) + '?')
        value_i = int(input('Value to owner #' + str(idx + 1) + '?'))
        script = make_random_string()

        if value_i <= 0:
            print('Non-positive value invalid')
            raise ValueError('Non-positive value invalid')
        total_value += value_i

        output = Output(wallet_addr, property_addr, value_i, idx, script)
        output_list.append(output)

    if total_value != input_value:
        print('Total output value not equal intput value, try again')
        raise ValueError('Total output value not equal input value, try again')

    testnet = Bitcoin(testnet=True)
    print('Testnet privkey options:')
    for wallet_privkey in wallet_privkeys:
        print(wallet_privkey)
    payor_privkey = input('Payor privkey?')
    recip_privkey = input('Recipient privkey?')

    if payor_privkey not in wallet_privkeys or recip_privkey not in wallet_privkeys:
        print('testnet privkeys invalid')
        raise ValueError('testnet privkeys invalid')

    satoshis = int(input('How many satoshis to send?'))

    recip_address = testnet.privtoaddr(recip_privkey)

    tx_dump = testnet.send(payor_privkey, recip_address, satoshis, fee=400000)

    try:
        if tx_dump['status'] == 'success':
            tx_data = tx_dump['data']
            btc_txn_hash = tx_data['txid']
        else:
            print('Testnet transaction failed')
            raise ValueError('Testnet transaction failed')
    except TypeError:
        raise ValueError('TypeError')

    new_transaction = Transaction(input_list, output_list, 'propTx',
                                  btc_txn_hash)

    print('Submitted transaction to Testnet. Hash:')
    print(btc_txn_hash)
    print('Transaction hash (own chain):')
    print(new_transaction.transaction_hash)

    # send transaction to registrar
    payload = new_transaction.to_dict()
    requests.post(registrar_txn_url, data=json.dumps(payload), headers=headers)

    print('Property transaction request sent to registrar: ' + property_addr)
Ejemplo n.º 12
0
def normalize_img((width, height), data):
    import ImageFile
    import Image
    p = ImageFile.Parser()
    p.feed(data)
    im=p.close()
    # small images processing(framing etc..)
    if im.size[0]<=22 and im.size[1]<=22:
        # normalize the small image
        #im = im.resize((16,16), Image.ANTIALIAS)
        
        # create our temp file names (to be removed soon)
        tmp_filename=[]
        for i in range(0,5):
            tmp_filename.append(settings.TMP_IMAGES_FOLDER+make_random_string(length=32)+'.png')
        
        im.save(tmp_filename[0],'png')
        
        # using ImageMagick
        try:
            subprocess.call(['convert','-bordercolor', 'none', '-border', '10', '-mattecolor', 'none','-frame', '2x2',tmp_filename[0],tmp_filename[1]])
            subprocess.call(['convert',tmp_filename[1],'-border','3','-alpha', 'transparent','-background', 'none','-fill','white','-stroke','none','-strokewidth','0','-draw','@'+settings.IMAGES_LIB_FOLDER+'rounded_corner.mvg',tmp_filename[2]])
            subprocess.call(['convert',tmp_filename[1],'-border', '3', '-alpha','transparent','-background','none','-fill', 'none', '-stroke', '#CCC', '-strokewidth', '3', '-draw' ,'@'+settings.IMAGES_LIB_FOLDER+'rounded_corner.mvg', tmp_filename[3]])
            subprocess.call(['convert',tmp_filename[1],'-matte','-bordercolor', 'none', '-border', '3',tmp_filename[2],'-compose', 'DstIn', '-composite',tmp_filename[3],'-compose', 'Over','-composite', tmp_filename[4]])
        except (subprocess.CalledProcessError,OSError):
            return ''
        
        im = Image.open(tmp_filename[4])
        
        # removal of tmp files
Ejemplo n.º 13
0
 def make_random_output(cls, index, value, property_addr=None):
     wallet_addr = make_random_string()
     if property_addr is None:
         property_addr = FAKE.address()
     script = make_random_string()
     return cls(wallet_addr, property_addr, value, index, script)