Exemplo n.º 1
0
 def setUp(self):
     self.new_user = User('Vikki', 'Ireri', '*****@*****.**',
                          'akisijui', [])
     self.new_account = Account('Instagram', 'https://www.instagram.com/',
                                '*****@*****.**', '12345')
     self.new_account1 = Account('Facebook', 'https://www.facebook.com/',
                                 '*****@*****.**', '67890')
Exemplo n.º 2
0
 def test_find_accounts_by_name(self):
     """
     test to check if accounts by the  account name and can display information
     """
     self.new_accounts.save_accounts()
     test_accounts = Account("facebook", "1234")
     test_accounts.save_accounts()
Exemplo n.º 3
0
    def createNewAccount(self, name):
        if name != '' and name in self.name_to_account:
            debugging.error("There is already an account named %s. Please use a different name.", name)
        account = Account(name)
        account.generateKeys()
        self.__addAccount(account)

        return account
Exemplo n.º 4
0
def addDefaultAccounts():
    if accountsTable.count() > 0:
        return

    checking = Account(name='Checking', currentAmount=123)
    savings = Account(name='Savings', currentAmount=123)

    accountsTable.addNew(checking)
    accountsTable.addNew(savings)
Exemplo n.º 5
0
 def __init__(self):
     
     self.chart_of_accounts = [  # Default Chart
         Account(acc_num=int(1000), acc_name="Cash", acc_type="Asset"),
         Account(acc_num=int(2000), acc_name="Accounts Payable", acc_type="Liability"),
         Account(acc_num=int(3000), acc_name="Retained Earnings", acc_type="Equity"),
         Account(acc_num=int(4000), acc_name="Sales Revenue", acc_type="Income"),
         Account(acc_num=int(5000), acc_name="Cost of Goods Sold", acc_type="Expense"),
     ]
Exemplo n.º 6
0
 def test_delete_accounts(self):
     """
     testcase to delete account
     """
     self.new_accounts.save_accounts()
     test_accounts = Account("facebook", "1234")
     test_accounts.save_accounts()
     self.new_accounts.delete_accounts()  #to delete an account object
     self.assertEqual(len(Account.account_list), 1)
Exemplo n.º 7
0
    def option_six(self):
        self.chart_of_accounts = [  # Default Chart
            Account(acc_num=int(1000), acc_name="Cash", acc_type="Asset"),
            Account(acc_num=int(2000), acc_name="Accounts Payable", acc_type="Liability"),
            Account(acc_num=int(3000), acc_name="Retained Earnings", acc_type="Equity"),
            Account(acc_num=int(4000), acc_name="Sales Revenue", acc_type="Income"),
            Account(acc_num=int(5000), acc_name="Cost of Goods Sold", acc_type="Expense"),
        ]

        print("Default Chart of accounts has been restored.")
Exemplo n.º 8
0
 def loadFromFile(self, file):
     with open(file, 'rb') as f:
         while True:
             raw_size = f.read(4)
             if len(raw_size) < 4: break
             size = struct.unpack('I', raw_size)[0]
             buffer = f.read(size)
             account = Account('')
             account.fromBytes(buffer)
             self.__addAccount(account)
Exemplo n.º 9
0
    def test_signature(self):
        message = b'Suck my dick.'
        account = Account('Felatio')
        account.generateKeys()
        signature = account.sign(message)
        logging.debug('signature: %s',signature.hex())

        sig_valid = accounts.isValid(
            account.getPublicKey(),
            message,
            signature
        )
        self.assertTrue(sig_valid, "Signature not valid!")
Exemplo n.º 10
0
def new_account(ctx, uuid):
    """Create a new account.

    This will generate a random private key and store it in encrypted form in the keystore
    directory. You are prompted for the password that is employed (if no password file is
    specified). If desired the private key can be associated with a random UUID (version 4) using
    the --uuid flag.
    """
    app = ctx.obj['app']
    if uuid:
        id_ = str(uuid4())
    else:
        id_ = None
    password = ctx.obj['password']
    if password is None:
        password = click.prompt('Password to encrypt private key', default='', hide_input=True,
                                confirmation_prompt=True, show_default=False)
    account = Account.new(password, uuid=id_)
    account.path = os.path.join(os.path.abspath(ctx.obj['config']['data_dir']),
                                ctx.obj['config']['accounts']['keystore_dir'],
                                account.address.encode('hex'))
    try:
        app.services.accounts.add_account(account)
    except IOError:
        click.echo('Could not write keystore file. Make sure you have write permission in the '
                   'configured directory and check the log for further information.')
        sys.exit(1)
    else:
        click.echo('Account creation successful')
        click.echo('  Address: ' + account.address.encode('hex'))
        click.echo('       Id: ' + str(account.uuid))
