def get(self, id, height=None, range=None, fields=None): global database #database = lib.get_db() # Enforce range limit if range is not None: range = min(range, worker_block_range_limit) fields = lib.fields_to_list(fields) # AUTH FILTER if id != g.user.id: response = jsonify({ 'message': 'Not authorized to access data for other users' }) response.status_code = 403 return response if height is None or height == 0: blocks = Pool_blocks.get_latest(range, id) else: blocks = Pool_blocks.get_by_height(height, range, id) if range == None: if blocks is None: return None return blocks.to_json(fields, True) else: bl = [] for block in blocks: bl.append(block.to_json(fields, True)) return bl
def get(self, height=0, range=None, fields=None): database = lib.get_db() fields = lib.fields_to_list(fields) if height == 0: height = Pool_blocks.get_latest().height if range == None: block = Pool_blocks.get_by_height(height) if block is None: return None else: return block.to_json(fields) else: blocks = [] for block in Pool_blocks.get_by_height(height, range): blocks.append(block.to_json(fields)) return blocks
def calculate(height, avg_range): # Get the most recent pool data from which to generate the stats previous_stats_record = Pool_stats.get_by_height(height - 1) assert previous_stats_record is not None, "No previous stats record found" avg_over_first_grin_block = Blocks.get_by_height(max( height - avg_range, 1)) assert avg_over_first_grin_block is not None, "Missing grin block: {}".format( max(height - avg_range, 1)) grin_block = Blocks.get_by_height(height) assert grin_block is not None, "Missing grin block: {}".format(height) latest_worker_shares = Worker_shares.get_by_height(height) # If no shares are found for this height, we have 2 options: # 1) Assume the share data is *delayed* so dont create the stats record now # assert len(latest_worker_shares) > 0, "No worker shares found" # 2) If we want we can create the record without share data and then when shares are added later this record will be recalculated avg_over_worker_shares = Worker_shares.get_by_height(height, avg_range) # Calculate the stats data timestamp = grin_block.timestamp difficulty = POOL_MIN_DIFF # XXX TODO - enchance to support multiple difficulties gps = 0 active_miners = 0 shares_processed = 0 num_shares_in_range = 0 if len(avg_over_worker_shares) > 0: num_shares_in_range = sum( [shares.valid for shares in avg_over_worker_shares]) gps = grin.calculate_graph_rate(difficulty, avg_over_first_grin_block.timestamp, grin_block.timestamp, num_shares_in_range) print("XXX: difficulty={}, {}-{}, len={}".format( difficulty, avg_over_first_grin_block.timestamp, grin_block.timestamp, num_shares_in_range)) if latest_worker_shares is not None: active_miners = len(latest_worker_shares) # XXX NO, FIX THIS num_valid = sum([shares.valid for shares in latest_worker_shares]) num_invalid = sum([shares.invalid for shares in latest_worker_shares]) shares_processed = num_valid + num_invalid total_shares_processed = previous_stats_record.total_shares_processed + shares_processed total_grin_paid = previous_stats_record.total_grin_paid # XXX TODO total_blocks_found = previous_stats_record.total_blocks_found if Pool_blocks.get_by_height(height - 1) is not None: total_blocks_found = total_blocks_found + 1 return Pool_stats(height=height, timestamp=timestamp, gps=gps, active_miners=active_miners, shares_processed=shares_processed, total_shares_processed=total_shares_processed, total_grin_paid=total_grin_paid, total_blocks_found=total_blocks_found)
def calculate(height, window_size): # Get the most recent pool data from which to generate the stats previous_stats_record = Pool_stats.get_by_height(height - 1) assert previous_stats_record is not None, "No previous Pool_stats record found" grin_block = Blocks.get_by_height(height) assert grin_block is not None, "Missing grin block: {}".format(height) window = Worker_shares.get_by_height(height, window_size) # assert window[-1].height - window[0].height >= window_size, "Failed to get proper window size" # print("Sanity: window size: {} vs {}".format(window[-1].height - window[0].height, window_size)) # Calculate the stats data timestamp = grin_block.timestamp active_miners = len(list(set([s.user_id for s in window]))) print("active_miners = {}".format(active_miners)) # Keep track of share totals - sum counts of all share sizes submitted for this block num_shares_processed = 0 share_counts = {} for ws in Worker_shares.get_by_height(height): num_shares_processed += ws.num_shares() for size in ws.sizes(): size_str = "{}{}".format("C", size) if size_str not in share_counts: share_counts[size_str] = {"valid": 0, "invalid": 0, "stale": 0} share_counts[size_str] = { "valid": share_counts[size_str]["valid"] + ws.num_valid(size), "invalid": share_counts[size_str]["invalid"] + ws.num_invalid(size), "stale": share_counts[size_str]["stale"] + ws.num_stale(size) } print("num_shares_processed this block= {}".format(num_shares_processed)) total_shares_processed = previous_stats_record.total_shares_processed + num_shares_processed total_blocks_found = previous_stats_record.total_blocks_found # Caclulate estimated GPS for all sizes with shares submitted all_gps = estimate_gps_for_all_sizes(window) if Pool_blocks.get_by_height(height - 1) is not None: total_blocks_found = total_blocks_found + 1 new_stats = Pool_stats( height=height, timestamp=timestamp, active_miners=active_miners, share_counts=share_counts, shares_processed=num_shares_processed, total_blocks_found=total_blocks_found, total_shares_processed=total_shares_processed, dirty=False, ) print("all_gps for all pool workers") pp.pprint(all_gps) for gps_est in all_gps: gps_rec = Gps(edge_bits=gps_est[0], gps=gps_est[1]) new_stats.gps.append(gps_rec) sys.stdout.flush() return new_stats
def get(self, height=None, range=None, fields=None): fields = lib.fields_to_list(fields) if height is None or height == 0: blocks = Pool_blocks.get_latest(range) else: blocks = Pool_blocks.get_by_height(height, range) if range == None: if blocks is None: return None return blocks.to_json(fields) else: bl = [] for block in blocks: bl.append(block.to_json(fields)) return bl
def get(self, height=None, range=None, fields=None): database = lib.get_db() LOGGER = lib.get_logger(PROCESS) LOGGER.warn("PoolAPI_blocks get height:{} range:{} fields:{}".format( height, range, fields)) fields = lib.fields_to_list(fields) if height is None or height == 0: blocks = Pool_blocks.get_latest(range) else: blocks = Pool_blocks.get_by_height(height, range) if range == None: if blocks is None: return None return blocks.to_json(fields) else: bl = [] for block in blocks: bl.append(block.to_json(fields)) return bl
def get(self, height=None, range=None, fields=None): LOGGER = lib.get_logger(PROCESS) debug and LOGGER.warn("PoolAPI_blocks get height:{}, range:{}, fields:{}".format(height, range, fields)) # Enforce range limit if range is not None: range = min(range, pool_blocks_range_limit) fields = lib.fields_to_list(fields) if height is None or height == 0: blocks = Pool_blocks.get_latest(range) else: blocks = Pool_blocks.get_by_height(height, range) if range == None: if blocks is None: return None return blocks.to_json(fields) else: bl = [] for block in blocks: bl = [block.to_json(fields)] + bl return bl
def calculate(height, window_size): # Get the most recent pool data from which to generate the stats previous_stats_record = Pool_stats.get_by_height(height - 1) assert previous_stats_record is not None, "No previous Pool_stats record found" grin_block = Blocks.get_by_height(height) assert grin_block is not None, "Missing grin block: {}".format(height) window = Worker_shares.get_by_height(height, window_size) # Calculate the stats data timestamp = grin_block.timestamp active_miners = len(list(set([s.worker for s in window]))) print("active_miners = {}".format(active_miners)) # Keep track of share totals - sum counts of all share sizes submitted for this block shares_processed = 0 if len(window) > 0: shares_processed = window[-1].num_shares() print("shares_processed this block= {}".format(shares_processed)) total_shares_processed = previous_stats_record.total_shares_processed + shares_processed total_grin_paid = previous_stats_record.total_grin_paid # XXX TODO total_blocks_found = previous_stats_record.total_blocks_found # Caclulate estimated GPS for all sizes with shares submitted all_gps = estimate_gps_for_all_sizes(window) if Pool_blocks.get_by_height(height - 1) is not None: total_blocks_found = total_blocks_found + 1 new_stats = Pool_stats( height=height, timestamp=timestamp, active_miners=active_miners, shares_processed=shares_processed, total_blocks_found=total_blocks_found, total_shares_processed=total_shares_processed, total_grin_paid=total_grin_paid, dirty=False, ) print("all_gps for all pool workers") pp.pprint(all_gps) for gps_est in all_gps: gps_rec = Gps(edge_bits=gps_est[0], gps=gps_est[1]) new_stats.gps.append(gps_rec) sys.stdout.flush() return new_stats
def calculate_block_payout_map(height, window_size, logger, estimate=False): global reward_estimate_mutex reward_estimate_mutex.acquire() try: if estimate == True: cached_map = get_block_payout_map_estimate(height, logger) if cached_map is not None: return cached_map # Get pool_block record and check block state #print("getting the pool bloch: {}".format(height)) #sys.stdout.flush() poolblock = Pool_blocks.get_by_height(height) if poolblock is None: return {} #print("The pool block {}".format(poolblock.to_json())) #sys.stdout.flush() if estimate == True: if poolblock.state != "new" and poolblock.state != "unlocked": return {} else: if poolblock.state != "unlocked": return {} # Get an array with share counts for each block in the window shares = Worker_shares.get_by_height(height, window_size) #print("share data in window = {}".format(shares)) #sys.stdout.flush() # Get total value of this block: reward + fees reward = get_reward_by_block(height) #print("Reward for block {} = {}".format(height, reward)) #sys.stdout.flush() # Get the "secondary_scaling" value for this block scale = get_scale_by_block(height) #print("Secondary Scaling value for block = {}".format(scale)) #sys.stdout.flush() # build a map of total shares of each size for each user shares_count_map = get_share_counts(shares) # DUMMY DATA # scale = 529 # shares_count_map = { # 1: {29: 50}, # 2: {29: 25, 31: 10}, # 3: {32: 5}, # } #print("Shares Count Map:") #sys.stdout.flush() #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(shares_count_map) #sys.stdout.flush() # Calcualte total value of all shares total_value = calculate_total_share_value(shares_count_map, scale) #print("total share value in payment window: {}".format(total_value)) #sys.stdout.flush() block_payout_map = {} # For each user with shares in the window, calculate payout and add to block_payout_map for user_id, worker_shares_count in shares_count_map.items(): #print("xxx: {} {}".format(user_id, worker_shares_count)) #sys.stdout.flush() # Calcualte the total share value from this worker total_worker_value = calculate_total_share_value( {user_id: worker_shares_count}, scale) worker_payment = total_worker_value / total_value * reward #print("worker_payment: {}".format(worker_payment/1000000000)) #sys.stdout.flush() block_payout_map[user_id] = worker_payment #print("block_payout_map = {}".format(block_payout_map)) #sys.stdout.flush() if estimate == True: payout_estimate_map_key = "payout-estimate-for-block-" + str( height) try: # Estimates are cached in redis, save it there if we can redisdb = lib.get_redis_db() #redisdb.hmset(payout_estimate_map_key, json.dumps(block_payout_map)) redisdb.set(payout_estimate_map_key, pickle.dumps(block_payout_map)) except Exception as e: logger.warn( "block_payout_map cache insert failed: {} - {}".format( payout_estimate_map_key, repr(e))) except Exception as e: logger.error("Estimate went wrong: {} - {}".format( e, traceback.print_stack())) finally: reward_estimate_mutex.release() #logger.warn("calculate_map: {}".format(block_payout_map)) return block_payout_map
def calculate_block_payout_map(height, window_size, pool_fee, logger, estimate=False): block_payout_map = {} # Get the grinpool admin user ID for pool fee pool_admin_user_id = 1 # Total the payments for sanity check total_payments_this_block = 0 try: admin_user = os.environ["GRIN_POOL_ADMIN_USER"] pool_admin_user_id = Users.get_id_by_username(admin_user) logger.warn("Pool Fee goes to admin account with id={}".format( pool_admin_user_id)) except Exception as e: logger.warn( "We dont have Admin account info, using default id={}: {}".format( pool_admin_user_id, e)) # Create the payout map # Get pool_block record and check block state #print("getting the pool block: {}".format(height)) #sys.stdout.flush() if estimate == False: poolblock = Pool_blocks.get_by_height(height) if poolblock is None or poolblock.state != "unlocked": return {} #print("The pool block {}".format(poolblock.to_json())) #sys.stdout.flush() # Get total value of this block: reward + tx fees reward = get_reward_by_block(height) print("Reward for block {} = {}".format(height, reward)) sys.stdout.flush() # The Pools Fee the_pools_fee = reward * pool_fee block_payout_map[pool_admin_user_id] = the_pools_fee reward = reward - the_pools_fee logger.warn("Pool Fee = {}".format(block_payout_map)) # Get the "secondary_scaling" value for this block scale = get_scale_by_block(height) #print("Secondary Scaling value for block = {}".format(scale)) #sys.stdout.flush() # build a map of total shares of each size for each user shares_count_map = get_share_counts(height, window_size) # DUMMY DATA # scale = 529 # shares_count_map = { # 1: {29: 50}, # 2: {29: 25, 31: 10}, # 3: {32: 5}, # } #print("Shares Count Map:") #sys.stdout.flush() #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(shares_count_map) #sys.stdout.flush() # Calcualte total value of all shares total_value = calculate_total_share_value(shares_count_map, scale) print("total share value in payment window: {}".format(total_value)) sys.stdout.flush() # For each user with shares in the window, calculate payout and add to block_payout_map for user_id, worker_shares_count in shares_count_map.items(): #print("xxx: {} {}".format(user_id, worker_shares_count)) #sys.stdout.flush() # Calcualte the total share value from this worker total_worker_value = calculate_total_share_value( {user_id: worker_shares_count}, scale) if total_value * reward > 0: worker_payment = int(total_worker_value / total_value * reward) else: # For next block estimate, there may be no shares submitted to the pool worker_payment = 0 total_payments_this_block += worker_payment print("worker_payment: {}".format(worker_payment / 1000000000)) sys.stdout.flush() if user_id in block_payout_map.keys(): block_payout_map[user_id] += worker_payment else: block_payout_map[user_id] = worker_payment logger.warn( "Total Grin Paid Out this block: {} + the_pools_fee: {} ".format( total_payments_this_block, the_pools_fee)) print("block_payout_map = {}".format(block_payout_map)) #sys.stdout.flush() #logger.warn("calculate_map: {}".format(block_payout_map)) return block_payout_map
def get(self, id, height=None, range=None): LOGGER = lib.get_logger(PROCESS) if id != g.user.id: response = jsonify( {'message': 'Not authorized to access data for other users'}) response.status_code = 403 return response debug and LOGGER.warn("EstimateApi_payment get id:{} height:{}".format( id, height)) id_str = str(id) if height is None: # Immature Balance Estimate LOGGER.warn("Immature Balance Estimate") # Get a list of all new and unlocked blocks unlocked_blocks = Pool_blocks.get_all_unlocked() unlocked_blocks_h = [blk.height for blk in unlocked_blocks] #LOGGER.warn("EstimateApi_payment unlocked blocks: {}".format(unlocked_blocks)) new_blocks = Pool_blocks.get_all_new() new_blocks_h = [blk.height for blk in new_blocks] #LOGGER.warn("EstimateApi_payment new blocks: {}".format(new_blocks)) total = 0 for height in unlocked_blocks_h + new_blocks_h: debug and print("Estimate block at height: {}".format(height)) payout_map = pool.get_block_payout_map_estimate(height, LOGGER) if payout_map is not None and id_str in payout_map: total = total + payout_map[id_str] return {"immature": total} if type(height) == str: if height == "next": # Next block estimate debug and LOGGER.warn("Next block estimate") estimate = 0 payout_map = pool.get_block_payout_map_estimate(height, LOGGER) if payout_map is None: estimate = "TBD" elif id_str in payout_map: estimate = payout_map[id_str] else: estimate = 0 return {"next": estimate} else: response = jsonify({'message': 'Invalid Request'}) response.status_code = 400 return response # Block Reward estimate if range is None: # One specific block estimate debug and LOGGER.warn("One specific block estimate") estimate = 0 payout_map = pool.get_block_payout_map_estimate(height, LOGGER) if payout_map is not None: if id_str in payout_map.keys(): estimate = payout_map[id_str] else: estimate = 0 else: # Maybe this is a pool block but we didnt estimate it yet pb = Pool_blocks.get_by_height(height) if pb is not None: estimate = "TBD" str_height = str(height) return {str_height: estimate} # Range of pool block reward estimates debug and LOGGER.warn("Range of blocks estimate") # Enforce range limit range = min(range, pool_blocks_range_limit) # Get the list of pool block(s) heights if height == 0: blocks = Pool_blocks.get_latest(range) else: blocks = Pool_blocks.get_by_height(height, range) block_heights = [pb.height for pb in blocks] # Get estimates for each of the blocks estimates = {} for height in block_heights: estimate = 0 payout_map = pool.get_block_payout_map_estimate(height, LOGGER) if payout_map is None: estimate = "TBD" elif id_str in payout_map: estimate = payout_map[id_str] else: estimate = 0 str_height = str(height) estimates[str_height] = estimate return estimates
def calculate_block_payout_map(height, window_size, pool_fee, logger, estimate=False): block_payout_map = {} # Get the grinpool admin user ID for pool fee pool_admin_user_id = 1 # Total the payments for sanity check total_payments_this_block = 0 try: admin_user = os.environ["GRIN_POOL_ADMIN_USER"] pool_admin_user_id = Users.get_id_by_username(admin_user) logger.warn("Pool Fee goes to admin account with id={}".format(pool_admin_user_id)) except Exception as e: logger.warn("We dont have Admin account info, using default id={}: {}".format(pool_admin_user_id, e)) # Create the payout map try: if estimate == True: cached_map = get_block_payout_map_estimate(height, logger) if cached_map is not None: return cached_map # Get pool_block record and check block state print("getting the pool block: {}".format(height)) sys.stdout.flush() poolblock = Pool_blocks.get_by_height(height) if poolblock is None: return {} print("The pool block {}".format(poolblock.to_json())) sys.stdout.flush() if estimate == True: if poolblock.state != "new" and poolblock.state != "unlocked": return {} else: if poolblock.state != "unlocked": return {} # Get total value of this block: reward + tx fees reward = get_reward_by_block(height) print("Reward for block {} = {}".format(height, reward)) sys.stdout.flush() # The Pools Fee the_pools_fee = reward * pool_fee block_payout_map[pool_admin_user_id] = the_pools_fee reward = reward - the_pools_fee logger.warn("Pool Fee = {}".format(block_payout_map)) # Get the "secondary_scaling" value for this block scale = get_scale_by_block(height) print("Secondary Scaling value for block = {}".format(scale)) sys.stdout.flush() # build a map of total shares of each size for each user shares_count_map = get_share_counts(height, window_size) # DUMMY DATA # scale = 529 # shares_count_map = { # 1: {29: 50}, # 2: {29: 25, 31: 10}, # 3: {32: 5}, # } #print("Shares Count Map:") #sys.stdout.flush() #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(shares_count_map) #sys.stdout.flush() # Calcualte total value of all shares total_value = calculate_total_share_value(shares_count_map, scale) print("total share value in payment window: {}".format(total_value)) sys.stdout.flush() # For each user with shares in the window, calculate payout and add to block_payout_map for user_id, worker_shares_count in shares_count_map.items(): print("xxx: {} {}".format(user_id, worker_shares_count)) sys.stdout.flush() # Calcualte the total share value from this worker total_worker_value = calculate_total_share_value({user_id:worker_shares_count}, scale) worker_payment = total_worker_value / total_value * reward total_payments_this_block += worker_payment print("worker_payment: {}".format(worker_payment/1000000000)) sys.stdout.flush() if user_id in block_payout_map.keys(): block_payout_map[user_id] += worker_payment else: block_payout_map[user_id] = worker_payment logger.warn("Total Grin Paid Out this block: {} + the_pools_fee: {} ".format(total_payments_this_block, the_pools_fee)) print("block_payout_map = {}".format(block_payout_map)) #sys.stdout.flush() if estimate == True: payout_estimate_map_key = "payout-estimate-for-block-" + str(height) try: # Estimates are cached in redis, save it there if we can redisdb = lib.get_redis_db() #redisdb.hmset(payout_estimate_map_key, json.dumps(block_payout_map)) redisdb.set(payout_estimate_map_key, pickle.dumps(block_payout_map)) except Exception as e: logger.warn("block_payout_map cache insert failed: {} - {}".format(payout_estimate_map_key, repr(e))) except Exception as e: logger.error("Estimate went wrong: {} - {}".format(e, traceback.print_exc(e))) raise e #logger.warn("calculate_map: {}".format(block_payout_map)) return block_payout_map