Beispiel #1
0
def tx_retract(tx, cursor):
    payload = json.loads(tx.payload)
    payload['amount'] = int(payload['amount'])

    sender = models.Account(tx.chain_id, tx.sender, cursor)
    asset_stat = stats.Asset(tx.chain_id, cursor)

    sender.delegate -= payload['amount']
    sender.balance += payload['amount']
    del_addr = sender.del_addr
    if sender.delegate == 0:
        sender.del_addr = None
    sender.save(cursor)
    rel = models.RelAccountTx(tx.chain_id, tx.sender, tx.height, tx.index,
                              cursor)
    rel.amount += payload['amount']
    rel.save(cursor)

    delegatee = models.Account(tx.chain_id, del_addr, cursor)
    delegatee.eff_stake -= payload['amount']
    delegatee.save(cursor)

    asset_stat.active_coins += payload['amount']
    asset_stat.delegates -= payload['amount']
    asset_stat.save(cursor)
def tx_grant(tx, cursor):
    payload = json.loads(tx.payload)

    parcel = models.Parcel(tx.chain_id, payload['target'], None, cursor)
    storage = models.Storage(tx.chain_id, parcel.storage_id, None, cursor)
    host = models.Account(tx.chain_id, storage.owner, cursor)
    owner = models.Account(tx.chain_id, parcel.owner, cursor)
    request = models.Request(tx.chain_id, payload['target'],
                             payload['grantee'], cursor)
    usage = models.Usage(tx.chain_id, payload['target'], payload['grantee'],
                         cursor)

    usage.custody = payload['custody']
    usage.extra = payload.get('extra', '{}')
    usage.save(cursor)

    owner.balance += request.payment
    if request.dealer is not None:
        dealer = models.Account(tx.chain_id, request.dealer, cursor)
        dealer.balance += request.dealer_fee
        dealer.save(cursor)
    owner.balance -= storage.hosting_fee
    owner.save(cursor)

    host.balance += storage.hosting_fee
    host.save(cursor)

    request.delete(cursor)
def tx_transfer(tx, cursor):
    payload = json.loads(tx.payload)
    payload['amount'] = int(payload['amount'])

    sender = models.Account(tx.chain_id, tx.sender, cursor)
    sender.balance -= payload['amount']
    sender.save(cursor)

    recp = models.Account(tx.chain_id, payload['to'], cursor)
    recp.balance += payload['amount']
    recp.save(cursor)
Beispiel #4
0
def tx_grant(tx, cursor):
    payload = json.loads(tx.payload)

    grantee = ''
    if 'grantee' in payload:
        grantee = payload['grantee']
    elif 'recipient' in payload:
        grantee = payload['recipient']

    parcel = models.Parcel(tx.chain_id, payload['target'], None, cursor)
    storage = models.Storage(tx.chain_id, parcel.storage_id, None, cursor)
    host = models.Account(tx.chain_id, storage.owner, cursor)
    owner = models.Account(tx.chain_id, parcel.owner, cursor)
    # NOTE: This is line is for creating buyer account in s_accounts table. It
    # is necessary to satisfy the foreign key constraint. Even if we create a
    # row for each tx sender, it is not the case for the recipient for
    # `request` or `grant` tx. So, we need to explicitly create a grantee or
    # recipient account in s_accounts table.
    buyer = models.Account(tx.chain_id, grantee, cursor)
    buyer.save(cursor)
    request = models.Request(tx.chain_id, payload['target'], grantee, cursor)
    usage = models.Usage(tx.chain_id, payload['target'], grantee, cursor)

    usage.custody = payload['custody']
    usage.extra = json.dumps(payload.get('extra', {}))
    usage.save(cursor)
    if tx.sender not in yappers:
        rel = models.RelParcelTx(tx.chain_id, parcel.parcel_id, tx.height,
                                 tx.index)
        rel.save(cursor)

    owner.balance += request.payment
    if request.dealer is not None:
        dealer = models.Account(tx.chain_id, request.dealer, cursor)
        dealer.balance += request.dealer_fee
        dealer.save(cursor)
    owner.balance -= storage.hosting_fee
    owner.save(cursor)
    if storage.hosting_fee > 0:
        rel = models.RelAccountTx(tx.chain_id, owner.address, tx.height,
                                  tx.index, cursor)
        rel.amount -= storage.hosting_fee
        rel.save(cursor)

        host.balance += storage.hosting_fee
        host.save(cursor)
        rel = models.RelAccountTx(tx.chain_id, host.address, tx.height,
                                  tx.index, cursor)
        rel.amount += storage.hosting_fee
        rel.save(cursor)

    request.delete(cursor)