Exemplo n.º 11
0
 def generate_accounts(self) -> None:
     short_names: Set[str] = set()
     long_names: Set[str] = set()
     limitsets: Set[LimitSet] = set()
     allhosts: Set[str] = set()
     routers: Set[str] = set()
     letters = string.ascii_lowercase
     while len(short_names) < 8:
         short_names.add(''.join(random.choice(letters) for _ in range(2)))
     while len(long_names) < 8:
         long_names.add(''.join(random.choice(letters) for _ in range(random.randint(5, 9))))
     while len(routers) < 3:
         routers.add(''.join(random.choice(letters) for _ in range(random.randint(5, 9))))
     while len(limitsets) < 3:
         limitsets.add(self.generate_limitset())
     accounts = []
     for sn, name in zip(short_names, long_names):
         generated_hosts: Set[str] = set()
         while len(generated_hosts) < random.randint(2, 7):
             new_host = ''.join(random.choice(letters) for _ in range(random.randint(3, 8)))
             if new_host in allhosts: continue
             generated_hosts.add(new_host)
             allhosts.add(new_host)
         hosts: Tuple[Host, ...] = tuple(Host(x) for x in generated_hosts)
         mark = random.choice(list(Mark))
         limit = random.choice(list(limitsets))
         acc = Account(sn, name, hosts, limit, mark)
         accounts.append(acc)
     self.accounts = {o.short: o for o in accounts}
     self.hosts = tuple(allhosts)
     self.limits = tuple(limitsets)
     self.routers = tuple(routers)
     self.config['test_host'] = random.choice(self.hosts)
     self.config['test_router'] = random.choice(self.routers)
Exemplo n.º 12
0
def new_account(ctx, uuid):
    """Create a new account.

    This will generate a random private key and store it in encrypted form in the keystore
    directory. You are prompted for the password that is employed (if no password file is
    specified). If desired the private key can be associated with a random UUID (version 4) using
    the --uuid flag.
    """
    app = ctx.obj['app']
    if uuid:
        id_ = str(uuid4())
    else:
        id_ = None
    password = ctx.obj['password']
    if password is None:
        password = click.prompt('Password to encrypt private key',
                                default='',
                                hide_input=True,
                                confirmation_prompt=True,
                                show_default=False)
    account = Account.new(password, uuid=id_)
    account.path = os.path.join(app.services.accounts.keystore_dir,
                                account.address.encode('hex'))
    try:
        app.services.accounts.add_account(account)
    except IOError:
        click.echo(
            'Could not write keystore file. Make sure you have write permission in the '
            'configured directory and check the log for further information.')
        sys.exit(1)
    else:
        click.echo('Account creation successful')
        click.echo('  Address: ' + account.address.encode('hex'))
        click.echo('       Id: ' + str(account.uuid))
Exemplo n.º 13
0
    def _quit(self):
        print("\nThank you for playing Blackjack!\n")

        if self.quit_without_save is False:
            Account().save(self.player)

        exit()
def createEvent():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        if user.user_type == 'organiser':
            return render_template('create.html', user=user)
        else:
            return redirect(url_for('home', events=None))
def requestRefund():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        event_id = request.form['id']
        purchase_date = request.form['purchase_date']
        user.requestRefund(event_id, purchase_date)
        return redirect(url_for('viewTransactions'))
Exemplo n.º 16
0
def welcomereply():
    resp = twilio.twiml.Response()

    logging.basicConfig( level=logging.INFO)
    connInfo = {
            "dbname": os.getenv('DBNAME', "echoalert"),
            "user": os.getenv('DBUSER', "postgres"),
            "host": os.getenv('DBHOST', "localhost"),
            "port": os.getenv('DBPORT', "5432"),
            "password": os.getenv('DBPASS', "defaultpassword"),
            }

    logging.info("initialized")
    PgDb.setup( **connInfo)

    fr = request.form.get("From")
    sid = request.form.get("SmsMessageSid")
    accountsid = request.form.get("AccountSid")
    smssid = request.form.get("SmsSid")
    body = request.form.get("Body")

    if len(fr) > 0:
        account = Account.get_account_by_phone(fr)
        logging.info("found {} accounts".format(len(account)))

    logging.info("From: {}, Body: {}".format(fr,body))

    resp.message("I got your message, but i'm not programmed to know how to handle it.")
    logging.info(request.form)
    return str(resp)
