Example #1
0
    def test_wallet_send(self):
        sender = generate_key()
        receiver = generate_key()

        data = {
            "public_key": str(sender.publickey()),
            "private_key": str(sender.privatekey()),
            "amount": 10,
            "recipient": str(receiver.publickey())
        }

        resp = wallet_send(json.dumps(data))
        data = json.loads(resp)
        self.assertEqual(data.get('successful', None), False)
Example #2
0
    def test_fraudulent_tx_source_other_user(self):
        blockchain = Blockchain()

        victim = generate_key()
        miner_key = generate_key()

        miner = Miner(blockchain)
        miner.reward_addr = miner_key.publickey()
        emptyblock = miner._mine()

        transfer = Wallet(miner_key, blockchain)
        transfer.send(10, victim.publickey())

        self.assertEqual(len(emptyblock.transactions), 1)
        self._test_fraudulent_tx(victim, blockchain)
Example #3
0
def create_wallet(data):
    key = generate_key()

    return json.dumps({
        "public_key": str(key.publickey()),
        "private_key": str(key.privatekey())
    })
Example #4
0
 def user(self, name, perms=[]):
     """
     Create user with name `name` and permissions `permissins`
     return authenticated session
     """
     if name not in self._users:
         pw = utils.generate_key()
         user = auth_db.Users()
         user.id = len(self._users) + 1
         user.name = name
         user.set_password(pw)
         user.firstnames = 'test'
         user.lastname = 'test'
         user.save()
         connection.session.commit()
         for perm_name in perms:
             perm = auth_db.Permissions.query().filter(
                 auth_db.Permissions.name == perm_name).one()
             user.permissions.append(perm)
         connection.session.commit()
         sessionkey = self.auth(user=name, password=pw)
         u = TestUser(name=name,
                      password=pw,
                      sessionkey=sessionkey,
                      user=user)
         self._users[name] = u
     return self._users[name]
Example #5
0
def hash_password(password, salt=None):
    if isinstance(password, str):
        password = password.encode("utf-8")
    if salt is None:
        salt = generate_key(size=20)
    return "$1$%s$%s" % (salt,
                         sha512(salt.encode("utf-8") + password).hexdigest())
Example #6
0
    def test_wallet_info(self):
        receiver = generate_key()

        data = {"public_key": str(receiver.publickey())}

        resp = wallet_info(json.dumps(data))
        data = json.loads(resp)
        self.assertIsNotNone(data.get('balance', None))
Example #7
0
    def test_fraudulent_tx_source_coinbase(self):
        blockchain = Blockchain()

        victim = generate_key()
        miner = Miner(blockchain)
        miner.reward_addr = victim.publickey()
        emptyblock = miner._mine()
        self.assertEqual(len(emptyblock.transactions), 1)
        self._test_fraudulent_tx(victim, blockchain)
Example #8
0
    def test_rsa(self):
        test_hash = "1234"

        key = generate_key()

        signature = sign(key, test_hash)

        self.assertTrue(verify_sig(key, signature, test_hash))
        self.assertFalse(verify_sig(key, signature, "4321"))
        self.assertFalse(verify_sig(key, signature, "12345"))
Example #9
0
    def _test_fraudulent_tx(self, victim, blockchain):
        """
        Try transaction from somebody else's "wallet"
        """

        miner_key = generate_key()
        perpetrator = generate_key()

        utxo = blockchain.scan_unspent_transactions(victim.publickey())

        perpetrator_owns = blockchain.scan_unspent_transactions(
            perpetrator.publickey())
        self.assertEqual(len(perpetrator_owns), 0)  # Sanity check

        # Let's handcraft tx that tries to steal victim's coins.
        tx = Transaction(perpetrator)  # Sign it with random key

        utxo = blockchain.scan_unspent_transactions(
            victim.publickey())  # Get victim's utxo

        debit = sum(map(lambda x: x['value'], utxo))

        for credit in utxo:
            tx.add_in(credit['hash'], sign(perpetrator, credit['hash']),
                      victim.publickey(), credit['value'])

        tx.add_out(debit, perpetrator.publickey())

        try:
            blockchain.add(tx)
            self.fail("Should've thrown UnauthorizedTxException")
        except UnauthorizedTxException:
            pass

        miner = Miner(blockchain)
        miner.reward_addr = miner_key.publickey()
        _ = miner._mine()

        perpetrator_owns = blockchain.scan_unspent_transactions(
            perpetrator.publickey())

        # Should own nothing. This tx should've failed.
        self.assertEqual(len(perpetrator_owns), 0)