Beispiel #5
0
def hydrate(engine=Engine, session=Session):

    accounts = [
        m.Account(name='Burger Kwik'),
        m.Account(name='Chikin Likin'),
        m.Account(name='Pizza Face')]

    locations = [
        m.Location(
            name='BK1',
            address='314 Circle Ct',
            account=accounts[0]),
        m.Location(
            name='BK2',
            address='1350 American Way',
            account=accounts[0]),
        m.Location(
            name='CL1',
            address='2718 Euler Blvd',
            account=accounts[1])]

    users = [
        m.User(
            name='Peter',
            account=accounts[0]),
        m.User(
            name='Paul',
            account=accounts[0]),
        m.User(
            name='Mary',
            account=accounts[0]),
        m.User(
            name='Karen',
            account=accounts[2]),
        m.User(
            name='Richard',
            account=accounts[2])]

    features = _features(
        locations[0], 'low',
        datetime.date(2016, 12, 1), datetime.date(2016, 12, 7))
    features += _features(
        locations[0], 'high',
        datetime.date(2016, 12, 1), datetime.date(2016, 12, 7))

    session.add_all(accounts)
    session.add_all(locations)
    session.add_all(users)
    session.commit()
Beispiel #6
0
def create_account():
    if session.get('username') and session.get('type') == 'executive':
        if request.method == 'POST':
            customer = models.Customer.query.filter_by(
                cid=request.form['cid']).first()
            if customer != None:
                cid = request.form['cid']
            else:
                cid = None
            accnt_type = request.form['accnt_type']
            ammount = int(request.form['ammount'])

            if cid and accnt_type and ammount:
                account = models.Account.query.filter_by(
                    customer_cid=cid, accnt_type=accnt_type).first()
                if (account == None):
                    account = models.Account(customer_cid=cid,
                                             accnt_type=accnt_type,
                                             ammount=ammount)
                    db.session.add(account)
                    db.session.commit()
                    flash("Account Created successfully!", "success")
                else:
                    flash(
                        "Account with CID : " + cid + " and Type : " +
                        accnt_type + " already exists!", "warning")
                return render_template('Customer/create_account.html')
        elif request.method == 'GET':
            return render_template('Customer/create_account.html')
    else:
        flash("Login first as a Executive", "danger")
        return redirect(url_for('login'))
Beispiel #7
0
def tx_request(tx, cursor):
    payload = json.loads(tx.payload)
    payload['payment'] = int(payload['payment'])
    payload['dealer_fee'] = int(payload.get('dealer_fee', '0'))

    buyer = models.Account(tx.chain_id, tx.sender, cursor)
    parcel = models.Parcel(tx.chain_id, payload['target'], None, cursor)
    request = models.Request(tx.chain_id, parcel.parcel_id, buyer.address,
                             cursor)

    request.payment = payload['payment']
    request.dealer = payload.get('dealer', None)
    request.dealer_fee = payload['dealer_fee']
    request.extra = json.dumps(payload.get('extra', {}))
    request.save(cursor)
    if tx.sender not in yappers:
        rel = models.RelParcelTx(tx.chain_id, parcel.parcel_id, tx.height,
                                 tx.index)
        rel.save(cursor)

    if request.dealer is not None:
        buyer.balance -= request.dealer_fee
    buyer.balance -= request.payment
    buyer.save(cursor)
    rel = models.RelAccountTx(tx.chain_id, buyer.address, tx.height, tx.index,
                              cursor)
    rel.amount -= request.payment
    rel.save(cursor)