Exemplo n.º 17
0
def run(ctx, node_id, console, fake_account):
    """Start the daemon"""
    config = ctx.obj['config']
    config['node']['privkey_hex'] = privkeys[node_id]
    config['discovery']['listen_port'] += node_id
    config['p2p']['listen_port'] += node_id
    log.info("starting", config=config)

    if config['node']['data_dir'] and not os.path.exists(
            config['node']['data_dir']):
        os.makedirs(config['node']['data_dir'])

    app = Casper(config)
    app.start_console = console

    for service in services:
        assert issubclass(service, BaseService)
        assert service.name not in app.services
        service.register_with_app(app)
        assert hasattr(app.services, service.name)
        # If this service is the account service, then attempt to unlock the coinbase
        if service is AccountsService:
            # If the fake_account flag is True, create a temparary fake account based on node_id
            if fake_account:
                account = Account.new('', decode_hex(privkeys[node_id]))
                app.services.accounts.add_account(account, store=False)
                continue
            unlock_accounts(ctx.obj['unlock'],
                            app.services.accounts,
                            password=ctx.obj['password'])
            try:
                app.services.accounts.coinbase
            except ValueError as e:
                log.fatal('invalid coinbase',
                          coinbase=config.get('pow', {}).get('coinbase_hex'),
                          error=e.message)
                sys.exit()

    # start app
    log.info('starting')
    app.start()

    if ctx.obj['log_file']:
        log.info("Logging to file %s", ctx.obj['log_file'])
        # User requested file logging - remove stderr handler
        root_logger = slogging.getLogger()
        for hdl in root_logger.handlers:
            if isinstance(hdl, StreamHandler) and hdl.stream == sys.stderr:
                root_logger.removeHandler(hdl)
                break

    # wait for interrupt
    evt = Event()
    gevent.signal(signal.SIGQUIT, evt.set)
    gevent.signal(signal.SIGTERM, evt.set)
    evt.wait()

    # finally stop
    app.stop()
Exemplo n.º 18
0
class TestAccounts(unittest.TestCase):
    '''
    Test class that defines test cases for the accounts class behaviours.

    Args:
        unittest.TestCase: TestCase class that helps in creating test cases
    '''
    def setUp(self):
        '''
        Set up method to run before each test cases.
        '''
        self.new_accounts = Account("facebook", "1234")

    def tearDown(self):
        '''
            tearDown method that does clean up after each test case has run.
            '''
        Account.accounts_list = []

    def test_accounts_instance(self):
        """
        method to test if the new accounts have been instanciated properly
        """
        self.assertEqual(self.new_accounts.account_name, "facebook")
        self.assertEqual(self.new_accounts.account_password, "1234")

    def test_save_accounts(self):
        """
        testcase to test if account objects have been saved
        """
        self.new_accounts.save_accounts()  # saving the new account
        self.assertEqual(len(Account.accounts_list), 1)

    def test_delete_accounts(self):
        """
        testcase to delete account
        """
        self.new_accounts.save_accounts()
        test_accounts = Account("facebook", "1234")
        test_accounts.save_accounts()
        self.new_accounts.delete_accounts()  #to delete an account object
        self.assertEqual(len(Account.account_list), 1)

    def test_find_accounts_by_name(self):
        """
        test to check if accounts by the  account name and can display information
        """
        self.new_accounts.save_accounts()
        test_accounts = Account("facebook", "1234")
        test_accounts.save_accounts()

    def test_display_all_accounts(self):
        """
        test to check if all contacts can be veiwed
        """
        self.assertEqual(Account.display_accounts(), Account.account_list)
def approveRefund():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        event_id = request.form['id']
        purchase_date = request.form['purchase_date']
        email = request.form['email']
        user.approveRefund(email, event_id, purchase_date)
        return redirect(url_for('refunds'))
Exemplo n.º 20
0
    def test_not_equal(self):
        a1 = Account('a1')
        a1.generateKeys()
        a2 = Account('a1')
        a2.generateKeys()

        self.assertFalse(a1.equals(a2),"Accounts should be different!")
def editEvent():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        event_id = request.args.get('id')
        event = EventsCollection.getSingleEvent(event_id)
        if user.user_type == 'organiser':
            return render_template('edit.html', user=user, event=event)
        else:
            return redirect(url_for('home', events=None))
Exemplo n.º 22
0
def run(ctx, node_id, console, fake_account):
    """Start the daemon"""
    config = ctx.obj['config']
    config['node']['privkey_hex'] = privkeys[node_id]
    config['discovery']['listen_port'] += node_id
    config['p2p']['listen_port'] += node_id
    log.info("starting", config=config)

    if config['node']['data_dir'] and not os.path.exists(config['node']['data_dir']):
        os.makedirs(config['node']['data_dir'])

    app = Casper(config)
    app.start_console = console

    for service in services:
        assert issubclass(service, BaseService)
        assert service.name not in app.services
        service.register_with_app(app)
        assert hasattr(app.services, service.name)
        # If this service is the account service, then attempt to unlock the coinbase
        if service is AccountsService:
            # If the fake_account flag is True, create a temparary fake account based on node_id
            if fake_account:
                account = Account.new('', decode_hex(privkeys[node_id]))
                app.services.accounts.add_account(account, store=False)
                continue
            unlock_accounts(ctx.obj['unlock'], app.services.accounts, password=ctx.obj['password'])
            try:
                app.services.accounts.coinbase
            except ValueError as e:
                log.fatal('invalid coinbase', coinbase=config.get('pow', {}).get('coinbase_hex'),
                          error=e.message)
                sys.exit()

    # start app
    log.info('starting')
    app.start()

    if ctx.obj['log_file']:
        log.info("Logging to file %s", ctx.obj['log_file'])
        # User requested file logging - remove stderr handler
        root_logger = slogging.getLogger()
        for hdl in root_logger.handlers:
            if isinstance(hdl, StreamHandler) and hdl.stream == sys.stderr:
                root_logger.removeHandler(hdl)
                break

    # wait for interrupt
    evt = Event()
    gevent.signal(signal.SIGQUIT, evt.set)
    gevent.signal(signal.SIGTERM, evt.set)
    evt.wait()

    # finally stop
    app.stop()
