def add_block(new_block): block = Block() block.id = new_block['id'] block.creator = new_block['creator'] block.created_at = datetime.datetime.strptime(new_block['created_at'], '%Y-%m-%d %H:%M:%S.%f') block.prev_hash = new_block['prev_hash'] block.hash = new_block['hash'] block.difficulty = new_block['difficulty'] block.suffix = new_block['suffix'] block.root_hash = new_block['root_hash'] fx_session.add(block) return block
def post_block(): new_block = request.get_json() last_block = Block.query.order_by(Block.id.desc()).first() if not new_block: return jsonify(result='failed', message="empty block."), 400 if not last_block and new_block['id'] != 1: Block.sync( Node.query.order_by( Node.last_connected_at.desc()).first()) return jsonify(result='failed', message="new block isn't our next block."), 403 if (new_block['id'] > 1 and (new_block['id'] != last_block.id + 1 or new_block['prev_hash'] != last_block.hash)): if new_block['id'] > last_block.id + 1: Block.sync( Node.query.order_by( Node.last_connected_at.desc()).first()) return jsonify(result='failed', message="new block isn't our next block."), 403 block = Block() block.id = new_block['id'] block.creator = new_block['creator'] block.created_at = datetime.datetime.strptime( new_block['created_at'], '%Y-%m-%d %H:%M:%S.%f') block.prev_hash = new_block['prev_hash'] block.hash = new_block['hash'] block.difficulty = new_block['difficulty'] block.suffix = new_block['suffix'] block.root_hash = new_block['root_hash'] for new_move in new_block['moves']: move = Move.query.get(new_move['id']) if not move: move = Move( id=new_move['id'], user=new_move['user'], name=new_move['name'], signature=new_move['signature'], tax=new_move['tax'], details=new_move['details'], created_at=datetime.datetime.strptime( new_move['created_at'], '%Y-%m-%d %H:%M:%S.%f' ), block_id=block.id, ) if not move.valid: return jsonify(result='failed', message=f"move {move.id} isn't valid."), 400 block.moves.append(move) if not block.valid: return jsonify(result='failed', message="new block isn't valid."), 400 db.session.add(block) db.session.commit() sent_node = Node() if 'sent_node' in new_block: sent_node.url = new_block['sent_node'] block_broadcast.delay( block.id, sent_node_url=sent_node.url, my_node_url=f'{request.scheme}://{request.host}' ) return jsonify(result='success')