def update_account(db: SQLAlchemy):
    to_save = request.form.to_dict()
    updating = 'account_id' in to_save

    if updating:
        account = db.session.query(models.Account).filter(
            models.Account.id == to_save['account_id']).first()
    else:
        account = models.Account()
    account.name = to_save['name']
    account.enabled = 'enabled' in to_save
    account.type = to_save['type']
    account.access_key = to_save['access_key']
    account.secret_key = to_save['secret_key']
    account.bucket = to_save['bucket']
    account.prefix = to_save['prefix']
    account.use_ssl = 'use_ssl' in to_save

    try:
        if updating:
            db.session.merge(account)
        else:
            db.session.add(account)
        db.session.commit()
        flash('Account created', category='success')
        return redirect(
            url_for('config_account.config_account', account_id=account.id))
    except IntegrityError:
        db.session.rollback()
        flash('Account creation failed', category='error')

    if updating:
        return redirect(url_for('config_account.config_account'))
    else:
        return redirect(url_for('config_account.add_account'))
Beispiel #9
0
def do_minute_update():
    trackings = []
    #query observe list and do update:
    obs = models.StockItem()
    observings = obs.get_observe()
    obsList = []
    b = models.StockRealtime()
    if len(observings) > 0:
        for i in observings:
            c = i.get('code')
            obsList.append(c)
    #add new methods
        b.new_by_codes(obsList)
        b.save_all()
    #TODO: query tracking list and exe tradecommand;
    if len(b.stocks.values()) > 0:
        #get tradecommand and calculate trade result;
        trades = models.Trade()
        alltrade = trades.load_all()
        for b in alltrade:
            c = b.command.get('code')
            p = b.command.get('price')
            if p == b.stocks.get(c).get('trade'):
                act = models.Account()
                act.load(b.command.acc)
                cost = p * b.command.get('hands') * -100
                if act.balance > cost:
                    act.trans(cost)
                    act.update()
                    b.trading(b.command.get('hands'))
                    b.update()  #assume all completed
Beispiel #10
0
    def post(self):
        if any(f for f in ('email', 'password', 'name') if f not in self.data):
            raise APIError('Missing parameter(s)')
        if not utils.is_valid_email(self.data['email']):
            raise APIError('Invalid email address')
        if len(self.data['password']) < 8:
            raise APIError('Invalid password')
        if len(self.data['name']) < 3:
            raise APIError('Invalid name')

        try:
            models.get_active_account(email=self.data['email'])
            raise APIError('Email already registered')
        except models.Account.DoesNotExist:
            account = models.Account(name=self.data['name'], email=self.data['email'],
                                     password=generate_password_hash(self.data['password']),
                                     calories_goal=settings['default_calories_goal'])
            account.save()

            # make this account a user
            models.AccountRole(account=account, role=models.Role.get(code='user')).save()

            update_token = urlserializer.dumps({'id': account.id, 'active': True}, salt='account-update')
            url = url_for('public', path='apply-account-changes', account_id=account.id, token=update_token,
                          _external=True)

            tasks.send_activation_email.delay(account.id, url, update_token)
            return created_response('account', account_id=account.id)
def tx_delegate(tx, cursor):
    payload = json.loads(tx.payload)
    payload['amount'] = int(payload['amount'])

    sender = models.Account(tx.chain_id, tx.sender, cursor)
    sender.delegate += payload['amount']
    sender.balance -= payload['amount']
    sender.del_addr = payload['to']
    sender.save(cursor)

    delegatee = models.Account(tx.chain_id, sender.del_addr, cursor)
    delegatee.eff_stake += payload['amount']
    delegatee.save(cursor)

    asset_stat = stats.Asset(tx.chain_id, cursor)
    asset_stat.active_coins -= payload['amount']
    asset_stat.delegates += payload['amount']
    asset_stat.save(cursor)
Beispiel #12
0
def tx_vote(tx, cursor):
    payload = json.loads(tx.payload)

    voter = models.Account(tx.chain_id, tx.sender, cursor)
    draft = models.Draft(tx.chain_id, payload['draft_id'], None, cursor)
    vote = models.Vote(tx.chain_id, draft.draft_id, voter.address, cursor)

    vote.approve = payload['approve']
    vote.save(cursor)
 def play(self, cursor):
     if self.code != 0:
         return
     sender = models.Account(self.chain_id, self.sender, cursor)
     sender.balance -= int(self.fee)
     # NOTE: fee will be added to the balance of the block proposer as part
     # of block incentive in block.play_incentives().
     processor.get(self.type, tx_unknown)(self, cursor)
     self.play_events(cursor)