def buyTicket():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        event_id = request.form['id']
        num_tix = request.form['num_tix']

        event = EventsCollection.getSingleEvent(event_id)
        user.purchaseTickets(event, num_tix)
        event.updateTicketAmount(num_tix)

        url = "/event?id="+str(event.ID)
        return redirect(url, code=302)
Exemplo n.º 24
0
def main(stdscr):
    ''' Main function of the program '''
    output = ''
    file_path = fileopenbox('Open account data csv')
    if file_path is None:
        terminate()
        return

    account_list = AccountList()
    with open(file_path, newline='') as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024),
                                      delimiters=CSV_DELIMITERS)
        csvfile.seek(0)
        reader = csv.DictReader(csvfile, dialect=dialect)
        for row in reader:
            account_list.append(Account(row['username'], row['password']))

    connection = Connection()
    while True:
        current = account_list.current()
        if current is None:
            terminate()
            return
        start_time = time.time()
        stdscr.clear()
        status = []
        macro = None
        try:
            status = get_status(connection, current)
            try:
                macro = get_macro(status)
                output = do_macro(connection, macro, current)
            except CompletedAccount:
                account_list.complete()
                output = {'description': 'Completed'}
        except RequestException as err:
            output = {'error': 'RequestException: {0}'.format(err)}
        except BadResponseException:
            output = {'error': 'BadResponseException'}
        except LootRetrieveException:
            output = {'error': 'LootRetrieveException'}

        process_time = time.time() - start_time
        stdscr.addstr('{:<30}{:.5f}s\n'.format('Process time', process_time))
        display_status(stdscr, status)
        stdscr.addstr('\n{:<30}{}\n'.format('Username', current.username))
        stdscr.addstr('{:<30}{}\n'.format('Password', current.password))
        stdscr.addstr('{:<30}{}\n'.format('Macro', macro))
        stdscr.addstr('{:<30}{}\n'.format('Ouptut', output))
        stdscr.addstr('\nctrl+shift+q to exit')
        stdscr.refresh()
        time.sleep(ACTION_INTERVAL)
Exemplo n.º 25
0
    def load_accounts(self, accounts_filepath):
        self._accounts_filepath = accounts_filepath

        try:
            with open(accounts_filepath, "r") as stream:
                data = json.load(stream)
        except FileNotFoundError:
            return

        account_list = []
        for account in data:
            account_list.append(Account(account_dict=account))
        self._handler.bind_accounts(account_list)
def editEventAction():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        event_id = request.form['event_id']
        name = request.form['name']
        date = request.form['date']
        location = request.form['location']
        capacity = request.form['capacity'] 
        price = request.form['price']

        event = EventsCollection.getSingleEvent(event_id)
        user.editEvent(event, name, location, date, capacity, price)
        return redirect(url_for('home', events=None))
def loginAction():
    email = request.form['email']
    password = request.form['password']
    user_type = request.form['user_type']

    user = Account.login(email, password, user_type)

    if user:
        session['user'] = user.__dict__
        return redirect(url_for('home', events=None))
    else:
        error = 'Invalid email address or password'
        return render_template('login.html', user_type=user_type, error=error)
Exemplo n.º 28
0
class AccountsTest(unittest.TestCase):
    def setUp(self):
        self.new_account = Account('Instagram', 'https://www.instagram.com/',
                                   '*****@*****.**', '12345')

    def test_init(self):
        self.assertEqual(self.new_account.account_name, 'Instagram')
        self.assertEqual(self.new_account.account_url,
                         'https://www.instagram.com/')
        self.assertEqual(self.new_account.email, '*****@*****.**')
        self.assertEqual(self.new_account.password, '12345')

    def test_save_account(self):
        account = self.new_account.save_account()
        self.assertEqual(account['name'], 'Instagram')
        self.assertEqual(account['link_url'], 'https://www.instagram.com/')
        self.assertEqual(account['email'], '*****@*****.**')
        self.assertEqual(account['password'], '12345')

    def test_copy_email(self):
        acc = self.new_account.save_account()
        email = self.new_account.copy_email(acc, 'email')
        print(pyperclip.paste(email))
def createEventAction():
    if 'user' in session:
        user = Account.fromDict(session['user'])
        name = request.form['name']
        date = request.form['date']
        location = request.form['location']
        event_type = request.form['event_type']
        capacity = request.form['capacity'] 
        description = request.form['description']
        price = request.form['price']
        tickets_remaining = request.form['tickets_remaining']

        event = Event(None, name, location, event_type, date, capacity, description, price, tickets_remaining, user.email, None)
        user.createEvent(event)
        return redirect(url_for('home', events=None))