Example #10
0
 def authenticate(self, username, password):
     """
     Authenticate user using username and password
     returns api key if credentials are correct
     """
     user = self.get_by_username(username)
     if user:
         if user.check_password(password) is True:
             apikey = generate_key()
             db.AuthKeys.add_key(user=user, key=apikey)
             return apikey
     raise AuthenticationFailed("Invalid username or password")
Example #11
0
 def authenticate(self, username, password):
     """
     Authenticate user using username and password
     returns api key if credentials are correct
     """
     user = self.get_by_username(username)
     if user:
         if user.check_password(password) is True:
             apikey = generate_key()
             db.AuthKeys.add_key(user=user, key=apikey)
             return apikey
     raise AuthenticationFailed("Invalid username or password")
Example #12
0
    def test_format(self):
        key = generate_key()
        keystr = str(key.publickey())
        newkey = RSAPublicKey.load(keystr)

        self.assertEqual(key.public_key.n, newkey.n)
        self.assertEqual(key.public_key.e, newkey.e)

        keystr = str(key.privatekey())
        newkey = RSAPrivateKey.load(keystr)

        self.assertEqual(key.priv_key.n, newkey.n)
        self.assertEqual(key.priv_key.d, newkey.d)
Example #13
0
    def test_chained_tx(self):
        blockchain = Blockchain()

        member1 = generate_key()
        member2 = generate_key()
        member3 = generate_key()

        miner = Miner(blockchain)
        miner.reward_addr = member1.publickey()
        _ = miner._mine()

        wallet1 = Wallet(member1, blockchain)
        wallet1.send(10, member2.publickey())

        wallet2 = Wallet(member2, blockchain)
        wallet2.send(10, member3.publickey())

        wallet3 = Wallet(member3, blockchain)

        self.assertEqual(wallet1.balance(), 0)
        self.assertEqual(wallet2.balance(), 0)
        self.assertEqual(wallet3.balance(), 10)
Example #14
0
    def test_pending_transactions(self):
        receiver = generate_key()

        tx = Transaction(None, txtype=TxType.COINBASE)
        tx.add_out(10, receiver.publickey())

        blockchain = Blockchain()
        blockchain.add(tx)

        pending_tx = blockchain.get_pending_transactions()

        self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 1)

        miner = Miner(blockchain)
        miner.reward_addr = receiver.publickey()
        newb = miner._mine()

        pending_tx = blockchain.get_pending_transactions()

        self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 0)
        self.assertEqual(len(filter(lambda x: tx.hash, newb.transactions)), 2)
Example #15
0
 def user(self, name, perms=[]):
     """
     Create user with name `name` and permissions `permissins`
     return authenticated session
     """
     if name not in self._users:
         pw = utils.generate_key()
         user = auth_db.Users()
         user.id = len(self._users) + 1
         user.name = name
         user.set_password(pw)
         user.firstnames = 'test'
         user.lastname = 'test'
         user.save()
         connection.session.commit()
         for perm_name in perms:
             perm = auth_db.Permissions.query().filter(
                         auth_db.Permissions.name==perm_name).one()
             user.permissions.append(perm)
         connection.session.commit()
         sessionkey = self.auth(user=name, password=pw)
         u = TestUser(name=name, password=pw, sessionkey=sessionkey, user=user)
         self._users[name] = u
     return self._users[name]