def hydrate(engine=Engine, session=Session):

    accounts = {
        'bk': m.Account(name='Burger Kwik'),
        'cl': m.Account(name='Chikin Likin'),
        'pf': m.Account(name='Pizza Face')}

    locations = [
        m.Location(
            name='BK1',
            address='314 Circle Ct',
            account=accounts['bk']),
        m.Location(
            name='BK2',
            address='1350 American Way',
            account=accounts['bk']),
        m.Location(
            name='CL1',
            address='2718 Euler Blvd',
            account=accounts['cl'])]

    users = [
        m.User(
            name='Peter',
            account=accounts['bk']),
        m.User(
            name='Paul',
            account=accounts['bk']),
        m.User(
            name='Mary',
            account=accounts['bk']),
        m.User(
            name='Karen',
            account=accounts['pf']),
        m.User(
            name='Richard',
            account=accounts['pf'])]

    session.add_all(accounts.values())
    session.add_all(locations)
    session.add_all(users)
    session.commit()
Beispiel #15
0
def tx_did_issue(tx, cursor):
    payload = json.loads(tx.payload)

    issuer = models.Account(tx.chain_id, tx.sender, cursor)
    vc = models.VC(tx.chain_id, payload['target'], issuer.address, cursor)
    vc.credential = json.dumps(payload['credential'])
    vc.active = True
    vc.save(cursor)

    rel = models.RelVCTx(tx.chain_id, vc.id, tx.height, tx.index)
    rel.save(cursor)
def tx_cancel(tx, cursor):
    payload = json.loads(tx.payload)

    buyer = models.Account(tx.chain_id, tx.sender, cursor)
    request = models.Request(tx.chain_id, payload['target'], tx.sender, cursor)

    buyer.balance += request.payment
    buyer.balance += request.dealer_fee
    buyer.save(cursor)

    request.delete(cursor)
Beispiel #17
0
def tx_did_claim(tx, cursor):
    payload = json.loads(tx.payload)

    owner = models.Account(tx.chain_id, tx.sender, cursor)
    did = models.DID(tx.chain_id, payload['target'], owner.address, cursor)
    did.document = json.dumps(payload['document'])
    did.active = True
    did.save(cursor)

    rel = models.RelDIDTx(tx.chain_id, did.id, tx.height, tx.index)
    rel.save(cursor)
Beispiel #18
0
 def test_verified_sender(self):
     email = '*****@*****.**'
     account = models.Account(email=email)
     account.put()
     response = self.testapp.post(
         '/mail/receive', json.dumps({
             'Text-part': 'foo',
             'Sender': email,
         }))
     self.assertEqual(response.status_int, 200)
     response = models.Response.query(ancestor=account.key).get()
     self.assertEqual(response.text, 'foo')
Beispiel #19
0
def auth_ac():
    ac_id = request.form['ac_id']
    user = g.user
    account = models.Account.get_by_id(ac_id)
    if not account:
        ac = session['LOA'][ac_id]
        account = models.Account(**ac)
    del session['LOA']
    user.accounts.append(account)
    models.db.session.add(user)
    models.db.session.commit()
    return account.response()