Exemplo n.º 30
0
def authorize():
    """
    Check if this is an authorized request. Store the result in the global object. This
    also stores the account if it is an authorized request.
    """
    from accounts import Account
    if 'X-PITA-ACCOUNT-ID' not in request.headers or 'X-PITA-SECRET' not in request.headers:
        g.authorized = False
        g.account = None
    else:
        g.account = Account.get(request.headers['X-PITA-ACCOUNT-ID'],
                                request.headers['X-PITA-SECRET'])
        g.authorized = g.account != None
    if g.authorized:
        g.account.update_last_seen()
Exemplo n.º 31
0
    def option_two(self):
        
        while True:
            while True:
                account_num = 0
                try:
                    account_num = int(input("Account Number"))
                except ValueError:
                    print("Account # cannot contain letters")
                    break
                num_in_use = 0
                for account in self.chart_of_accounts:
                    if account.acc_num == account_num:
                        print("Account # already in use. Try again")
                        num_in_use = 1
                if num_in_use == 0:
                    break
            if account_num == 0:
                break
            account_name = input("Account Name")
            account_type = input("Account Type")
            i = 0
            num_of_accounts = len(self.chart_of_accounts)

            while num_of_accounts > i:
                if account_num < self.chart_of_accounts[i].acc_num:
                    self.chart_of_accounts.insert(i, (
                        Account(acc_num=int(account_num), acc_name=account_name, acc_type=account_type)))
                    break
                i += 1
            else:
                self.chart_of_accounts.append(
                    Account(acc_num=int(account_num), acc_name=account_name, acc_type=account_type))
            add_more = input("Type \"Y\" to enter another account, otherwise click anything else")
            if add_more.upper() != "Y":
                break
Exemplo n.º 32
0
def load_all_projects(wf):
    log.debug('start updating the cache')
    wf = Workflow3()

    all_accounts = None
    try:
        all_accounts = Accounts(get_accounts(wf))
    except PasswordNotFound:  # API key has not yet been set
        notify("WARNING", "No API key saved")

        log.error('No API key saved')

    log.debug('loading accounts...')

    if not all_accounts:
        # just paste gitlab url to the variables page and token to the keychain and start using the workflow
        url = get_wf_variable(wf, "gitlab_url")
        token = get_wf_variable(wf, "gitlab_token")
        all_accounts = Account({
            "simple_account": {
                "url": url,
                "token": token,
                "project_membership": "true",
                "project_visibility": "internal",
            }
        })

    log.info('Removing cache: {}'.format(DATA_FILE))
    # if os.path.exists(DATA_FILE):
    #     return
    try:
        os.remove(DATA_FILE)
    except:
        pass

    result = []
    for acc_name, acc_settings in all_accounts.dict.items():
        log.info('base api url is: {url}; api token is: {token_name}'.format(
            url=acc_settings.url, token_name=acc_settings.token))
        result.extend(get_all_pages(wf, account=acc_settings))

    with open(DATA_FILE, 'w+') as fp:
        json.dump(result, fp)

    notify(
        "Cache was updated",
        "Was loaded {projects} projects from all gitlab instances".format(
            projects=len(result)))
Exemplo n.º 33
0
    def load_data(self):
        """Read data from json file."""
        data = {}
        with open(AccountManager.filename, "r") as f:
            try:
                data = json.load(f)
            except json.JSONDecodeError:
                print("Empty file")

        if data:
            for account in data["Accounts"]:
                if account["type"] == "Account":
                    account_from_json = Account(account["balance"])
                else:
                    account_from_json = SavingsAccount(account["balance"])
                self.add_account(account_from_json)
def signupAction():
    email = request.form['email']
    name = request.form['name']
    password = request.form['password']
    verify_password = request.form['verify_password']
    user_type = request.form['user_type']

    if(password != verify_password):
        error = 'Passwords do not match'
        return render_template('signup.html', user_type=user_type, error=error)
    else:
        user = Account.register(name, email, password, user_type)
        if user:
            session['user'] = user.__dict__
            return redirect(url_for('home', events=None))
        else:
            error = 'Account with that email already exists'
            return render_template('signup.html', user_type=user_type, error=error)
Exemplo n.º 35
0
    def __init__(self):
        self.BJ = Blackjack(None)
        self.player = Player(None, None, None)
        self.quit_without_save = False

        self.login_options = {
            1: self._registration,
            2: self._sign_in,
            3: self._quit
        }
        self.game_options = {
            1: self._play,
            2: self._deposit,
            3: self._info,
            4: self._sign_out,
            5: self._delete_account,
            6: self._quit
        }
def home(events=None):
    if 'user' in session:
        user = Account.fromDict(session['user'])
        user_type = user.user_type
        events = []

        if request.method == 'GET':
            events = user.searchEvents('*', '*', '*', '*')
        elif request.method == 'POST':
            location = request.form['location'] if request.form['location'] != '' else '*'
            name = request.form['name'] if request.form['name'] != '' else '*'
            date = request.form['date'] if request.form['date'] != '' else '*'
            event_type = request.form['event_type'] if request.form['event_type'] != '' else '*'
            events = user.searchEvents(location, name, date, event_type)

        return render_template('home.html', events=events, user=user)
    else:
        return redirect("/", code=302)
