示例#1
0
def block_user():
    user_id = request.form.get('id')
    blocked_id = request.form.get('blocked_id')
    newBlock = Block(user_id = user_id, blocked_id = blocked_id)
    db.session.add(newBlock)
    db.session.commit()
    return newBlock.to_dict()
示例#2
0
def new_class():
    teacher = Teacher.query.filter_by(id=current_user.id).first()
    try:
        blocks = teacher.blocks
    except exc.SQLAlchemyError:
        pass
    manual_block_form = ManualBlockForm()

    if manual_block_form.validate_on_submit():
        subject = Subject(title=manual_block_form.class_subject.data)
        db.session.add(subject)
        db.session.commit()
        subject = Subject.query.filter_by(
            title=manual_block_form.class_subject.data, ).first()
        block = Block(
            subject_id=subject.id,
            teacher_id=teacher.id,
            title=manual_block_form.class_block.data,
        )
        db.session.add(block)
        db.session.commit()

        return redirect(url_for('classes'))

    return render_template(
        'classes/new_class.html',
        blocks=blocks,
        manual_block_form=manual_block_form,
    )
示例#3
0
def listblocks() -> int:
    """Synch block data from node

    :return int: number of new blocks synched to database
    """

    # TODO: Handle blockchain forks gracefully

    client = get_active_rpc_client()

    height_node = client.getblockcount()['result']
    latest_block_obj = Block.select().order_by(Block.height.desc()).first()
    if latest_block_obj is None:
        height_db = 0
    else:
        height_db = latest_block_obj.height

    if height_db == height_node:
        return 0

    synced = 0

    for batch in batchwise(range(height_db, height_node), 100):

        new_blocks = client.listblocks(batch)

        with data_db.atomic():
            for block in new_blocks['result']:

                addr_obj, adr_created = Address.get_or_create(
                    address=block['miner'])
                block_obj, blk_created = Block.get_or_create(
                    hash=unhexlify(block['hash']),
                    defaults=dict(
                        time=datetime.fromtimestamp(block['time']),
                        miner=addr_obj,
                        txcount=block['txcount'],
                        height=block['height'],
                    ))
                if blk_created:
                    synced += 1

                log.debug('Synced block {}'.format(block_obj.height))
                signals.database_blocks_updated.emit(block_obj.height,
                                                     height_node)
    log.debug('Synced {} blocks total.'.format(synced))
    return synced
示例#4
0
def create_block_zero_if_needed():
    block = Block.query.filter(Block.id == 0).first()
    ts = datetime.fromtimestamp(0)
    if block is None:
        block = Block(id=0, created=ts)
        db.session.add(block)
        db.session.commit()
    return block
示例#5
0
def lambda_init_if_needed():
    # Creates the database record for the first block if it doesn't exist
    block = Block.query.filter(Block.id == 1).first()
    if block is None:
        block = Block()
        db.session.add(block)
        db.session.commit()

    return block
示例#6
0
文件: node.py 项目: shalir/Smilodon
def create_node():
    data = request.get_json(force=True)
    node = Node()
    node.parent = data['parent']
    node.name = data['text']
    node.type = data['type']
    node.owner_id = g.user.id
    db.session.add(node)
    db.session.flush()
    if node.type == 'file':
        note = Block()
        note.node_id = node.id
        note.content = ""
        db.session.add(note)
    db.session.commit()
    return jsonify({
        'id': node.id,
        'text': node.name,
        'type': node.type
    })
示例#7
0
def block_created():
    data = request.form

    # Only accept notification if secret key is present
    if data['secret'] != app.config['NOTIFY_SECRET_KEY']:
        abort(403)

    with blockchain_lock:
        lambda_init_if_needed()

        # TODO: consider the need for reprocessing
        block_num = data['block']
        block = Block()
        db.session.add(block)
        db.session.commit()

        # Something really dodgy is going on if this isn't the case
        app.logger.info("block_num  = {} | block.id = {}".format(
            block_num, block.id))

        return 'ACK block {}'.format(block.id)