Beispiel #20
0
def tx_grant(tx, cursor):
    payload = json.loads(tx.payload)

    parcel = models.Parcel(tx.chain_id, payload['target'], None, cursor)
    storage = models.Storage(tx.chain_id, parcel.storage_id, None, cursor)
    host = models.Account(tx.chain_id, storage.owner, cursor)
    owner = models.Account(tx.chain_id, parcel.owner, cursor)
    request = models.Request(tx.chain_id, payload['target'],
                             payload['grantee'], cursor)
    usage = models.Usage(tx.chain_id, payload['target'], payload['grantee'],
                         cursor)

    usage.custody = payload['custody']
    usage.extra = json.dumps(payload.get('extra', {}))
    usage.save(cursor)
    # rel = models.RelParcelTx(tx.chain_id, parcel.parcel_id, tx.height,
    #                          tx.index, cursor)
    # rel.save(cursor)

    owner.balance += request.payment
    if request.dealer is not None:
        dealer = models.Account(tx.chain_id, request.dealer, cursor)
        dealer.balance += request.dealer_fee
        dealer.save(cursor)
    owner.balance -= storage.hosting_fee
    owner.save(cursor)
    if storage.hosting_fee > 0:
        rel = models.RelAccountTx(tx.chain_id, owner.address, tx.height,
                                  tx.index, cursor)
        rel.amount -= storage.hosting_fee
        rel.save(cursor)

        host.balance += storage.hosting_fee
        host.save(cursor)
        rel = models.RelAccountTx(tx.chain_id, host.address, tx.height,
                                  tx.index, cursor)
        rel.amount += storage.hosting_fee
        rel.save(cursor)

    request.delete(cursor)
Beispiel #21
0
 def test_everything(self):
     email = '*****@*****.**'
     account = models.Account(email=email)
     account.put()
     response = self.testapp.post(
         '/mail/receive',
         json.dumps({
             'Text-part': EXAMPLE_TEXT_PART,
             'Sender': email,
         }))
     self.assertEqual(response.status_int, 200)
     response = models.Response.query(ancestor=account.key).get()
     self.assertEqual(response.text, 'The greatest response!!')
Beispiel #22
0
def tx_setup(tx, cursor):
    payload = json.loads(tx.payload)
    payload['registration_fee'] = int(payload['registration_fee'])
    payload['hosting_fee'] = int(payload['hosting_fee'])

    owner = models.Account(tx.chain_id, tx.sender, cursor)
    storage = models.Storage(tx.chain_id, payload['storage'], owner.address,
                             cursor)

    storage.url = payload['url']
    storage.registration_fee = payload['registration_fee']
    storage.hosting_fee = payload['hosting_fee']
    storage.active = True
    storage.save(cursor)
Beispiel #23
0
    def post(self, token_info):
        email = token_info.get('email')
        sub = token_info.get('sub')

        account = ndb.Key(models.Account, sub).get()
        if account is None:
            try:
                account = models.Account(id=sub, email=email)
                mail.send_email_from_template(email, 'welcome')
                account.put()
            except Exception:
                self.abort(500, 'Unable to create account.')

        self.respond(account)
Beispiel #24
0
def tx_register(tx, cursor):
    payload = json.loads(tx.payload)

    owner = models.Account(tx.chain_id, tx.sender, cursor)
    parcel = models.Parcel(tx.chain_id, payload['target'], owner.address,
                           cursor)
    storage = models.Storage(tx.chain_id, parcel.storage_id, None, cursor)

    parcel.custody = payload['custody']
    if parcel.custody is not None and len(parcel.custody) > 100:
        parcel.custody = parcel.custody[:100]
    parcel.proxy_account = payload.get('proxy_account', None)
    if parcel.proxy_account is not None and len(parcel.proxy_account) > 40:
        parcel.proxy_account = parcel.proxy_account[:40]
    parcel.extra = json.dumps(payload.get('extra', {}))
    parcel.on_sale = True
    parcel.save(cursor)
    if tx.sender not in yappers:
        rel = models.RelParcelTx(tx.chain_id, parcel.parcel_id, tx.height,
                                 tx.index)
        rel.save(cursor)

    if storage.registration_fee > 0:
        owner.balance -= storage.registration_fee
        owner.save(cursor)
        rel = models.RelAccountTx(tx.chain_id, owner.address, tx.height,
                                  tx.index, cursor)
        rel.amount -= storage.registration_fee
        rel.save(cursor)

        host = models.Account(tx.chain_id, storage.owner, cursor)
        host.balance += storage.registration_fee
        host.save(cursor)
        rel = models.RelAccountTx(tx.chain_id, host.address, tx.height,
                                  tx.index, cursor)
        rel.amount += storage.registration_fee
        rel.save(cursor)