Exemplo n.º 37
0
    def test_newAccount(self, mock_object1, mockobject2):
        # Create a new accounts
        name = 'test new account'
        account = Account(name)

        # Generate the keys
        account.generateKeys()

        private_key = account.getPrivateKey()
        public_key = account.getPublicKey()
        address = account.getAddress()
        b58address = account.getB58Address()
        set_name = account.getName()

        logging.debug('new %s', account)

        self.assertEqual(private_key.hex(), '1bf1cd4065d7ad80f01b271dcf3121112e97e2553b25a5dad5bfd5cc540f654c', "Incorrect private key!")
        self.assertEqual(public_key.hex(), '1bf1cd4065d7ad80f01b271dcf3121112e97e2553b25a5dad5bfd5cc540f654c', "Incorrect public key!")
        self.assertEqual(address.hex(),'2447daf348074b76b36fbc9ec15f154f5d487a37', "Incorrect address!")
        self.assertEqual(b58address, '14JqQVsxQDSewkkQrJuvCbhZuSHWC2CunJ', "Incorrect b58 address!")
        self.assertEqual(name, set_name, "Incorrect name!")
Exemplo n.º 38
0
def import_account(ctx, f, uuid):
    """Import a private key from FILE.

    FILE is the path to the file in which the private key is stored. The key is assumed to be hex
    encoded, surrounding whitespace is stripped. A new account is created for the private key, as
    if it was created with "pyethapp account new", and stored in the keystore directory. You will
    be prompted for a password to encrypt the key (if no password file is specified). If desired a
    random UUID (version 4) can be generated using the --uuid flag in order to identify the new
    account later.
    """
    app = ctx.obj['app']
    if uuid:
        id_ = str(uuid4())
    else:
        id_ = None
    privkey_hex = f.read()
    try:
        privkey = privkey_hex.strip().decode('hex')
    except TypeError:
        click.echo(
            'Could not decode private key from file (should be hex encoded)')
        sys.exit(1)
    password = ctx.obj['password']
    if password is None:
        password = click.prompt('Password to encrypt private key',
                                default='',
                                hide_input=True,
                                confirmation_prompt=True,
                                show_default=False)
    account = Account.new(password, privkey, uuid=id_)
    account.path = os.path.join(app.services.accounts.keystore_dir,
                                account.address.encode('hex'))
    try:
        app.services.accounts.add_account(account)
    except IOError:
        click.echo(
            'Could not write keystore file. Make sure you have write permission in the '
            'configured directory and check the log for further information.')
        sys.exit(1)
    else:
        click.echo('Account creation successful')
        click.echo('  Address: ' + account.address.encode('hex'))
        click.echo('       Id: ' + str(account.uuid))
Exemplo n.º 39
0
def import_account(ctx, f, uuid):
    """Import a private key from FILE.

    FILE is the path to the file in which the private key is stored. The key is assumed to be hex
    encoded, surrounding whitespace is stripped. A new account is created for the private key, as
    if it was created with "pyethapp account new", and stored in the keystore directory. You will
    be prompted for a password to encrypt the key (if no password file is specified). If desired a
    random UUID (version 4) can be generated using the --uuid flag in order to identify the new
    account later.
    """
    app = ctx.obj['app']
    if uuid:
        id_ = str(uuid4())
    else:
        id_ = None
    privkey_hex = f.read()
    try:
        privkey = privkey_hex.strip().decode('hex')
    except TypeError:
        click.echo('Could not decode private key from file (should be hex encoded)')
        sys.exit(1)
    password = ctx.obj['password']
    if password is None:
        password = click.prompt('Password to encrypt private key', default='', hide_input=True,
                                confirmation_prompt=True, show_default=False)
    account = Account.new(password, privkey, uuid=id_)
    account.path = os.path.join(app.services.accounts.keystore_dir, account.address.encode('hex'))
    try:
        app.services.accounts.add_account(account)
    except IOError:
        click.echo('Could not write keystore file. Make sure you have write permission in the '
                   'configured directory and check the log for further information.')
        sys.exit(1)
    else:
        click.echo('Account creation successful')
        click.echo('  Address: ' + account.address.encode('hex'))
        click.echo('       Id: ' + str(account.uuid))
Exemplo n.º 40
0
    def test_marshalling(self):
        # Create an account and convert it to bytes
        in_name = 'Love that hard c**k!'
        account = Account('Visual')
        account.generateKeys()
        logging.debug('Before marshal %s', account)
        buffer = account.toBytes()
#        print('test_marshalling:',buffer.hex())
        logging.debug('Marshalled buffer: %s', buffer.hex())
        # Create a new account from the bytes
        new_account = Account('')
        new_account.fromBytes(buffer)
        logging.debug('Unmarshalled %s', account)
        # Check if they have the content
        self.assertTrue(new_account.equals(account))

        # Different names should be okay, if all else is the same
        new_name = 'resurected!'
        new_account.setName(new_name)
        self.assertEqual(new_name, new_account.getName(),'Account name not set correctly!')
        self.assertTrue(new_account.equals(account), "Names should not affect Account equality!")