Example #16
0
    def main():
        """
        Main GUI function
        """

        new_user_section = [
            [
                sg.Text('Username'),
                sg.Input(key='_USERNAME_',
                         tooltip='What is your myASNB account username?')
            ],
            [
                sg.Text('Password'),
                sg.Input(key='_PASSWORD_',
                         password_char="*",
                         tooltip='What is your myASNB account password?')
            ],
            [
                sg.Text('Investment Amount (RM)'),
                sg.Input(key='_INVESTMENT_AMOUNT_',
                         tooltip='How much do you want to invest?',
                         change_submits=True,
                         do_not_clear=True)
            ],
        ]

        layout = [
            [
                sg.Text('myASNB Unit Holder Login',
                        font='Helvetica 20',
                        justification='center')
            ],
            [
                sg.Checkbox('Login as new user',
                            enable_events=True,
                            key='_CHECKBOX_KEY_',
                            tooltip='Tick to login.')
            ],
            [collapse(new_user_section, '_SECTION_KEY_', False)],
            [
                sg.OK('Start',
                      tooltip='Start the bot (Press: ENTER)',
                      size=(10, 1),
                      bind_return_key=True,
                      focus=True),
                sg.Cancel('Quit', tooltip='Goodbye.', size=(5, 1))
            ],
        ]

        window = sg.Window(
            'Six Percent',
            layout,
            auto_size_text=False,
            default_element_size=(25, 1),
            text_justification='l',
            return_keyboard_events=True,
            grab_anywhere=False,
        )

        user_credentials_template = dict(username='',
                                         password='',
                                         investment_amount='')
        user_credentials = user_credentials_template.copy()
        section_toggle = False

        while True:
            event, values = window.read()

            if event == '_CHECKBOX_KEY_':
                section_toggle = not section_toggle
                window['_SECTION_KEY_'].update(visible=section_toggle)

            elif event == '_INVESTMENT_AMOUNT_':
                window.FindElement(event).Update(
                    re.sub("[^0-9]", "", values[event]))
            # end if

            user_credentials = {
                **user_credentials,
                'username': values['_USERNAME_'],
                'password': values['_PASSWORD_'],
                'investment_amount': values['_INVESTMENT_AMOUNT_'],
            }

            if event in (sg.WIN_CLOSED, 'Quit'):
                logging.info('👋 Exiting program gracefully')
                window.close()
                sys.exit()

            elif event == 'Start':
                break
            # end if
        # end while

        window.close()

        if not os.path.isfile('secret.key'):
            generate_key()
        # end if

        # Encrypts user password before storing it
        if user_credentials['password']:
            user_credentials['password'] = encrypt_password(
                user_credentials['password'])
        # end if

        return dict(
        ) if user_credentials == user_credentials_template else user_credentials
Example #17
0
File: db.py Project: annttu/Renki
def hash_password(password, salt=None):
    if isinstance(password, str):
        password = password.encode("utf-8")
    if salt is None:
        salt = generate_key(size=20)
    return "$1$%s$%s" % (salt, sha512(salt.encode("utf-8") + password).hexdigest())
Example #18
0
    def test_value_transfer(self):
        """
        Test successful transaction
        """
        SENDER_ORIG_VALUE = MINING_REWARD  # Mining reward
        SEND_AMOUNT = 5

        blockchain = Blockchain()

        sender = generate_key()
        receiver = generate_key()
        miner_key = generate_key()

        # This is an empty blockchain so create value out of thin air.
        miner = Miner(blockchain)
        miner.reward_addr = sender.publickey()
        emptyblock = miner._mine()

        self.assertEqual(len(emptyblock.transactions), 1)

        # First test with unconfirmed transactions
        for i in range(1, 3):
            wallet = Wallet(sender, blockchain)
            wallet.send(SEND_AMOUNT, receiver.publickey())

            # Scan the blockchain for the transaction that just happened.
            receiver_owns = blockchain.scan_unspent_transactions(
                receiver.publickey())
            value_received = sum(
                map(lambda x: x.get('value', 0), receiver_owns))
            self.assertEqual(value_received, SEND_AMOUNT * i)

            sender_owns = blockchain.scan_unspent_transactions(
                sender.publickey())
            value_owned_by_sender = sum(
                map(lambda x: x.get('value', 0), sender_owns))
            self.assertEqual(value_owned_by_sender,
                             SENDER_ORIG_VALUE - SEND_AMOUNT * i)

        # Mine the transactions
        miner = Miner(blockchain)
        miner.reward_addr = miner_key.publickey()
        newb = miner._mine()

        # Test with confirmed transactions
        receiver_owns = blockchain.scan_unspent_transactions(
            receiver.publickey())
        value_received = sum(map(lambda x: x.get('value', 0), receiver_owns))
        self.assertEqual(value_received, SEND_AMOUNT * 2)

        sender_owns = blockchain.scan_unspent_transactions(sender.publickey())
        value_owned_by_sender = sum(
            map(lambda x: x.get('value', 0), sender_owns))
        self.assertEqual(value_owned_by_sender,
                         SENDER_ORIG_VALUE - SEND_AMOUNT * 2)

        # Check whether miner received the award
        miner_owns = blockchain.scan_unspent_transactions(
            miner_key.publickey())
        value_owned_by_miner = sum(map(lambda x: x.get('value', 0),
                                       miner_owns))
        self.assertEqual(value_owned_by_miner, MINING_REWARD)

        self.assertEqual(len(newb.transactions), 3)