Beispiel #25
0
 def play(self, cursor):
     if self.code != 0:
         return
     # NOTE: This will create a tx sender's account in s_accounts even if a
     # fee is zero. It is necssary to satisfy the foreign key constraints in
     # various tables.
     sender = models.Account(self.chain_id, self.sender, cursor)
     if self.fee != 0:
         sender.balance -= int(self.fee)
         sender.save(cursor)
     processor = processorMap.get(self.type, tx_unknown)
     processor(self, cursor)
     # NOTE: fee will be added to the balance of the block proposer as part
     # of block incentive in block.play_incentives().
     self.play_events(cursor)
Beispiel #26
0
def insert_default_accounts():
    #[(login,pwHash, gmlevel)]
    accs = [('ADMINISTRATOR', 'a34b29541b87b7e4823683ce6c7bf6ae68beaaac', 3),
            ('GAMEMASTER', '7841e21831d7c6bc0b57fbe7151eb82bd65ea1f9', 2),
            ('MODERATOR', 'a7f5fbff0b4eec2d6b6e78e38e8312e64d700008', 1),
            ('PLAYER', '3ce8a96d17c5ae88a30681024e86279f1a38c041', 0)]

    for acc in accs:
        ac = models.Account()
        ac.username = acc[0]
        ac.pwHash = acc[1]
        ac.gmlevel = acc[2]
        db_session.add(ac)

    db_session.commit()
Beispiel #27
0
 def ResolveSteamUser(self, user_data):
     """Resolves user information to a blank pd2 confidence ndb.Account model.
 
 Assumes input data has been sanitized.
 
 Requires:
   user_data: String containing ID information to lookup
     (url, vanity, SteamID64, SteamID, etc.).
 
 Returns:
   models.Account blank object with steam_64 ID set.
 
 Raises:
   Pd2ConfidenceError if errors resolving user_data.
 """
     try:
         return models.Account(steam_64=int(user_data))
     except ValueError:
         pass
     if 'STEAM_0' in user_data:
         try:
             return models.Account(steam_64=steam_id.ToSteam64(user_data))
         except steam_id.SteamIdError, e:
             raise Pd2ConfidenceError(e)
def tx_register(tx, cursor):
    payload = json.loads(tx.payload)

    owner = models.Account(tx.chain_id, tx.sender, cursor)
    parcel = models.Parcel(tx.chain_id, payload['target'], owner.address,
                           cursor)
    storage = models.Storage(tx.chain_id, parcel.storage_id, None, cursor)
    host = models.Account(tx.chain_id, storage.owner, cursor)

    parcel.custody = payload['custody']
    if parcel.custody != None and len(parcel.custody) > 100:
        parcel.custody = parcel.custody[:100]
    parcel.proxy_account = payload.get('proxy_account', None)
    if parcel.proxy_account != None and len(parcel.proxy_account) > 40:
        parcel.proxy_account = parcel.proxy_account[:40]
    parcel.extra = payload.get('extra', '{}')
    parcel.on_sale = True
    parcel.save(cursor)

    owner.balance -= storage.registration_fee
    owner.save(cursor)

    host.balance += storage.registration_fee
    host.save(cursor)
Beispiel #29
0
def tx_cancel(tx, cursor):
    payload = json.loads(tx.payload)

    buyer = models.Account(tx.chain_id, tx.sender, cursor)
    request = models.Request(tx.chain_id, payload['target'], tx.sender, cursor)

    buyer.balance += request.payment
    buyer.balance += request.dealer_fee
    buyer.save(cursor)
    rel = models.RelAccountTx(tx.chain_id, buyer.address, tx.height, tx.index,
                              cursor)
    rel.amount += request.payment + request.dealer_fee
    rel.save(cursor)

    request.delete(cursor)
def tx_withdraw(tx, cursor):
    payload = json.loads(tx.payload)
    payload['amount'] = int(payload['amount'])

    sender = models.Account(tx.chain_id, tx.sender, cursor)
    sender.stake -= payload['amount']
    sender.eff_stake -= payload['amount']
    sender.balance += payload['amount']
    if sender.stake == 0:
        sender.val_addr = None
    sender.save(cursor)

    asset_stat = stats.Asset(tx.chain_id, cursor)
    asset_stat.active_coins += payload['amount']
    asset_stat.stakes -= payload['amount']
    asset_stat.save(cursor)