Exemplo n.º 41
0
def account_slug(slug):
    acct_type, username = slug.split(':', 1)
    for cls in Account.__subclasses__():
        if acct_type == cls.__name__ or acct_type == cls.shortname():
            return cls(username=username)
Exemplo n.º 42
0
 def __init__(self):
     self.rows=[]
     self.account=Account('budgetacc',rub)
     self.bying_targets=None
     self.executions=[]
Exemplo n.º 43
0
class Budget:
    def __init__(self):
        self.rows=[]
        self.account=Account('budgetacc',rub)
        self.bying_targets=None
        self.executions=[]
    def Add(self, row):
        self.rows.append(row)
    def get_buying_targets(self):
        return self.bying_targets

    def check_item_execution(self,budget_item, foradate):
        is_todo=False
        is_overdue=False
        is_executed=self._check_is_executed(budget_item,foradate)
        if not is_executed:
            is_overdue=self._is_item_overdue(budget_item, foradate)

        if budget_item.exactdate and budget_item.debit>0:
            if (not is_overdue) and (not is_executed):
                if budget_item.exactdate>=foradate:
                    diff=budget_item.exactdate- foradate
                    if diff.days<31:
                        is_todo=True

                    if budget_item.period!=BudgetFreq.OneTime:
                        if budget_item.debit<2000:
                            is_todo=False

        return is_overdue, is_executed, is_todo

    def _check_is_executed(self,budget_item,date):
        res=False

        if budget_item.behaviour==BudgetBehaviour.Done:
            return True



        p=None
        if budget_item.period== BudgetFreq.Annually:

            p=common.CalendarHelper.Period(datetime(budget_item.exactdate.year,1,1),datetime(budget_item.exactdate.year,12,31,23,59,59))
        if budget_item.period== BudgetFreq.OneTime:

            p=common.CalendarHelper.Period(datetime(2000,1,1),datetime(3000,1,1))
        if budget_item.period== BudgetFreq.Monthly:
            if budget_item.exactdate:
                s=datetime(budget_item.exactdate.year,budget_item.exactdate.month,1)

                if s.month+1>12:
                    e=datetime(s.year+1,1,1)-timedelta(seconds=1)
                else:
                    e=datetime(s.year,s.month+1,1)-timedelta(seconds=1)
                p=common.CalendarHelper.Period(s,e)

        if not p:
            return False

        for eid, edate in self.executions:
            if eid!=budget_item.id and (eid!=budget_item.description):
                continue
            if edate>=p.start and edate<=p.end:
                res=True
                break

        return res
    def _is_item_overdue(self, budget_item, foradate):

        if budget_item.debit<1:
            return False

        if budget_item.behaviour==BudgetBehaviour.Expectation:
            return False

        item_date=budget_item.exactdate
        if not item_date:

            if budget_item.period==BudgetFreq.Monthly:
                day=1
                if budget_item.day!=0:
                    day=budget_item.day
                item_date=datetime(foradate.year, foradate.month,day)

            if not item_date:
                return False

        if item_date<foradate:

            #фильтруем шум периодических расходов
            if budget_item.period!=BudgetFreq.OneTime:
                diff=foradate-item_date
                if diff.days>30:
                    return False
                if budget_item.debit<2000:
                    return False
                #фильтруем end
            return True
        return False
    def create_buying_target(self, srcitem, dt):
        if not self.in_time_limit(srcitem, dt):
            return srcitem
        budget2=srcitem
        if srcitem.behaviour!=BudgetBehaviour.Expectation:
            budget2=copy.copy(srcitem)
            #budget2._description=budget2.description
            budget2._description=budget2.description+"({0})".format(dt.year)
            if budget2.period== BudgetFreq.Monthly:
                budget2._description=budget2.description+"({0}-{1})".format(dt.year,dt.month)
            budget2.id=budget2.description.lower()
            budget2.exactdate=dt
            self.bying_targets.append(budget2)
        return budget2
    def make_statement(self, start_date,currency=usd,forNyears=1):
        self.bying_targets=[]
        self._start=start_date


        for budget in self.rows:
            if budget.period== BudgetFreq.Annually:
                for year_repeater in range(0,forNyears):
                    dt=datetime(self._start.year+year_repeater,budget.exactdate.month,budget.exactdate.day )

                    bcopy=self.create_buying_target(budget, dt)
                    self.createline(bcopy, dt)


            if budget.period== BudgetFreq.OneTime:
                if budget.behaviour!=BudgetBehaviour.Done:
                    if budget.debit>0:
                        self.bying_targets.append(budget)
                        #budget.isoverdue=True
                self.createline(budget, budget.exactdate)

            if budget.period== BudgetFreq.Monthly:
                #self.bying_targets.append(budget)
                for year_repeater in range(0,forNyears):
                    day=1
                    if budget.day!=0:
                        day=budget.day
                    for mo in range(1,13):
                        date=datetime(self._start.year+year_repeater, mo,day)

                        bcopy=self.create_buying_target(budget, date)
                        self.createline(bcopy, date)


            if budget.period==BudgetFreq.Daily:
                cur=self._start
                for day in range(1,365*forNyears):
                    self.createline(budget, cur)
                    cur+=timedelta(days=1)

            if budget.period== BudgetFreq.Weekly:
                cur=self._start
                di=cur.weekday()
                ti=1 #monday

                if budget.day!=0:
                    ti=budget.day

                cur+=timedelta(days=(di-ti))

                for we in range(1,(365*forNyears)/7):
                    #date=datetime(self._start.year, mo,day)
                    self.createline(budget, cur)
                    cur+=timedelta(days=7)



        p = Pool()
        p.link_account(self.account)
        res=p.make_statement(currency)
        return res
    def in_time_limit(self,budget,date):
        if budget.start:
            if date<budget.start:
                return False

        if budget.end:
            if date>budget.end:
                return False
        return True
    def createline(self, budget, date):
        if not self.in_time_limit(budget, date):
            return

        amnt=budget.debit
        if budget.credit>0:
            amnt=budget.credit
        tx=Tx(amnt,date)
        tx._tags=budget.tags
        tx.comment=budget.description

        tx.src=TxSource("fn","sn",0,0)
        tx.source_budget=budget

        if budget.credit>0:
            self.account.income(tx)
        else:
            self.account.out(tx)

            #(self, period, day,debit, credit, currency,tags, description, exactdate=None):
    def xsldate(self, xslsvalue):
        res=None

        if isinstance(xslsvalue, float):

            tdate=xlrd.xldate_as_tuple(xslsvalue,0)
            res=datetime(tdate[0],tdate[1],tdate[2])
        return res
    def read_executions(self,filename, sheetname):
        book = xlrd.open_workbook(filename)
        sheet=book.sheet_by_name(sheetname)

        for rowi in range(1,sheet.nrows):
            r=sheet.row(rowi)
            sid=r[1].value.lower()
            if len(sid)>0:
                xlsdate=r[2].value
                tdate=xlrd.xldate_as_tuple(xlsdate,0)
                exactdate=datetime(tdate[0],tdate[1],tdate[2])
                self.executions.append( (sid,exactdate) )
    def read(self, filename, sheetname):
        print "  budget",filename
        book = xlrd.open_workbook(filename)
        sheet=book.sheet_by_name(sheetname)
        #expectation

        behavemap={"expectation":BudgetBehaviour.Expectation, "done":BudgetBehaviour.Done}

        periodsmap={"monthly":BudgetFreq.Monthly,"weekly":BudgetFreq.Weekly,"annually": BudgetFreq.Annually,"onetime": BudgetFreq.OneTime, "daily": BudgetFreq.Daily}
        for rowi in range(1,sheet.nrows):
            r=sheet.row(rowi)
            speriod=r[1].value.lower()
            sday=r[2].value
            day=1
            exactdate=None
            if isinstance(sday, float):
                if sday>31:
                    xlsdate=sday
                    tdate=xlrd.xldate_as_tuple(xlsdate,0)
                    exactdate=datetime(tdate[0],tdate[1],tdate[2])
                else:
                    day=int(sday)
            if len(speriod)<1 and exactdate:
                speriod="onetime"

            if len(speriod)<1:
                continue

            if not periodsmap.has_key(speriod):
                raise Exception("Unknown Period '{0}' at row {1}".format(speriod, rowi))

            period=periodsmap[speriod]

            scur=r[9].value.upper().strip()
            currency=rub
            if len(scur)>0:
                currency, cur_index=Currency.str_to_currency_code(scur)

            sbehave=r[10].value.lower().strip()
            behave=BudgetBehaviour.Std
            if len(sbehave)>0:
                behave=behavemap[sbehave]
            saccomplished=""
            if len(r)>11:
                saccomplished=r[11].value

            tags=r[6].value.split(',')
            etags=[]
            for t in tags:
                st=t.strip()
                if len(st)>0:
                    etags.append(st)
            tags=etags


            debit=r[3].value
            if not isinstance(debit, float): debit=0
            credit=r[4].value
            if not isinstance(credit, float): credit=0
            descr=r[5].value
            if period==BudgetFreq.OneTime:
                if not exactdate:
                    mes=u"Exact date for budget line '{0}' missed".format(descr)
                    print mes
                    raise Exception(mes)
            id=r[0].value
            br=BudgetRow(period,day, debit,credit,currency,tags,descr,id,saccomplished,exactdate=exactdate,behaviour=behave)
            self.Add(br)



            br.start=self.xsldate(r[7].value)
            br.end=self.xsldate(r[8].value)
            #tdate=xlrd.xldate_as_tuple(xlsdate,0)
            #date=datetime(tdate[0],tdate[1],tdate[2],tdate[3],tdate[4],tdate[5])
    def diff(self,plan, actual):

        pass