def address_reward_chart(coin_name, address): address_user = querys.get_address_user(address) if address_user is not None: results = create_reward_chart(coin_name, address) return response(results) else: return response(error_code=1018)
def get_address_payouts(coin_name, address): if request.args.get('page') is None: page = 1 else: page = int(request.args.get('page')) results = [] address_user = querys.get_address_user(address) if address_user is not None: my_payouts = Transactions.query.\ filter(Transactions.username == address).\ filter(Transactions.coin_name == coin_name).\ order_by(Transactions.timestamp.desc()).paginate(page, COUNT_PER_PAGE, error_out=False) if my_payouts is not None: for item in my_payouts.items: results.append(item.to_json()) return response({ 'transactions': results, 'hasNext': my_payouts.has_next }) return response(error_code=1007) else: return response(error_code=1018)
def coin_detail(coin_name): coin = querys.get_coin_with_coin_name(coin_name) if coin is None: return response(error_code=1000) # shares = querys.get_last_ten_minute_pool_accepted_shares(coin.name) # if shares[0][0] is not None: hashrate = utils.convert_hashrate_by_share(coin.algorithm, coin.pool_hash) if 'equihash' in coin.algorithm: pool_hash = utils.hashrate_to_readable_string(hashrate, 'equihash') else: pool_hash = utils.hashrate_to_readable_string(hashrate) # else: # pool_hash = '0 H/s' workers = Workers.query.filter(Workers.coin_name == coin.name).filter( Workers.disconnected.is_(None)).count() result = { 'name': coin.name, 'code': coin.code, 'port': coin.port, 'algorithm': coin.algorithm, 'fee': '%s %s' % (coin.fee, '%'), 'poolHash': pool_hash, 'activeWorkers': workers, 'transactionFee': coin.tx_fee, 'miningStatus': coin.mining_status, 'btcPrice': coin.btc_price, 'usdPrice': coin.usd_price, } return response(result)
def address_dashboard_info(coin_name, address): address_user = querys.get_address_user(address) if address_user is not None: result = create_my_stat(coin_name, address) return response(result) else: return response(error_code=1018)
def create_reward_history(coin_name, username): page = int(request.args.get('page')) history = db.session.query(Rewards, Block).join(Block).\ filter(Rewards.username == username).\ filter(Block.coin_name == coin_name).\ order_by(Rewards.timestamp.desc()).paginate(page, COUNT_PER_PAGE, error_out=False) if history is not None: results = [] for item in history.items: found_block = item.Block date = found_block.timestamp confirmations = found_block.confirmations need_confirmations = found_block.coin.confirmation_count if confirmations >= need_confirmations: confirm_message = 'confirmed' elif confirmations == -1: confirm_message = 'orphan' else: confirm_message = str(need_confirmations - confirmations) + ' left' result = { 'block': found_block.height, 'valid': confirm_message, 'difficulty': found_block.difficulty, 'reward': found_block.reward, 'your_reward': item.Rewards.reward, 'date': date.strftime("%Y-%m-%d %H:%M") } results.append(result) return response({'rewards': results, 'hasNext': history.has_next}) else: return response(error_code=1007)
def block_history(coin_name): if request.args.get('page') is None: page = 1 else: page = int(request.args.get('page')) history = querys.get_block_history_by_paging(coin_name, page, COUNT_PER_PAGE) coin = querys.get_coin_with_coin_name(coin_name) need_confirmations = coin.confirmation_count if history is not None: results = [] for found_block in history.items: date = found_block.timestamp confirmations = found_block.confirmations if confirmations >= need_confirmations: confirm_message = 'confirmed' elif confirmations == -1: confirm_message = 'orphan' else: confirm_message = str(need_confirmations - confirmations) + ' left' result = { 'block': found_block.height, 'valid': confirm_message, 'difficulty': found_block.difficulty, 'reward': found_block.reward, 'date': date.strftime("%Y-%m-%d %H:%M") } results.append(result) return response({'rewards': results, 'hasNext': history.has_next}) else: return response(error_code=1007)
def join(): body = simplejson.loads(request.data) if 'username' not in body or 'email' not in body or 'password' not in body: return response(error_code=1000) username = body['username'] password = body['password'] email = body['email'] if not check_user_validation(username, password, email): return response(error_code=1000) if not check_recaptcha(body['recaptcha']): return response(error_code=1010) if not check_exist_user(username, email): return response(error_code=1001) new_user = Users() new_user.username = username new_user.email = email new_user.password = hashlib.sha256(password.encode()).hexdigest() db.session.add(new_user) db.session.commit() session['username'] = username verify_email_send(email, username) return response()
def change_password(): username = session['username'] body = simplejson.loads(request.data) if 'old_password' not in body or 'new_password' not in body: return response(error_code=1000) old_password = body['old_password'] new_password = body['new_password'] login_user = Users.query.filter(Users.username == username).first() hash_old_password = hashlib.sha256(old_password.encode()).hexdigest() hash_new_password = hashlib.sha256(new_password.encode()).hexdigest() if login_user.password != hash_old_password: return response(error_code=1004) if hash_old_password == hash_new_password: return response(error_code=1005) login_user.password = hash_new_password db.session.commit() # TODO: Password 변경 Email Notification 구현 해야함 return response()
def delete_comments(comments_id): username = session['username'] comments = Comments.query.filter(Comments.id == comments_id).filter( Comments.username == username).first() if comments is None: return response(error_code=1000) db.session.delete(comments) db.session.commit() return response()
def verify_email(): username = session['username'] _body = simplejson.loads(request.data) is_valid_code = check_email_code_validation(username, _body['verify_code']) if is_valid_code is False: return response(error_code=1012) user = g.user user.state = 'normal' db.session.commit() return response()
def verify_email_send(email, username): # TODO balance 에서 또 보내는 경우에 대한 처리 필요 _already_send = EmailVerify.query.filter( EmailVerify.username == username).first() if _already_send is not None: total_seconds = (datetime.utcnow() - _already_send.created).total_seconds() if total_seconds < 600: return response(error_code=1013) if not os.getenv("DEBUG") == 'true': verify_code = send_verify_email(email, username) else: verify_code = generate_random_string() print(verify_code) if verify_code is not None: if _already_send is not None: email_verify = _already_send else: email_verify = EmailVerify() email_verify.verify_code = verify_code email_verify.username = username email_verify.created = datetime.utcnow() if _already_send is None: db.session.add(email_verify) db.session.commit() return email_verify
def mined_blocks(): coins = querys.get_open_coins() mined_block_list = Block.query.filter(Block.mined.is_(True)).order_by( Block.timestamp.desc()).limit(len(coins)) results = [] for block in mined_block_list: block_json = block.to_json() coin_confirmations = 100 # Default 100 for coin in coins: if coin.name == block.coin_name: coin_confirmations = coin.confirmation_count break if block.confirmations >= coin_confirmations: block_json['status'] = 'confirmed' elif block.confirmations == -1: block_json['status'] = 'orphan' else: block_json['status'] = '%s left' % (coin_confirmations - block.confirmations) results.append(block_json) return response(results)
def decorated_function(*args, **kwargs): if 'username' not in session: return response(error_code=1003) username = session['username'] cache_key = 'user:{}'.format(username) user = cache.get(cache_key) if cache.get('user:{}'.format(username)) is None: user = Users.query.filter(Users.username == username).first() cache.set(cache_key, user, timeout=60) if user is None: session.pop('username', None) return response(error_code=1003) g.user = user return f(*args, **kwargs)
def password_reset(uuid): username = cache.get(uuid) if username is None: return response(error_code=1000) temp_password = generate_random_string() _user = Users.query.filter(Users.username == username).first() _user.password = hashlib.sha256(temp_password.encode()).hexdigest() db.session.commit() if send_temp_password_email(_user.email, _user.username, temp_password) is None: return response(error_code=1013) cache.delete(uuid) return response()
def get_verify_email(): username = session['username'] _already_send = EmailVerify.query.filter( EmailVerify.username == username).first() if _already_send is not None: total_seconds = (datetime.utcnow() - _already_send.created).total_seconds() if total_seconds < 600: return response(error_code=1013) _user = g.user verify_code = verify_email_send(_user.email, _user.username) if verify_code is not None: return response() return response(error_code=1014)
def forget(): _body = simplejson.loads(request.data) if 'recaptcha' not in _body or not check_recaptcha(_body['recaptcha']): return response(error_code=1010) username = _body['username'] _user = Users.query.filter( or_(Users.username == username, Users.email == username)).first() if _user is None: return response(error_code=1018) uri = send_password_reset_email(_user.email, _user.username) if uri is None: return response(error_code=1013) cache.set(uri, _user.username, timeout=3600) return response()
def change_email_notification(): username = session['username'] body = simplejson.loads(request.data) email_notification_status = body['emailNotification'] Users.query.filter(Users.username == username).update( {'email_notification': email_notification_status}) db.session.commit() return response()
def login(): body = simplejson.loads(request.data) if 'username' not in body or 'password' not in body: return response(error_code=1000) if not check_recaptcha(body['recaptcha']): return response(error_code=1010) username = body['username'] password = body['password'] hash_password = hashlib.sha256(password.encode()).hexdigest() login_user = Users.query.filter(or_(Users.username == username, Users.email == username)). \ filter(Users.password == hash_password).first() if login_user is None: return response(error_code=1002) session['username'] = login_user.username return response()
def check_otp_code(): username = session['username'] body = simplejson.loads(request.data) if 'code' not in body: return response(error_code=1000) code = body['code'] try: is_valid = check_otp_validation(username, code) except ValueError: return response(error_code=1006) user = Users.query.filter(Users.username == session['username']).first() if is_valid is True: user.otp_state = True db.session.commit() return response() return response(error_code=1006)
def get_comments(page): try: page = int(page) except ValueError: page = 1 comments = Comments.query.filter(Comments.parent_id.is_(None)).order_by( Comments.created.desc()).paginate(page, 20, error_out=False) to_json = [item.to_json() for item in comments.items] return response({'comments': to_json, 'hasNext': comments.has_next})
def add_comments(): username = session['username'] body = simplejson.loads(request.data) if 'contents' not in body: return response(error_code=1000) contents = body['contents'] if len(contents) == 0: return response() parent_id = None if 'parent_id' in body and body['parent_id'] != 0: parent_id = body['parent_id'] comments = Comments() comments.username = username comments.contents = contents comments.parent_id = parent_id db.session.add(comments) db.session.commit() return response()
def pool_dashboard_info(coin_name): coin = querys.get_coin_with_coin_name(coin_name) last_block_info = Block.query. \ filter(Block.coin_name == coin_name). \ order_by(Block.height.desc()).first() last_mined_time = db.session.query(Block.timestamp). \ filter(Block.coin_name == coin_name). \ filter(Block.mined.is_(True)). \ order_by(Block.height.desc()).first() active_workers = db.session.query(Workers.username, Workers.name). \ filter(Workers.coin_name == coin_name). \ filter(Workers.disconnected.is_(None)). \ group_by(Workers.username, Workers.name).all() # shares = querys.get_last_ten_minute_pool_accepted_shares(coin_name) # if shares[0][0] is not None: hashrate = utils.convert_hashrate_by_share(coin.algorithm, coin.pool_hash) if 'equihash' in coin.algorithm: pool_hash = utils.hashrate_to_readable_string(hashrate, 'equihash') else: pool_hash = utils.hashrate_to_readable_string(hashrate) # else: # pool_hash = '0 H/s' active_users = set() for item in active_workers: active_users.add(item[0]) result = { 'poolHashRate': pool_hash, 'activeUsers': len(active_users), 'activeWorkers': len(active_workers) } if last_block_info is not None: result['lastBlockInfo'] = last_block_info.to_json() else: result['lastBlockInfo'] = Block().to_json() if last_mined_time is not None: result['lastMinedTime'] = last_mined_time[0] return response(result)
def generate_otp_key_and_get_qr_code(): user = Users.query.filter(Users.username == session['username']).first() if user.otp_key is None or len(user.otp_key) == 0: # generate OTP KEY user.otp_key = ''.join( random.SystemRandom().choice(string.ascii_letters) for _ in range(OTP_KEY_LENGTH)) db.session.commit() if user.otp_state is False: # generate QR code qr_code = pyotp.totp.TOTP(user.otp_key).provisioning_uri( user.username, issuer_name="ACPool") q = qrcode.make(qr_code) img = BytesIO() q.save(img) img.seek(0) return send_file(img, mimetype="image/png") return response()
def home_coins(): result_list = [] coins = querys.get_open_coins() all_workers = Workers.query.filter(Workers.disconnected.is_(None)).all() for coin in coins: hashrate = utils.convert_hashrate_by_share(coin.algorithm, coin.pool_hash) if 'equihash' in coin.algorithm: pool_hash = utils.hashrate_to_readable_string(hashrate, 'equihash') else: pool_hash = utils.hashrate_to_readable_string(hashrate) worker_count = 0 for worker in all_workers: if worker.coin_name == coin.name: worker_count += 1 result = { 'name': coin.name, 'code': coin.code, 'port': coin.port, 'algorithm': coin.algorithm, 'fee': '%s %s' % (coin.fee, '%'), 'poolHash': pool_hash, 'activeWorkers': worker_count, 'transactionFee': coin.tx_fee, 'btcPrice': coin.btc_price, 'usdPrice': coin.usd_price, 'miningStatus': coin.mining_status, } result_list.append(result) result_list = sorted(result_list, key=itemgetter('activeWorkers'), reverse=True) return response(result_list)
def pool_dashboard_chart(coin_name): start, end = utils.get_chart_start_end_datetime() coin = querys.get_coin_with_coin_name(coin_name) pool_graph_datas = db.session.query(func.sum(ShareStats.sum_share_difficulty), func.sum(ShareStats.accepted_share_count), func.sum(ShareStats.rejected_share_count), ShareStats.timestamp). \ filter(ShareStats.coin_name == coin_name). \ filter(ShareStats.timestamp >= start). \ filter(ShareStats.timestamp <= end). \ group_by(ShareStats.timestamp). \ order_by(ShareStats.timestamp).all() hashrates = [] shares = [] for share_stat in pool_graph_datas: hashrate = utils.convert_hashrate_by_share(coin.algorithm, share_stat[0]) date = share_stat[3].strftime('%Y%m%dT%H%M%SZ') accepted = share_stat[1] rejected = share_stat[2] hashrates.append({'date': date, 'pool': hashrate}) shares.append({ 'date': date, 'accepted': accepted, 'rejected': rejected }) result = { 'hashrates': hashrates, 'shares': shares, } return response(result)
def my_stat(): username = session['username'] # Last 24 Hours Earning coins coins = querys.get_open_coins() start_date = datetime.now() - timedelta(days=1) rewards = Rewards.query.filter(Rewards.username == username).filter( Rewards.timestamp > start_date).all() my_earning_coins = [] earnings = [] sum_of_unconfirmed_btc = 0 sum_of_unconfirmed_usd = 0 sum_of_confirmed_btc = 0 sum_of_confirmed_usd = 0 for reward in rewards: reward_coin = None for coin in coins: if coin.name == reward.block.coin_name: reward_coin = coin break if reward_coin is None: reward_coin = reward.block.coin reward_block = reward.block confirmations = reward_block.confirmations need_confirmations = reward_coin.confirmation_count btc_price = reward_coin.btc_price usd_price = reward_coin.usd_price if reward.block.coin_name not in my_earning_coins: my_earning_coins.append(reward_block.coin_name) earnings.append({ 'coinName': reward_block.coin_name, 'confirmed': 0, 'unconfirmed': 0 }) index = my_earning_coins.index(reward_block.coin_name) else: index = my_earning_coins.index(reward_block.coin_name) coin_result = earnings[index] if confirmations >= need_confirmations: coin_result['confirmed'] += reward.reward sum_of_confirmed_btc += reward.reward * btc_price sum_of_confirmed_usd += reward.reward * usd_price else: coin_result['unconfirmed'] += reward.reward sum_of_unconfirmed_btc += reward.reward * btc_price sum_of_unconfirmed_usd += reward.reward * usd_price if sum_of_confirmed_btc != 0 or sum_of_unconfirmed_btc != 0: earnings.append({ 'coinName': '*bitcoin', 'confirmed': sum_of_confirmed_btc, 'unconfirmed': sum_of_unconfirmed_btc }) if sum_of_confirmed_usd != 0 or sum_of_unconfirmed_usd != 0: earnings.append({ 'coinName': '*usdt', 'confirmed': sum_of_confirmed_usd, 'unconfirmed': sum_of_unconfirmed_usd }) for earning in earnings: earning['confirmed'] = utils.translate_float_string( round(earning['confirmed'], 8)) earning['unconfirmed'] = utils.translate_float_string( round(earning['unconfirmed'], 8)) # Current Workers status workers = Workers.query.filter(Workers.username == username).filter( Workers.disconnected.is_(None)).all() # 내 Worker가 일하고있는 코인들 my_working_coins = [] work_fors = [] for worker in workers: if worker.coin_name in my_working_coins: index = my_working_coins.index(worker.coin_name) else: my_working_coins.append(worker.coin_name) work_fors.append({'name': worker.coin_name, 'workers': 0}) index = my_working_coins.index(worker.coin_name) work_for = work_fors[index] work_for['workers'] += 1 # My Hashrate ten_minute_ago = datetime.now() - timedelta(minutes=10) shares = db.session.query(func.sum(Shares.pool_difficulty)).filter(Shares.pool_result.is_(True)). \ filter(Shares.timestamp > ten_minute_ago).filter(Shares.username == username).all() my_hashrate = 0.0 if shares[0][0] is not None: my_hashrate = shares[0][0] * 7158388.055 my_stat_result = { 'earnings': earnings, 'workers': len(workers), 'workFors': work_fors, 'hashrate': my_hashrate } return response(my_stat_result)
def address_reward_history(coin_name, address): address_user = querys.get_address_user(address) if address_user is not None: return create_reward_history(coin_name, address) else: return response(error_code=1018)
def my_reward_chart(coin_name): username = session['username'] results = create_reward_chart(coin_name, username) return response(results)
def get_user(): _user = Users.query.filter(Users.username == session['username']).first() g.user = _user return response(_user.to_json())
def logout(): session.pop('username', None) return response()