示例#8
0
def process_blocks():
    """
    Find last valid Block, delete every Block above in DB and get all Blocks above from Node.
    Process through new Blocks:
    Add them to DB.
    Process through all transactions in block.
    """
    client = get_active_rpc_client()

    ### get last valid block in DB ###
    last_valid_height = -1
    last_block_is_valid = False
    with data_session_scope() as session:
        while not last_block_is_valid:
            latest_block = session.query(Block).order_by(
                Block.height.desc()).first()
            if not latest_block:
                break
            try:
                block_from_chain = client.getblock('{}'.format(
                    latest_block.height))
            except Exception as e:
                log.debug(e)
                return
            if latest_block.hash == unhexlify(block_from_chain['hash']):
                last_block_is_valid = True
                last_valid_height = latest_block.height
            else:
                session.delete(latest_block)

    blockchain_params = client.getblockchainparams()
    pubkeyhash_version = blockchain_params['address-pubkeyhash-version']
    checksum_value = blockchain_params['address-checksum-value']

    block_count_node = client.getblockcount()

    with data_session_scope() as session:
        # height is 0 indexed,
        for batch in batchwise(range(last_valid_height + 1, block_count_node),
                               100):
            try:
                with data_session_scope() as session:
                    signals.batch_gui_updates_allowed.emit(False)
                    new_blocks = client.listblocks(batch)

                    first = True
                    for block in new_blocks:
                        # Allow emitting certain GUI update signals for the first block in the batch
                        # or if we're close to the current node block count
                        if first or block_count_node - block['height'] < 16:
                            signals.batch_gui_updates_allowed.emit(True)
                        block_obj = Block(
                            hash=unhexlify(block['hash']),
                            height=block['height'],
                            mining_time=datetime.fromtimestamp(block['time']),
                        )
                        session.add(block_obj)
                        session.add(
                            MiningReward(block=unhexlify(block['hash']),
                                         address=block['miner']))
                        Address.create_if_not_exists(session, block['miner'])
                        if block['txcount'] > 1:
                            process_transactions(session, block['height'],
                                                 pubkeyhash_version,
                                                 checksum_value, client)
                        signals.database_blocks_updated.emit(
                            block['height'], block_count_node)
                        signals.blockschanged.emit(
                            session.query(Block).count())
                        # Skip certain GUI update signals for the remainder of the batch
                        if first:
                            signals.batch_gui_updates_allowed.emit(False)
                            first = False
            except Exception as e:
                signals.batch_gui_updates_allowed.emit(True)
                log.debug('Exception in process_blocks:')
                log.debug(e)
                return
    signals.batch_gui_updates_allowed.emit(True)

    if last_valid_height != block_count_node:
        # permissions and votes tables are completely refreshed after each new block
        process_permissions()
示例#9
0
def getblock():
    """Process detailed data from individual blocks to find last votes from guardians"""

    # TODO cleanup this deeply nested mess :)

    client = get_active_rpc_client()
    global getblock_proccessed_height
    blockchain_params = client.getblockchainparams()['result']
    pubkeyhash_version = blockchain_params['address-pubkeyhash-version']
    checksum_value = blockchain_params['address-checksum-value']

    block_objs = Block.multi_tx_blocks().where(
        Block.height > getblock_proccessed_height)

    votes_changed = False

    with data_db.atomic():
        for block_obj in block_objs:
            height = block_obj.height
            block_info = client.getblock("{}".format(height))['result']
            for txid in block_info['tx']:
                transaction = client.getrawtransaction(txid, 4)
                if transaction['error'] is None:
                    if 'vout' in transaction['result']:
                        vout = transaction['result']['vout']
                        permissions = []
                        start_block = None
                        end_block = None
                        for vout_key, entry in enumerate(vout):
                            if len(entry['permissions']) > 0:
                                for key, perm in entry['permissions'][0].items(
                                ):
                                    if perm and key in permission_candidates:
                                        permissions.append(key)
                                    if key == 'startblock':
                                        start_block = perm
                                    if key == 'endblock':
                                        end_block = perm
                                in_entry = transaction['result']['vin'][
                                    vout_key]
                                public_key = in_entry['scriptSig'][
                                    'asm'].split(' ')[1]
                                from_pubkey = public_key_to_address(
                                    public_key, pubkeyhash_version,
                                    checksum_value)
                                given_to = entry['scriptPubKey']['addresses']
                                for addr in given_to:
                                    log.debug(
                                        'Grant or Revoke {} given by {} to {} at time {}'
                                        .format(permissions, from_pubkey, addr,
                                                block_obj.time))
                                    addr_from_obj, _ = Address.get_or_create(
                                        address=from_pubkey)
                                    addr_to_obj, _ = Address.get_or_create(
                                        address=addr)
                                    vote_obj, created = Vote.get_or_create(
                                        txid=txid,
                                        defaults=dict(
                                            from_address=addr_from_obj,
                                            to_address_id=addr_to_obj,
                                            time=block_obj.time))
                                    if created:
                                        votes_changed = True

            getblock_proccessed_height = height

    if votes_changed:
        signals.votes_changed.emit()
示例#10
0
        full_name='Zachery Haley',
        email='*****@*****.**',
        belt_color='Brown',
        affiliation='GFTeam',
        avatar=
        'https://64.media.tumblr.com/ed6c711e9bcf78d9e07ed9d49f74a49a/5e7104cb65b9b19f-77/s400x600/1fef80e0b5e89ad70a5d526fdcf0d706994c724a.jpg',
        encrypted_password=bcrypt.hashpw("onepiece".encode('utf-8'),
                                         bcrypt.gensalt(14)))

    miss_goldenweek = User(
        username='******',
        full_name='demo land',
        email='*****@*****.**',
        belt_color='Black',
        affiliation='Checkmat',
        avatar=
        'https://64.media.tumblr.com/3e0c719e439014c6b222de0b6ba8098c/5e7104cb65b9b19f-41/s250x400/7e0acb01126538cec6adeb35272514439aac799f.jpg',
        encrypted_password=bcrypt.hashpw("password".encode('utf-8'),
                                         bcrypt.gensalt(14)))

    block1 = Block(user_id=1, blocked_id=2)

    block2 = Block(user_id=1, blocked_id=3)
    db.session.add(demo_user)
    db.session.add(mister_3)
    db.session.add(miss_monday)
    db.session.add(Zackitty)
    db.session.add(miss_goldenweek)
    db.session.add(block1)
    db.session.add(block2)
    db.session.commit()