class Clix: def __init__(self, creator: Callable): self._creator = creator self._queue = Queue() self._executor = ProcessPoolExecutor() self._loop = None def reform(self, mapper: Callable, predicate: Callable = notnull) -> 'Clix': self._queue.put_nowait( lambda iterable: filter_map(iterable, mapper, predicate)) return self def map(self, mapper: Callable) -> 'Clix': self._queue.put_nowait(lambda iterable: gather(*( self.__execute(mapper, i) for i in iterable))) return self def __execute(self, function: Callable, *args: Any) -> Generator: return self._loop.run_in_executor(self._executor, function, *args) def flatten(self, flattener: Callable = (lambda v: v)) -> 'Clix': self._queue.put_nowait( lambda iterable: self.__flatten(iterable, flattener)) return self @staticmethod async def __flatten(iterable: Iterable, flattener: Callable) -> Generator: return (i for si in iterable for i in flattener(si)) def distinct(self, keymaker: Callable) -> 'Clix': self._queue.put_nowait( lambda iterable: self.__distinct(iterable, keymaker)) return self @staticmethod async def __distinct(iterable: Iterable, keymaker: Callable) -> ValuesView: return {keymaker(i): i for i in iterable}.values() def sieve(self, mapper: Callable, predicate: Callable = notnull) -> 'Clix': return self.reform(lambda i: self.__execute(mapper, i), predicate) async def apply(self, applier: Callable) -> Iterable: self._loop = get_event_loop() iterable = await self._creator() while not self._queue.empty(): function = await self._queue.get() iterable = await function(iterable) iterable = await gather(*(map(applier, iterable))) self._executor.shutdown() return iterable async def list(self) -> List[Any]: iterable = await self.apply(self.__skip) return list(iterable) @staticmethod async def __skip(value: Any) -> Any: return value
class PendantFeaturesService: @inject def __init__(self, default_params_factory: PendantFeaturesParamsFactory) -> None: self._executor = ProcessPoolExecutor(max_workers=1) self._default_params_factory = default_params_factory def extract( self, image: np.ndarray, params: Optional[PendantFeaturesParams] = None, *, labels: bool = False, ) -> asyncio.Future: if params is None: params = self._default_params_factory.create() cfut = self._executor.submit( extract_pendant_features, image, params.drop_region, params.needle_region, thresh1=params.thresh1, thresh2=params.thresh2, labels=labels, ) fut = asyncio.wrap_future(cfut, loop=asyncio.get_event_loop()) return fut def destroy(self) -> None: self._executor.shutdown()
async def main(db_path, max_query_time): args = dict(initializer=initializer, initargs=(log, db_path, MainNetLedger, 0.25)) workers = max(os.cpu_count(), 4) log.info(f"using {workers} reader processes") query_executor = ProcessPoolExecutor(workers, **args) tasks = [search(query_executor, constraints) for constraints in get_args()] try: results = await asyncio.gather(*tasks) query_times = [{ 'sql': interpolate(*_get_claims( """ claimtrie.claim_hash as is_controlling, claimtrie.last_take_over_height, claim.claim_hash, claim.txo_hash, claim.claims_in_channel, claim.height, claim.creation_height, claim.activation_height, claim.expiration_height, claim.effective_amount, claim.support_amount, claim.trending_group, claim.trending_mixed, claim.trending_local, claim.trending_global, claim.short_url, claim.canonical_url, claim.channel_hash, channel.txo_hash AS channel_txo_hash, channel.height AS channel_height, claim.signature_valid """, **constraints)), 'duration': ts, 'error': error } for ts, constraints, error in results] errored = [ query_info for query_info in query_times if query_info['error'] ] errors = {str(query_info['error']): [] for query_info in errored} for error in errored: errors[str(error['error'])].append(error['sql']) slow = [ query_info for query_info in query_times if not query_info['error'] and query_info['duration'] > (max_query_time / 2.0) ] fast = [ query_info for query_info in query_times if not query_info['error'] and query_info['duration'] <= (max_query_time / 2.0) ] print(f"-- {len(fast)} queries were fast") slow.sort(key=lambda query_info: query_info['duration'], reverse=True) print(f"-- Failing queries:") for error in errors: print(f"-- Failure: \"{error}\"") for failing_query in errors[error]: print(f"{textwrap.dedent(failing_query)};\n") print() print(f"-- Slow queries:") for slow_query in slow: print( f"-- Query took {slow_query['duration']}\n{textwrap.dedent(slow_query['sql'])};\n" ) finally: query_executor.shutdown()
class ConanFeaturesService: @inject def __init__(self, default_params_factory: ConanParamsFactory) -> None: self._executor = ProcessPoolExecutor(max_workers=1) self._default_params_factory = default_params_factory def extract(self, image: np.ndarray, params: Optional[ConanFeaturesParams] = None, *, labels: bool = False) -> asyncio.Future: params = params or self._default_params_factory.create() params_dict = { 'baseline': params.baseline, 'inverted': params.inverted, 'thresh': params.thresh, 'roi': params.roi, 'labels': labels, } cfut = self._executor.submit(extract_contact_angle_features, image, **params_dict) fut = asyncio.wrap_future(cfut, loop=asyncio.get_event_loop()) return fut def destroy(self) -> None: self._executor.shutdown()
def main(): pool = ProcessPoolExecutor(max_workers=int(multiprocessing.cpu_count() * 0.5)) # pool = ProcessPoolExecutor(max_workers=1) pages_2 = [{ 'id': "p1", 'type': 'STACK', 'constraint': None }, { 'id': "p2", 'type': 'STACK', 'constraint': None }] pages_3 = [{ 'id': "p1", 'type': 'STACK', 'constraint': None }, { 'id': "p2", 'type': 'STACK', 'constraint': None }, { 'id': "p3", 'type': 'STACK', 'constraint': None }] base_constraints = [ { "type": "EDGES_TO_SUB_ARC_ON_PAGES", "arguments": ["0", "1"], # the outer terminals "modifier": ["p1", "p2"] # the pages }, # inner terminals are after one outer terminal and before the other { "type": "NODES_PREDECESSOR", "arguments": ["0"], "modifier": ["2", "3"], }, { "type": "NODES_PREDECESSOR", "arguments": ["2", "3"], "modifier": ["1"], } ] set_printing(False) onlyfiles = [ os.path.join('500-random-planar-3-trees', f) for f in listdir(path='500-random-planar-3-trees') if isfile(os.path.join('500-random-planar-3-trees', f)) ] for file in onlyfiles: with open(file, mode="r") as f: graph_str = f.read() future = pool.submit(do_experiment, base_constraints, pages_2, pages_3, graph_str) future.add_done_callback(callback) pool.shutdown(wait=True)
def main(): pool = ProcessPoolExecutor(max_workers=int(multiprocessing.cpu_count() - 2)) # pool = ProcessPoolExecutor(max_workers=1) pages = [{ 'id': "p1", 'type': 'STACK', 'constraint': None }, { 'id': "p2", 'type': 'STACK', 'constraint': None }, { 'id': "p3", 'type': 'STACK', 'constraint': None }] base_constraints = [ { "type": "EDGES_TO_SUB_ARC_ON_PAGES", "arguments": ["0", "1"], # the outer terminals "modifier": ["p1", "p2"] # the pages }, # inner terminals are after one outer terminal and before the other { "type": "NODES_PREDECESSOR", "arguments": ["0"], "modifier": ["2", "3"], }, { "type": "NODES_PREDECESSOR", "arguments": ["2", "3"], "modifier": ["1"], } ] set_printing(False) experiments = [ # (graph_generation.random_planar_gh, 300, [15, 10]), (graph_generation.random_planar, 1000, [110]), # (graph_generation.spine_graph, 1, list(range(10, 350, 1))) ] with open("results_random_planar_110.json", mode="a") as f: def callback(my_future: Future): if not my_future.done() or my_future.cancelled(): return result: ExResult = my_future.result() print(simplejson.dumps(result), file=f) for graph_gen, number_of_runs, num_node_list in experiments: for num_nodes in num_node_list: for i in range(number_of_runs): future = pool.submit(do_experiment, base_constraints, graph_gen, i, num_nodes, pages) future.add_done_callback(callback) pool.shutdown(wait=True)
def mat_vec(A: List[List[int]], x: List[int]) -> List[int]: N = len(A) y = [0] * N f = partial(calc, A=A, x=x, y=y) pool = ProcessPoolExecutor(max_workers=2) pool.map(f, [i for i in range(N)]) pool.shutdown(wait=True) return y
class DelayedFileList: def __init__(self, filename): self.__loader = ProcessPoolExecutor(4) self.__filehandle = open( filename, "r", encoding="iso-8859-1" ) # :type self.__filehandle: typing.TextIO self.__lines = 0 self.__thousand_offsets = [0] line = self.__filehandle.readline() while line: if line.strip(): self.__lines += 1 if self.__lines % 1000 == 0: self.__thousand_offsets.append( self.__filehandle.tell()) line = self.__filehandle.readline() self.__filehandle.seek(0) def __len__(self): return self.__lines def __getitem__(self, i): if i < 0 or i >= len(self): raise IndexError("Out of bounds") thousand_offset = self.__thousand_offsets[i // 1000] remainder = i % 1000 self.__filehandle.seek(thousand_offset) while remainder > 0: self.__filehandle.readline() remainder -= 1 name, url = [ x.strip() for x in self.__filehandle.readline().strip().split("\t") ] class_name = name.split("_")[0] pre_image = Image(name, class_name, url, None, None) submitted_task = self.__loader.submit(load_image, pre_image.url) def deferred_load(): return submitted_task.result() return Image(name, class_name, url, load_annotation_for_image(pre_image), deferred_load) def close(self): self.__loader.shutdown() self.__filehandle.close()
class SnakeGameExecutor(object): def __init__(self, args): self.hpv = args.host, args.port, args.venue self.executor = ProcessPoolExecutor(max_workers=(os.cpu_count())) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.executor.shutdown(wait=True) return False def run_batch(self, batch): params = [(*self.hpv, snake) for snake in batch] return self.executor.map(run_simulation, params)
class Pools: _instance = None def __init__(self): self.threaded = ThreadPoolExecutor() self.process = ProcessPoolExecutor() @staticmethod def get(): if not Pools._instance: Pools._instance = Pools() return Pools._instance def shutdown(self): self.threaded.shutdown() self.process.shutdown()
async def main(db_path, max_query_time): args = dict(initializer=initializer, initargs=(log, db_path, MainNetLedger, 0.25)) workers = max(os.cpu_count(), 4) log.info(f"using {workers} reader processes") query_executor = ProcessPoolExecutor(workers, **args) tasks = [search(query_executor, constraints) for constraints in get_args()] try: results = await asyncio.gather(*tasks) times = {msg: ts for ts, msg in results} log.info("\n".join( sorted(filter(lambda msg: times[msg] > max_query_time, times.keys()), key=lambda msg: times[msg]))) finally: query_executor.shutdown()
class ProcessExecutor(Executor): slug = 'executor:process' name = "Executor: Process" awaiter_dict = { 'as_completed': as_completed, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.executor = ProcessPoolExecutor(max_workers=self.workers) def submit(self, fn: Callable, *args, **kwargs): return self.executor.submit(fn, *args, **kwargs) def shutdown(self, wait=True): self.executor.shutdown(wait)
def get_linkpred_scores(lp_data, weighted, predictor_indices=None, include_train=False, parallel_version=False): predictor_indices = predictor_indices or range(len(all_predictors)) predictors = [all_predictors[i] for i in predictor_indices] predictor_names = [all_predictor_names[i] for i in predictor_indices] A_train = lp_data['A_train'] A_test = lp_data['A_test'] A_test_pos = lp_data['A_test_pos'] A_test_neg = lp_data['A_test_neg'] G_train = nx.from_scipy_sparse_matrix(A_train) if include_train: pairs = list(itertools.combinations(range(A_train.shape[0]), 2)) else: test_pairs = list(zip(*triu(A_test_pos + A_test_neg).nonzero())) pairs = test_pairs if not include_train else test_pairs + list( zip(*triu(A_train).nonzero())) scores = {} if not parallel_version: for i, predictor in tqdm(enumerate(predictors), 'Predictor: '): predictor_name = predictor_names[i] abbr, lp_scores = perform_one_lp(predictor_name, predictor, G_train, pairs, weighted) scores[abbr] = lp_scores else: num_predictors = len(predictors) max_workers = min(num_predictors, multiprocessing.cpu_count()) pool = ProcessPoolExecutor(max_workers=max_workers) process_list = [] for i, predictor in enumerate(predictors): predictor_name = predictor_names[i] process_list.append( pool.submit(perform_one_lp, predictor_name, predictor, G_train, pairs, weighted)) print('{} of {} processes scheduled ({})'.format( len(process_list), num_predictors, predictor_name)) for p in as_completed(process_list): abbr, lp_scores = p.result() scores[abbr] = lp_scores print('{} of {} processes completed'.format( len(scores), len(process_list))) pool.shutdown(wait=True) scores_df = pd.DataFrame(scores) return scores_df
def lyricSpider(user_id): print("======= 开始爬 歌词 信息 ===========") startTime = datetime.datetime.now() print(startTime.strftime('%Y-%m-%d %H:%M:%S')) # 所有歌手数量 try: musics_num = sql.get_music_num(user_id) except: print("用户未开启权限,程序结束") sys.exit(0) print("musics :", len(musics_num), "start") batch = math.ceil(musics_num.get('num') / 34.0) pool = ProcessPoolExecutor(3) for index in range(0, batch): pool.submit(saveLyricBatch, user_id, index) pool.shutdown(wait=True) print("======= 结束爬 歌词 信息 ===========") endTime = datetime.datetime.now() print(endTime.strftime('%Y-%m-%d %H:%M:%S')) print("耗时:", (endTime - startTime).seconds, "秒")
def main(): pool = ProcessPoolExecutor(max_workers=int(multiprocessing.cpu_count() * 0.25)) pages = [{ 'id': "p1", 'type': 'STACK', 'constraint': None }, { 'id': "p2", 'type': 'STACK', 'constraint': None }] base_constraints = [ { "type": "EDGES_TO_SUB_ARC_ON_PAGES", "arguments": ["0", "1"], # the outer terminals "modifier": ["p1", "p2"] # the pages }, # inner terminals are after one outer terminal and before the other { "type": "NODES_PREDECESSOR", "arguments": ["0"], "modifier": ["2", "3"], }, { "type": "NODES_PREDECESSOR", "arguments": ["2", "3"], "modifier": ["1"], } ] set_printing(False) with open("results_random_planar_110.json", mode="r") as f: for line in f: future = pool.submit(do_experiment, base_constraints, pages, line) future.add_done_callback(callback) pool.shutdown(wait=True)
def thead_collect(): results = MONGO.select('albums', {'collected': {'$ne': 1}}, limit=200) # thead_pool = ThreadPoolExecutor(5) thead_pool = ProcessPoolExecutor(5) while results: for result in results: baby = CollectBaby(result) # magic() thead_pool.submit(baby.collect) # baby.collect() results = MONGO.select('albums', { '_id': { '$gt': result.get('_id') }, 'collected': { '$ne': 1 } }, limit=200) thead_pool.shutdown(wait=True)
async def test_endpoint(): print(f"main process: {os.getpid()}") START_TIME = time.time() STOP_TIME = START_TIME + 2 pool = ProcessPoolExecutor(max_workers=3) futures = [ pool.submit(simple_routine, [1]), pool.submit(simple_routine, [1]), pool.submit(simple_routine, [10]), ] results = [] for fut in futures: remains = max(STOP_TIME - time.time(), 0) try: results.append(fut.get(timeout = remains)) except: results.append("not done") # terminate the entire pool pool.shutdown(wait=False) print("exiting at: ", int(time.time() - START_TIME)) return "True"
class Blockchain(BlockchainInterface): constants: ConsensusConstants constants_json: Dict # peak of the blockchain _peak_height: Optional[uint32] # All blocks in peak path are guaranteed to be included, can include orphan blocks __block_records: Dict[bytes32, BlockRecord] # all hashes of blocks in block_record by height, used for garbage collection __heights_in_cache: Dict[uint32, Set[bytes32]] # Defines the path from genesis to the peak, no orphan blocks __height_to_hash: Dict[uint32, bytes32] # All sub-epoch summaries that have been included in the blockchain from the beginning until and including the peak # (height_included, SubEpochSummary). Note: ONLY for the blocks in the path to the peak __sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {} # Unspent Store coin_store: CoinStore # Store block_store: BlockStore # Used to verify blocks in parallel pool: ProcessPoolExecutor # Set holding seen compact proofs, in order to avoid duplicates. _seen_compact_proofs: Set[Tuple[VDFInfo, uint32]] # Whether blockchain is shut down or not _shut_down: bool # Lock to prevent simultaneous reads and writes lock: asyncio.Lock @staticmethod async def create( coin_store: CoinStore, block_store: BlockStore, consensus_constants: ConsensusConstants, ): """ Initializes a blockchain with the BlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config. """ self = Blockchain() self.lock = asyncio.Lock() # External lock handled by full node cpu_count = multiprocessing.cpu_count() if cpu_count > 61: cpu_count = 61 # Windows Server 2016 has an issue https://bugs.python.org/issue26903 num_workers = max(cpu_count - 2, 1) self.pool = ProcessPoolExecutor(max_workers=num_workers) log.info(f"Started {num_workers} processes for block validation") self.constants = consensus_constants self.coin_store = coin_store self.block_store = block_store self.constants_json = recurse_jsonify(dataclasses.asdict(self.constants)) self._shut_down = False await self._load_chain_from_store() self._seen_compact_proofs = set() return self def shut_down(self): self._shut_down = True self.pool.shutdown(wait=True) async def _load_chain_from_store(self) -> None: """ Initializes the state of the Blockchain class from the database. """ height_to_hash, sub_epoch_summaries = await self.block_store.get_peak_height_dicts() self.__height_to_hash = height_to_hash self.__sub_epoch_summaries = sub_epoch_summaries self.__block_records = {} self.__heights_in_cache = {} block_records, peak = await self.block_store.get_block_records_close_to_peak(self.constants.BLOCKS_CACHE_SIZE) for block in block_records.values(): self.add_block_record(block) if len(block_records) == 0: assert peak is None self._peak_height = None return assert peak is not None self._peak_height = self.block_record(peak).height assert len(self.__height_to_hash) == self._peak_height + 1 def get_peak(self) -> Optional[BlockRecord]: """ Return the peak of the blockchain """ if self._peak_height is None: return None return self.height_to_block_record(self._peak_height) async def get_full_peak(self) -> Optional[FullBlock]: if self._peak_height is None: return None """ Return list of FullBlocks that are peaks""" block = await self.block_store.get_full_block(self.height_to_hash(self._peak_height)) assert block is not None return block async def get_full_block(self, header_hash: bytes32) -> Optional[FullBlock]: return await self.block_store.get_full_block(header_hash) async def receive_block( self, block: FullBlock, pre_validation_result: Optional[PreValidationResult] = None, fork_point_with_peak: Optional[uint32] = None, summaries_to_check: List[SubEpochSummary] = None, # passed only on long sync ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32]]: """ This method must be called under the blockchain lock Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case of a new peak. """ genesis: bool = block.height == 0 if self.contains_block(block.header_hash): return ReceiveBlockResult.ALREADY_HAVE_BLOCK, None, None if not self.contains_block(block.prev_header_hash) and not genesis: return ( ReceiveBlockResult.DISCONNECTED_BLOCK, Err.INVALID_PREV_BLOCK_HASH, None, ) if not genesis and (self.block_record(block.prev_header_hash).height + 1) != block.height: return ReceiveBlockResult.INVALID_BLOCK, Err.INVALID_HEIGHT, None npc_result: Optional[NPCResult] = None if pre_validation_result is None: if block.height == 0: prev_b: Optional[BlockRecord] = None else: prev_b = self.block_record(block.prev_header_hash) sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(block.finished_sub_slots) > 0, prev_b, self ) if block.is_transaction_block(): if block.transactions_generator is not None: try: block_generator: Optional[BlockGenerator] = await self.get_block_generator(block) except ValueError: return ReceiveBlockResult.INVALID_BLOCK, Err.GENERATOR_REF_HAS_NO_GENERATOR, None assert block_generator is not None and block.transactions_info is not None npc_result = get_name_puzzle_conditions( block_generator, min(self.constants.MAX_BLOCK_COST_CLVM, block.transactions_info.cost), False ) removals, tx_additions = tx_removals_and_additions(npc_result.npc_list) else: removals, tx_additions = [], [] header_block = get_block_header(block, tx_additions, removals) else: npc_result = None header_block = get_block_header(block, [], []) required_iters, error = validate_finished_header_block( self.constants, self, header_block, False, difficulty, sub_slot_iters, ) if error is not None: return ReceiveBlockResult.INVALID_BLOCK, error.code, None else: npc_result = pre_validation_result.npc_result required_iters = pre_validation_result.required_iters assert pre_validation_result.error is None assert required_iters is not None error_code, _ = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, block.height, npc_result, fork_point_with_peak, self.get_block_generator, ) if error_code is not None: return ReceiveBlockResult.INVALID_BLOCK, error_code, None block_record = block_to_block_record( self.constants, self, required_iters, block, None, ) # Always add the block to the database async with self.block_store.db_wrapper.lock: try: # Perform the DB operations to update the state, and rollback if something goes wrong await self.block_store.db_wrapper.begin_transaction() await self.block_store.add_full_block(block, block_record) fork_height, peak_height, records = await self._reconsider_peak( block_record, genesis, fork_point_with_peak, npc_result ) await self.block_store.db_wrapper.commit_transaction() # Then update the memory cache. It is important that this task is not cancelled and does not throw self.add_block_record(block_record) for fetched_block_record in records: self.__height_to_hash[fetched_block_record.height] = fetched_block_record.header_hash if fetched_block_record.sub_epoch_summary_included is not None: self.__sub_epoch_summaries[ fetched_block_record.height ] = fetched_block_record.sub_epoch_summary_included if peak_height is not None: self._peak_height = peak_height self.block_store.cache_block(block) except BaseException: await self.block_store.db_wrapper.rollback_transaction() raise if fork_height is not None: return ReceiveBlockResult.NEW_PEAK, None, fork_height else: return ReceiveBlockResult.ADDED_AS_ORPHAN, None, None async def _reconsider_peak( self, block_record: BlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32], npc_result: Optional[NPCResult], ) -> Tuple[Optional[uint32], Optional[uint32], List[BlockRecord]]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there was no update to the heaviest chain. """ peak = self.get_peak() if genesis: if peak is None: block: Optional[FullBlock] = await self.block_store.get_full_block(block_record.header_hash) assert block is not None if npc_result is not None: tx_removals, tx_additions = tx_removals_and_additions(npc_result.npc_list) else: tx_removals, tx_additions = [], [] await self.coin_store.new_block(block, tx_additions, tx_removals) await self.block_store.set_peak(block.header_hash) return uint32(0), uint32(0), [block_record] return None, None, [] assert peak is not None if block_record.weight > peak.weight: # Find the fork. if the block is just being appended, it will return the peak # If no blocks in common, returns -1, and reverts all blocks if block_record.prev_hash == peak.header_hash: fork_height: int = peak.height elif fork_point_with_peak is not None: fork_height = fork_point_with_peak else: fork_height = find_fork_point_in_chain(self, block_record, peak) if block_record.prev_hash != peak.header_hash: await self.coin_store.rollback_to_block(fork_height) # Rollback sub_epoch_summaries heights_to_delete = [] for ses_included_height in self.__sub_epoch_summaries.keys(): if ses_included_height > fork_height: heights_to_delete.append(ses_included_height) for height in heights_to_delete: log.info(f"delete ses at height {height}") del self.__sub_epoch_summaries[height] # Collect all blocks from fork point to new peak blocks_to_add: List[Tuple[FullBlock, BlockRecord]] = [] curr = block_record.header_hash while fork_height < 0 or curr != self.height_to_hash(uint32(fork_height)): fetched_full_block: Optional[FullBlock] = await self.block_store.get_full_block(curr) fetched_block_record: Optional[BlockRecord] = await self.block_store.get_block_record(curr) assert fetched_full_block is not None assert fetched_block_record is not None blocks_to_add.append((fetched_full_block, fetched_block_record)) if fetched_full_block.height == 0: # Doing a full reorg, starting at height 0 break curr = fetched_block_record.prev_hash records_to_add = [] for fetched_full_block, fetched_block_record in reversed(blocks_to_add): records_to_add.append(fetched_block_record) if fetched_block_record.is_transaction_block: if fetched_block_record.header_hash == block_record.header_hash: tx_removals, tx_additions = await self.get_tx_removals_and_additions( fetched_full_block, npc_result ) else: tx_removals, tx_additions = await self.get_tx_removals_and_additions(fetched_full_block, None) await self.coin_store.new_block(fetched_full_block, tx_additions, tx_removals) # Changes the peak to be the new peak await self.block_store.set_peak(block_record.header_hash) return uint32(max(fork_height, 0)), block_record.height, records_to_add # This is not a heavier block than the heaviest we have seen, so we don't change the coin set return None, None, [] async def get_tx_removals_and_additions( self, block: FullBlock, npc_result: Optional[NPCResult] = None ) -> Tuple[List[bytes32], List[Coin]]: if block.is_transaction_block(): if block.transactions_generator is not None: if npc_result is None: block_generator: Optional[BlockGenerator] = await self.get_block_generator(block) assert block_generator is not None npc_result = get_name_puzzle_conditions(block_generator, self.constants.MAX_BLOCK_COST_CLVM, False) tx_removals, tx_additions = tx_removals_and_additions(npc_result.npc_list) return tx_removals, tx_additions else: return [], [] else: return [], [] def get_next_difficulty(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.DIFFICULTY_STARTING return get_next_sub_slot_iters_and_difficulty(self.constants, new_slot, curr, self)[1] def get_next_slot_iters(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.SUB_SLOT_ITERS_STARTING return get_next_sub_slot_iters_and_difficulty(self.constants, new_slot, curr, self)[0] async def get_sp_and_ip_sub_slots( self, header_hash: bytes32 ) -> Optional[Tuple[Optional[EndOfSubSlotBundle], Optional[EndOfSubSlotBundle]]]: block: Optional[FullBlock] = await self.block_store.get_full_block(header_hash) if block is None: return None curr_br: BlockRecord = self.block_record(block.header_hash) is_overflow = curr_br.overflow curr: Optional[FullBlock] = block assert curr is not None while True: if curr_br.first_in_sub_slot: curr = await self.block_store.get_full_block(curr_br.header_hash) assert curr is not None break if curr_br.height == 0: break curr_br = self.block_record(curr_br.prev_hash) if len(curr.finished_sub_slots) == 0: # This means we got to genesis and still no sub-slots return None, None ip_sub_slot = curr.finished_sub_slots[-1] if not is_overflow: # Pos sub-slot is the same as infusion sub slot return None, ip_sub_slot if len(curr.finished_sub_slots) > 1: # Have both sub-slots return curr.finished_sub_slots[-2], ip_sub_slot prev_curr: Optional[FullBlock] = await self.block_store.get_full_block(curr.prev_header_hash) if prev_curr is None: assert curr.height == 0 prev_curr = curr prev_curr_br = self.block_record(curr.header_hash) else: prev_curr_br = self.block_record(curr.prev_header_hash) assert prev_curr_br is not None while prev_curr_br.height > 0: if prev_curr_br.first_in_sub_slot: prev_curr = await self.block_store.get_full_block(prev_curr_br.header_hash) assert prev_curr is not None break prev_curr_br = self.block_record(prev_curr_br.prev_hash) if len(prev_curr.finished_sub_slots) == 0: return None, ip_sub_slot return prev_curr.finished_sub_slots[-1], ip_sub_slot def get_recent_reward_challenges(self) -> List[Tuple[bytes32, uint128]]: peak = self.get_peak() if peak is None: return [] recent_rc: List[Tuple[bytes32, uint128]] = [] curr: Optional[BlockRecord] = peak while curr is not None and len(recent_rc) < 2 * self.constants.MAX_SUB_SLOT_BLOCKS: if curr != peak: recent_rc.append((curr.reward_infusion_new_challenge, curr.total_iters)) if curr.first_in_sub_slot: assert curr.finished_reward_slot_hashes is not None sub_slot_total_iters = curr.ip_sub_slot_total_iters(self.constants) # Start from the most recent for rc in reversed(curr.finished_reward_slot_hashes): recent_rc.append((rc, sub_slot_total_iters)) sub_slot_total_iters = uint128(sub_slot_total_iters - curr.sub_slot_iters) curr = self.try_block_record(curr.prev_hash) return list(reversed(recent_rc)) async def validate_unfinished_block( self, block: UnfinishedBlock, skip_overflow_ss_validation=True ) -> PreValidationResult: if ( not self.contains_block(block.prev_header_hash) and not block.prev_header_hash == self.constants.GENESIS_CHALLENGE ): return PreValidationResult(uint16(Err.INVALID_PREV_BLOCK_HASH.value), None, None) unfinished_header_block = UnfinishedHeaderBlock( block.finished_sub_slots, block.reward_chain_block, block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage, block.foliage_transaction_block, b"", ) prev_b = self.try_block_record(unfinished_header_block.prev_header_hash) sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(unfinished_header_block.finished_sub_slots) > 0, prev_b, self ) required_iters, error = validate_unfinished_header_block( self.constants, self, unfinished_header_block, False, difficulty, sub_slot_iters, skip_overflow_ss_validation, ) if error is not None: return PreValidationResult(uint16(error.code.value), None, None) prev_height = ( -1 if block.prev_header_hash == self.constants.GENESIS_CHALLENGE else self.block_record(block.prev_header_hash).height ) npc_result = None if block.transactions_generator is not None: assert block.transactions_info is not None try: block_generator: Optional[BlockGenerator] = await self.get_block_generator(block) except ValueError: return PreValidationResult(uint16(Err.GENERATOR_REF_HAS_NO_GENERATOR.value), None, None) if block_generator is None: return PreValidationResult(uint16(Err.GENERATOR_REF_HAS_NO_GENERATOR.value), None, None) npc_result = get_name_puzzle_conditions( block_generator, min(self.constants.MAX_BLOCK_COST_CLVM, block.transactions_info.cost), False ) error_code, cost_result = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, uint32(prev_height + 1), npc_result, None, self.get_block_generator, ) if error_code is not None: return PreValidationResult(uint16(error_code.value), None, None) return PreValidationResult(None, required_iters, cost_result) async def pre_validate_blocks_multiprocessing( self, blocks: List[FullBlock], npc_results: Dict[uint32, NPCResult], batch_size: int = 4 ) -> Optional[List[PreValidationResult]]: return await pre_validate_blocks_multiprocessing( self.constants, self.constants_json, self, blocks, self.pool, True, npc_results, self.get_block_generator, batch_size, ) def contains_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory. """ return header_hash in self.__block_records def block_record(self, header_hash: bytes32) -> BlockRecord: return self.__block_records[header_hash] def height_to_block_record(self, height: uint32) -> BlockRecord: header_hash = self.height_to_hash(height) return self.block_record(header_hash) def get_ses_heights(self) -> List[uint32]: return sorted(self.__sub_epoch_summaries.keys()) def get_ses(self, height: uint32) -> SubEpochSummary: return self.__sub_epoch_summaries[height] def height_to_hash(self, height: uint32) -> Optional[bytes32]: return self.__height_to_hash[height] def contains_height(self, height: uint32) -> bool: return height in self.__height_to_hash def get_peak_height(self) -> Optional[uint32]: return self._peak_height async def warmup(self, fork_point: uint32): """ Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last block height to load in the cache """ if self._peak_height is None: return block_records = await self.block_store.get_block_records_in_range( max(fork_point - self.constants.BLOCKS_CACHE_SIZE, uint32(0)), fork_point ) for block_record in block_records.values(): self.add_block_record(block_record) def clean_block_record(self, height: int): """ Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) while blocks_to_remove is not None and height >= 0: for header_hash in blocks_to_remove: del self.__block_records[header_hash] # remove from blocks del self.__heights_in_cache[uint32(height)] # remove height from heights in cache height = height - 1 blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) def clean_block_records(self): """ Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__block_records) < self.constants.BLOCKS_CACHE_SIZE: return peak = self.get_peak() assert peak is not None if peak.height - self.constants.BLOCKS_CACHE_SIZE < 0: return self.clean_block_record(peak.height - self.constants.BLOCKS_CACHE_SIZE) async def get_block_records_in_range(self, start: int, stop: int) -> Dict[bytes32, BlockRecord]: return await self.block_store.get_block_records_in_range(start, stop) async def get_header_blocks_in_range(self, start: int, stop: int) -> Dict[bytes32, HeaderBlock]: hashes = [] for height in range(start, stop + 1): if self.contains_height(uint32(height)): header_hash: bytes32 = self.height_to_hash(uint32(height)) hashes.append(header_hash) blocks: List[FullBlock] = await self.block_store.get_blocks_by_hash(hashes) header_blocks: Dict[bytes32, HeaderBlock] = {} for block in blocks: if self.height_to_hash(block.height) != block.header_hash: raise ValueError(f"Block at {block.header_hash} is no longer in the blockchain (it's in a fork)") tx_additions: List[CoinRecord] = [ c for c in (await self.coin_store.get_coins_added_at_height(block.height)) if not c.coinbase ] removed: List[CoinRecord] = await self.coin_store.get_coins_removed_at_height(block.height) header = get_block_header( block, [record.coin for record in tx_additions], [record.coin.name() for record in removed] ) header_blocks[header.header_hash] = header return header_blocks async def get_header_block_by_height(self, height: int, header_hash: bytes32) -> Optional[HeaderBlock]: header_dict: Dict[bytes32, HeaderBlock] = await self.get_header_blocks_in_range(height, height) if len(header_dict) == 0: return None if header_hash not in header_dict: return None return header_dict[header_hash] async def get_block_records_at(self, heights: List[uint32]) -> List[BlockRecord]: """ gets block records by height (only blocks that are part of the chain) """ hashes = [] for height in heights: hashes.append(self.height_to_hash(height)) return await self.block_store.get_block_records_by_hash(hashes) async def get_block_record_from_db(self, header_hash: bytes32) -> Optional[BlockRecord]: if header_hash in self.__block_records: return self.__block_records[header_hash] return await self.block_store.get_block_record(header_hash) def remove_block_record(self, header_hash: bytes32): sbr = self.block_record(header_hash) del self.__block_records[header_hash] self.__heights_in_cache[sbr.height].remove(header_hash) def add_block_record(self, block_record: BlockRecord): """ Adds a block record to the cache. """ self.__block_records[block_record.header_hash] = block_record if block_record.height not in self.__heights_in_cache.keys(): self.__heights_in_cache[block_record.height] = set() self.__heights_in_cache[block_record.height].add(block_record.header_hash) async def persist_sub_epoch_challenge_segments( self, ses_block_hash: bytes32, segments: List[SubEpochChallengeSegment] ): return await self.block_store.persist_sub_epoch_challenge_segments(ses_block_hash, segments) async def get_sub_epoch_challenge_segments( self, ses_block_hash: bytes32, ) -> Optional[List[SubEpochChallengeSegment]]: segments: Optional[List[SubEpochChallengeSegment]] = await self.block_store.get_sub_epoch_challenge_segments( ses_block_hash ) if segments is None: return None return segments # Returns 'True' if the info is already in the set, otherwise returns 'False' and stores it. def seen_compact_proofs(self, vdf_info: VDFInfo, height: uint32) -> bool: pot_tuple = (vdf_info, height) if pot_tuple in self._seen_compact_proofs: return True # Periodically cleanup to keep size small. TODO: make this smarter, like FIFO. if len(self._seen_compact_proofs) > 10000: self._seen_compact_proofs.clear() self._seen_compact_proofs.add(pot_tuple) return False async def get_block_generator( self, block: Union[FullBlock, UnfinishedBlock], additional_blocks=None ) -> Optional[BlockGenerator]: if additional_blocks is None: additional_blocks = {} ref_list = block.transactions_generator_ref_list if block.transactions_generator is None: assert len(ref_list) == 0 return None if len(ref_list) == 0: return BlockGenerator(block.transactions_generator, []) result: List[GeneratorArg] = [] previous_block_hash = block.prev_header_hash if ( self.try_block_record(previous_block_hash) and self.height_to_hash(self.block_record(previous_block_hash).height) == previous_block_hash ): # We are not in a reorg, no need to look up alternate header hashes (we can get them from height_to_hash) for ref_height in block.transactions_generator_ref_list: header_hash = self.height_to_hash(ref_height) ref_block = await self.get_full_block(header_hash) assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(GeneratorArg(ref_block.height, ref_block.transactions_generator)) else: # First tries to find the blocks in additional_blocks reorg_chain: Dict[uint32, FullBlock] = {} curr: Union[FullBlock, UnfinishedBlock] = block additional_height_dict = {} while curr.prev_header_hash in additional_blocks: prev: FullBlock = additional_blocks[curr.prev_header_hash] additional_height_dict[prev.height] = prev if isinstance(curr, FullBlock): assert curr.height == prev.height + 1 reorg_chain[prev.height] = prev curr = prev peak: Optional[BlockRecord] = self.get_peak() if self.contains_block(curr.prev_header_hash) and peak is not None: # Then we look up blocks up to fork point one at a time, backtracking previous_block_hash = curr.prev_header_hash prev_block_record = await self.block_store.get_block_record(previous_block_hash) prev_block = await self.block_store.get_full_block(previous_block_hash) assert prev_block is not None assert prev_block_record is not None fork = find_fork_point_in_chain(self, peak, prev_block_record) curr_2: Optional[FullBlock] = prev_block assert curr_2 is not None and isinstance(curr_2, FullBlock) reorg_chain[curr_2.height] = curr_2 while curr_2.height > fork and curr_2.height > 0: curr_2 = await self.block_store.get_full_block(curr_2.prev_header_hash) assert curr_2 is not None reorg_chain[curr_2.height] = curr_2 for ref_height in block.transactions_generator_ref_list: if ref_height in reorg_chain: ref_block = reorg_chain[ref_height] assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(GeneratorArg(ref_block.height, ref_block.transactions_generator)) else: if ref_height in additional_height_dict: ref_block = additional_height_dict[ref_height] else: header_hash = self.height_to_hash(ref_height) ref_block = await self.get_full_block(header_hash) assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(GeneratorArg(ref_block.height, ref_block.transactions_generator)) assert len(result) == len(ref_list) return BlockGenerator(block.transactions_generator, result)
class BackgroundResourceProbe(AbstractProbe): """ Background probe: cpu, memory, heap and JMX metrics TODO Refactor this """ jmx = None executor = None futures = {} interrupt = False def __init__(self, probe_config): super().__init__(probe_config) self.jmx = None def validate_config(self): pass def start(self): """ Start background probe (Separate process created) """ super().start() # create result for current version self.results[self.version] = {} # remove previous lock file if os.path.isfile('lock'): os.remove('lock') # create lock file with open('lock', 'w') as f: pass # Create PoolExecutor and submit bs_probe in it # Can be launched in debug mode - with local ThreadPool. In default separate process will be launched. # # Using in default mode (with ProcessPoolExecutor): # Only default types can be passed into submit() as args (dict, list, set, int, string) # But there is no chance to pass class instance into separate process (e.g. current SshPool cannot be passed) # # Also self.watch_thread() method should be static (because self arg is passed by default in instance method) if 'debug_background_probe' in self.test_class.config: self.executor = ThreadPoolExecutor( max_workers=len(self.probe_config['probes'])) else: self.executor = ProcessPoolExecutor( max_workers=len(self.probe_config['probes'])) for probe_name in self.probe_config['probes']: if probe_name == 'cpu_mem': self.futures['cpu_mem'] = self.executor.submit( self.cpu_mem_thread_method, self.ignite.get_alive_default_nodes(), self.ignite.nodes, self.test_class.config['ssh']) elif probe_name == 'heap': self.futures['heap'] = self.executor.submit( self.heap_thread_method, self.ignite.get_alive_default_nodes(), self.ignite.nodes, self.test_class.config['ssh']) elif probe_name == 'jmx': assert 'jmx_metrics' in self.probe_config, 'jmx_metrics should be defined if jmx background probe used' # start jmx utility wo gateway self.jmx = JmxUtility(self.ignite, start_gateway=False) self.jmx.start_utility() jmx_node_id = int(self.jmx.node_id) self.futures['jmx'] = self.executor.submit( self.jmx_thread_method, self.ignite.get_alive_default_nodes(), self.ignite.nodes, jmx_node_id, self.probe_config['jmx_metrics']) else: raise TidenException('Unknown probe name %s' % probe_name) def stop(self, **kwargs): """ Stop background probe NB! Do not move fut.results vs jmx node killing. This may lead to py4j errors in log. """ super().stop() # write 1 into lock file to stop all probes with open('lock', 'w') as f: f.write('1') # get result from process threads (this code guarantee that jmx is not usable anymore) sleep(10) for name, fut in self.futures.items(): if fut.exception(): log_print("Failed to evaluate probe %s, %s" % (name, fut.exception()), color='red') else: self.results[self.version][name] = fut.result() # kill utility using ignite api (jmx gateway already down in probe thread) if self.jmx: self.jmx.kill_utility() # self.ignite.kill_node(self.jmx.node_id) # shutdown executor self.executor.shutdown(wait=True) # remove lock file os.remove('lock') def is_passed(self, **kwargs): """ Just print results :param kwargs: None :return: always True """ return True @staticmethod def cpu_mem_thread_method(nodes_to_monitor, ignite_nodes, ssh_config, timeout=5): """ probe thread that collects cpu,mem from nodes_to_monitor Command to collect: "ps -p PID -o pid,%%cpu,%%mem" :param nodes_to_monitor: nodes that we want to monitor (server nodes in this example) :param ignite_nodes: nodes from current Ignite app (need to get PID) :param ssh_config: config['ssh_config'] from tiden config (Need to initialize SshPool) :param timeout: timeout between data collect :return: collected results ('default' python type) """ ssh = SshPool(ssh_config) ssh.connect() cpu_mem_result = {} with open('lock', 'r') as f: while True: if f.read(1) == '1': log_print("Background probe CPU has been interrupted") break commands = {} node_ids_to_pid = {} for node_ids in nodes_to_monitor: node_ids_to_pid[node_ids] = ignite_nodes[node_ids]['PID'] for node_idx in nodes_to_monitor: host = ignite_nodes[node_idx]['host'] if commands.get(host) is None: commands[host] = [ 'ps -p %s -o pid,%%cpu,%%mem' % ignite_nodes[node_idx]['PID'] ] else: commands[host].append('ps -p %s -o pid,%%cpu,%%mem' % ignite_nodes[node_idx]['PID']) results = ssh.exec(commands) results_parsed = {} for host in results.keys(): result = results[host][0] search = re.search('(\d+)\s+?(\d+.?\d?)\s+?(\d+.?\d?)', result) if search: node_id = 0 for node_id, pid in node_ids_to_pid.items(): if pid == int(search.group(1)): node_id = node_id break results_parsed[node_id] = (float(search.group(2)), float(search.group(3))) else: continue cpu_mem_result[get_current_time()] = results_parsed sleep(timeout) return cpu_mem_result @staticmethod def heap_thread_method(nodes_to_monitor, ignite_nodes, ssh_config, timeout=5): """ probe thread that collects JVM Heap usage from nodes_to_monitor Command to collect: "jcmd PID GC.class_histogram" This command prints following text: "PID: 1. JAVA_OBJECT_NUM JAVA_OBJECT_SIZE JAVA_OBJECT_NAME ... N. Total TOTAL_OBJECTS TOTAL_OBJECTS_SIZE" So we need to collect PID (to match it to node) and TOTAL_OBJECTS_SIZE from that output. :param nodes_to_monitor: nodes that we want to monitor (server nodes in this example) :param ignite_nodes: nodes from current Ignite app (need to get PID) :param ssh_config: config['ssh_config'] from tiden config (Need to initialize SshPool) :return: collected results ('default' python type) """ ssh = SshPool(ssh_config) ssh.connect() heap_result = {} try: with open('lock', 'r') as f: while True: if f.read(1) == '1': log_print("Background probe HEAP has been interrupted") break commands = {} node_ids_to_pid = {} for node_ids in nodes_to_monitor: node_ids_to_pid[node_ids] = ignite_nodes[node_ids][ 'PID'] for node_idx in nodes_to_monitor: host = ignite_nodes[node_idx]['host'] if commands.get(host) is None: commands[host] = [ 'jcmd %s GC.class_histogram' % ignite_nodes[node_idx]['PID'] ] else: commands[host].append( 'jcmd %s GC.class_histogram' % ignite_nodes[node_idx]['PID']) results = ssh.exec(commands) results_parsed = {} for host in results.keys(): result = results[host][0] findall = re.compile( '(\d+):\n|Total\s+\d+\s+(\d+)').findall(result) # findall will return 2d array: [['PID', ''], [''] ['TOTAL_HEAP_USAGE']] # todo maybe there is a better way to get this if findall: node_id = 0 for node_id, pid in node_ids_to_pid.items(): if pid == int(findall[0][0]): node_id = node_id break try: results_parsed[node_id] = (int(findall[1][1])) except Exception: results_parsed[node_id] = 0 else: continue heap_result[get_current_time()] = results_parsed sleep(timeout) except Exception: log_print(traceback.format_exc()) return heap_result @staticmethod def jmx_thread_method(nodes_to_monitor, ignite_nodes, jmx_node_id, metrics_to_collect, timeout=5): """ probe thread that collects JMX metrics from specified nodes Uses mocked JMXUtility (does not start new instance, just use existing methods) We need to pass nothing to create this instance just override nodes, gateway and service :param nodes_to_monitor: nodes that we want to monitor (server nodes in this example) :param ignite_nodes: nodes from current Ignite app (need to get PID) :param jmx_node_id: jmx node id from tiden.ignite.nodes :param metrics_to_collect: {'attr': {'grp': 'Group', 'bean': 'Bean', 'attribute': 'Attr'}, ...} :param timeout: timeout to collect metrics :return: collected results ('default' python type) """ # Close connections and shutdown gateway properly jmx_metric = {} jmx = None try: jmx = JmxUtility() jmx.initialize_manually(jmx_node_id, ignite_nodes) with open('lock', 'r') as f: while True: if f.read(1) == '1': log_print("Background probe JMX has been interrupted") break current_time = get_current_time() for node_idx in nodes_to_monitor: if current_time not in jmx_metric: jmx_metric[current_time] = {} if node_idx not in jmx_metric[current_time]: jmx_metric[current_time][node_idx] = {} for name, metric in metrics_to_collect.items(): try: string_value = \ jmx.get_attributes(node_idx, metric['grp'], metric['bean'], metric['attribute'], )[metric['attribute']] if metric['type'] == 'int': jmx_metric[current_time][node_idx][ name] = int(string_value) else: jmx_metric[current_time][node_idx][ name] = string_value except Exception: jmx_metric[current_time][node_idx][name] = None sleep(timeout) except Exception: log_print(traceback.format_exc()) finally: # Close connections and shutdown gateway properly if jmx: jmx.kill_manually() return jmx_metric
class MediaEventHandler(FileSystemEventHandler): __LOG = None _CONFIG = ConverterConfig.get_instance() DEFAULT_MAX_PROCESSES = 2 DEFAULT_CONVERTER = ConverterFactory.Converters.FFMPEG def __init__(self, max_processes: int = DEFAULT_MAX_PROCESSES, converter: ConverterFactory.Converters = DEFAULT_CONVERTER): super().__init__() MediaEventHandler.__LOG = LogManager.get_instance().get( LogManager.Logger.OBSERVER) self.__converter = ConverterFactory.get_type(converter) self.__executor = ProcessPoolExecutor( max_workers=max_processes, initializer=MediaEventHandler.__init_worker) @classmethod def __init_worker(cls) -> None: """ Workaround for managing Python's bug: while on wait syscall, KeyboardInterrupt is not handled Prevent the child processes from ever receiving KeyboardInterrupt and leaving it completely up to the parent process to catch the interrupt and clean up the process pool. :author: John Reese, https://noswap.com/blog/python-multiprocessing-keyboardinterrupt and https://github.com/jreese/multiprocessing-keyboardinterrupt """ signal.signal(signal.SIGINT, signal.SIG_IGN) def on_created(self, event: FileSystemEvent) -> None: super().on_created(event) try: Validation.is_file(event.src_path) except FileNotFoundError: MediaEventHandler.__LOG.debug( f"[SKIPPING] '{event.src_path}': not a file") return MediaEventHandler.__LOG.debug(f"[CREATED] '{event.src_path}'") fileout = self.__get_fileout_from( event.src_path, MediaEventHandler._CONFIG.media_out_folder, MediaEventHandler._CONFIG.media_out_format.get('format')) converter_object = MediaInfo( event.src_path, MediaEventHandler._CONFIG.media_in_converted_folder, fileout, MediaEventHandler._CONFIG.media_out_format) self.__executor.submit(self.__converter.execute, converter_object) def on_deleted(self, event: FileSystemEvent) -> None: super().on_deleted(event) MediaEventHandler.__LOG.debug(f"[DELETED] '{event.src_path}'") def shutdown(self): self.__executor.shutdown(wait=True) @classmethod def __get_fileout_from(cls, filein: str, dirout: str, extension: str) -> str: path_filein = Path(filein) path_dirout = Path(dirout) return str( path_dirout.joinpath( path_filein.stem).with_suffix(f".{extension}"))
def do_test3(workers): param = {"max_workers": workers} loop = asyncio.new_event_loop() lock = threading.Lock() tresult = [] presult = [] cresult = [] pre_input1 = input_generator(workers, 0) pre_input2 = input_generator(workers, max(pre_input1)) pre_input3 = input_generator(workers, max(pre_input2)) def result_checker(list, lock, fut): with lock: try: list.append(fut.result()) except Exception as e: list.append(e) texec = ThreadPoolExecutor(**param) pexec = ProcessPoolExecutor(**param) cexec = CoroutinePoolExecutor(**param, loop=loop) tstart = round(time.time()+1) input1 = [tstart + i for i in pre_input1] input2 = [tstart + i for i in pre_input2] input3 = [tstart + i for i in pre_input3] for x in input1: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) result_iter = texec.map(wake_at, input2) for x in input3: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) for x in result_iter: with lock: tresult.append(x) texec.shutdown(True) pstart = round(time.time() + _start_warm_up) input1 = [pstart + i for i in pre_input1] input2 = [pstart + i for i in pre_input2] input3 = [pstart + i for i in pre_input3] for x in input1: future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) result_iter = pexec.map(wake_at, input2) for x in input3: future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) for x in result_iter: with lock: presult.append(x) pexec.shutdown(True) cstart = round(time.time() + _start_warm_up) input1 = [cstart + i for i in pre_input1] input2 = [cstart + i for i in pre_input2] input3 = [cstart + i for i in pre_input3] async def async_main(): for x in input1: future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) result_iter = cexec.map(async_wake_at, input2) for x in input3: future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) async for x in result_iter: with lock: cresult.append(x) await cexec.shutdown(False) loop.run_until_complete(async_main()) try: loop.run_until_complete(cexec.shutdown(True)) texec.shutdown(True) pexec.shutdown(True) finally: loop.close() tresult = [round((x - tstart) / _precision) for x in tresult] presult = [round((x - pstart) / _precision) for x in presult] cresult = [round((x - cstart) / _precision) for x in cresult] result = True for (t, p, c) in zip(tresult, presult, cresult): result = result and (t == p) if not result: print(tresult) print(presult) print(cresult) print(t,p,c) assert False result = result and (p == c) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (c == t) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False return result
offset = 1000 * index musics = sql.get_music_page(offset, 1000) print("index:", index, "offset:", offset, "artists :", len(musics)) for item in musics: try: my_lyric_comment.saveComment(item['music_id']) except Exception as e: # 打印错误日志 print(' internal error : ' + str(e)) # traceback.print_exc() time.sleep(5) if __name__ == '__main__': print("======= 开始爬 评论 信息 ===========") startTime = datetime.datetime.now() print(startTime.strftime('%Y-%m-%d %H:%M:%S')) # 所有歌手数量 musics_num = sql.get_all_music_num() # 批次 batch = math.ceil(musics_num.get('num') / 1000.0) # 构建线程池 pool = ProcessPoolExecutor(5) for index in range(0, batch): pool.submit(saveCommentBatch, index) pool.shutdown(wait=True) print("======= 结束爬 评论 信息 ===========") endTime = datetime.datetime.now() print(endTime.strftime('%Y-%m-%d %H:%M:%S')) print((endTime - startTime).seconds)
class Blockchain: constants: ConsensusConstants constants_json: Dict # peak of the blockchain peak_height: Optional[uint32] # All sub blocks in peak path are guaranteed to be included, can include orphan sub-blocks sub_blocks: Dict[bytes32, SubBlockRecord] # Defines the path from genesis to the peak, no orphan sub-blocks sub_height_to_hash: Dict[uint32, bytes32] # All sub-epoch summaries that have been included in the blockchain from the beginning until and including the peak # (height_included, SubEpochSummary). Note: ONLY for the sub-blocks in the path to the peak sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {} # Unspent Store coin_store: CoinStore # Store block_store: BlockStore # Used to verify blocks in parallel pool: ProcessPoolExecutor # Whether blockchain is shut down or not _shut_down: bool # Lock to prevent simultaneous reads and writes lock: asyncio.Lock @staticmethod async def create( coin_store: CoinStore, block_store: BlockStore, consensus_constants: ConsensusConstants, ): """ Initializes a blockchain with the SubBlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config. """ self = Blockchain() self.lock = asyncio.Lock() # External lock handled by full node cpu_count = multiprocessing.cpu_count() if cpu_count > 61: cpu_count = 61 # Windows Server 2016 has an issue https://bugs.python.org/issue26903 num_workers = max(cpu_count - 2, 1) log.info(f"Starting {num_workers} processes for block validation") self.pool = ProcessPoolExecutor(max_workers=num_workers) self.constants = consensus_constants self.coin_store = coin_store self.block_store = block_store self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) self._shut_down = False await self._load_chain_from_store() return self def shut_down(self): self._shut_down = True self.pool.shutdown(wait=True) async def _load_chain_from_store(self) -> None: """ Initializes the state of the Blockchain class from the database. """ self.sub_blocks, peak = await self.block_store.get_sub_block_records() self.sub_height_to_hash = {} self.sub_epoch_summaries = {} if len(self.sub_blocks) == 0: assert peak is None self.peak_height = None return assert peak is not None self.peak_height = self.sub_blocks[peak].sub_block_height # Sets the other state variables (peak_height and height_to_hash) curr: SubBlockRecord = self.sub_blocks[peak] while True: self.sub_height_to_hash[curr.sub_block_height] = curr.header_hash if curr.sub_epoch_summary_included is not None: self.sub_epoch_summaries[ curr.sub_block_height] = curr.sub_epoch_summary_included if curr.sub_block_height == 0: break curr = self.sub_blocks[curr.prev_hash] assert len(self.sub_height_to_hash) == self.peak_height + 1 def get_peak(self) -> Optional[SubBlockRecord]: """ Return the peak of the blockchain """ if self.peak_height is None: return None return self.sub_blocks[self.sub_height_to_hash[self.peak_height]] async def get_full_peak(self) -> Optional[FullBlock]: if self.peak_height is None: return None """ Return list of FullBlocks that are peaks""" block = await self.block_store.get_full_block( self.sub_height_to_hash[self.peak_height]) assert block is not None return block async def get_block_peak(self) -> Optional[FullBlock]: """ Return peak block""" if self.peak_height is None: return None start = int(self.peak_height) peak = None while start >= 0: block = await self.block_store.get_full_block( self.sub_height_to_hash[uint32(start)]) if block is not None and block.is_block(): peak = block break start -= 1 return peak def is_child_of_peak(self, block: UnfinishedBlock) -> bool: """ True iff the block is the direct ancestor of the peak """ peak = self.get_peak() if peak is None: return False return block.prev_header_hash == peak.header_hash def contains_sub_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan sub-blocks that we have added but no longer keep in memory. """ return header_hash in self.sub_blocks async def get_full_block(self, header_hash: bytes32) -> Optional[FullBlock]: return await self.block_store.get_full_block(header_hash) async def receive_block( self, block: FullBlock, pre_validation_result: Optional[PreValidationResult] = None, ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32]]: """ This method must be called under the blockchain lock Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case of a new peak. """ genesis: bool = block.sub_block_height == 0 if block.header_hash in self.sub_blocks: return ReceiveBlockResult.ALREADY_HAVE_BLOCK, None, None if block.prev_header_hash not in self.sub_blocks and not genesis: return ( ReceiveBlockResult.DISCONNECTED_BLOCK, Err.INVALID_PREV_BLOCK_HASH, None, ) if pre_validation_result is None: if block.sub_block_height == 0: prev_sb: Optional[SubBlockRecord] = None else: prev_sb = self.sub_blocks[block.prev_header_hash] sub_slot_iters, difficulty = get_sub_slot_iters_and_difficulty( self.constants, block, self.sub_height_to_hash, prev_sb, self.sub_blocks) required_iters, error = validate_finished_header_block( self.constants, self.sub_blocks, block.get_block_header(), False, difficulty, sub_slot_iters, ) if error is not None: return ReceiveBlockResult.INVALID_BLOCK, error.code, None else: required_iters = pre_validation_result.required_iters assert pre_validation_result.error is None assert required_iters is not None error_code = await validate_block_body( self.constants, self.sub_blocks, self.sub_height_to_hash, self.block_store, self.coin_store, self.get_peak(), block, block.sub_block_height, block.height if block.is_block() else None, pre_validation_result.cost_result if pre_validation_result is not None else None, ) if error_code is not None: return ReceiveBlockResult.INVALID_BLOCK, error_code, None sub_block = block_to_sub_block_record( self.constants, self.sub_blocks, self.sub_height_to_hash, required_iters, block, None, ) # Always add the block to the database await self.block_store.add_full_block(block, sub_block) self.sub_blocks[sub_block.header_hash] = sub_block fork_height: Optional[uint32] = await self._reconsider_peak( sub_block, genesis) if fork_height is not None: return ReceiveBlockResult.NEW_PEAK, None, fork_height else: return ReceiveBlockResult.ADDED_AS_ORPHAN, None, None async def _reconsider_peak(self, sub_block: SubBlockRecord, genesis: bool) -> Optional[uint32]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there was no update to the heaviest chain. """ peak = self.get_peak() if genesis: if peak is None: block: Optional[ FullBlock] = await self.block_store.get_full_block( sub_block.header_hash) assert block is not None await self.coin_store.new_block(block) self.sub_height_to_hash[uint32(0)] = block.header_hash self.peak_height = uint32(0) await self.block_store.set_peak(block.header_hash) return uint32(0) return None assert peak is not None if sub_block.weight > peak.weight: # Find the fork. if the block is just being appended, it will return the peak # If no blocks in common, returns -1, and reverts all blocks fork_sub_block_height: int = find_fork_point_in_chain( self.sub_blocks, sub_block, peak) if fork_sub_block_height == -1: coin_store_reorg_height = -1 else: last_sb_in_common = self.sub_blocks[self.sub_height_to_hash[ uint32(fork_sub_block_height)]] if last_sb_in_common.is_block: coin_store_reorg_height = last_sb_in_common.height else: coin_store_reorg_height = last_sb_in_common.height - 1 # Rollback to fork await self.coin_store.rollback_to_block(coin_store_reorg_height) # Rollback sub_epoch_summaries heights_to_delete = [] for ses_included_height in self.sub_epoch_summaries.keys(): if ses_included_height > fork_sub_block_height: heights_to_delete.append(ses_included_height) for sub_height in heights_to_delete: del self.sub_epoch_summaries[sub_height] # Collect all blocks from fork point to new peak blocks_to_add: List[Tuple[FullBlock, SubBlockRecord]] = [] curr = sub_block.header_hash while fork_sub_block_height < 0 or curr != self.sub_height_to_hash[ uint32(fork_sub_block_height)]: fetched_block: Optional[ FullBlock] = await self.block_store.get_full_block(curr) fetched_sub_block: Optional[ SubBlockRecord] = await self.block_store.get_sub_block_record( curr) assert fetched_block is not None assert fetched_sub_block is not None blocks_to_add.append((fetched_block, fetched_sub_block)) if fetched_block.sub_block_height == 0: # Doing a full reorg, starting at height 0 break curr = fetched_sub_block.prev_hash for fetched_block, fetched_sub_block in reversed(blocks_to_add): self.sub_height_to_hash[ fetched_sub_block. sub_block_height] = fetched_sub_block.header_hash if fetched_sub_block.is_block: await self.coin_store.new_block(fetched_block) if fetched_sub_block.sub_epoch_summary_included is not None: self.sub_epoch_summaries[ fetched_sub_block. sub_block_height] = fetched_sub_block.sub_epoch_summary_included # Changes the peak to be the new peak await self.block_store.set_peak(sub_block.header_hash) self.peak_height = sub_block.sub_block_height return uint32(max(fork_sub_block_height, 0)) # This is not a heavier block than the heaviest we have seen, so we don't change the coin set return None def get_next_difficulty(self, header_hash: bytes32, new_slot: bool) -> uint64: assert header_hash in self.sub_blocks curr = self.sub_blocks[header_hash] if curr.sub_block_height <= 2: return self.constants.DIFFICULTY_STARTING return get_next_difficulty( self.constants, self.sub_blocks, self.sub_height_to_hash, header_hash, curr.sub_block_height, uint64(curr.weight - self.sub_blocks[curr.prev_hash].weight), curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) def get_next_slot_iters(self, header_hash: bytes32, new_slot: bool) -> uint64: assert header_hash in self.sub_blocks curr = self.sub_blocks[header_hash] if curr.sub_block_height <= 2: return self.constants.SUB_SLOT_ITERS_STARTING return get_next_sub_slot_iters( self.constants, self.sub_blocks, self.sub_height_to_hash, header_hash, curr.sub_block_height, curr.sub_slot_iters, curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) async def get_sp_and_ip_sub_slots( self, header_hash: bytes32 ) -> Optional[Tuple[Optional[EndOfSubSlotBundle], Optional[EndOfSubSlotBundle]]]: block: Optional[FullBlock] = await self.block_store.get_full_block( header_hash) if block is None: return None is_overflow = self.sub_blocks[block.header_hash].overflow curr_sbr: SubBlockRecord = self.sub_blocks[block.header_hash] curr: Optional[FullBlock] = block assert curr is not None while curr_sbr.sub_block_height > 0: if curr_sbr.first_in_sub_slot: curr = await self.block_store.get_full_block( curr_sbr.header_hash) assert curr is not None break curr_sbr = self.sub_blocks[curr_sbr.prev_hash] if len(curr.finished_sub_slots) == 0: # This means we got to genesis and still no sub-slots return None, None ip_sub_slot = curr.finished_sub_slots[-1] if not is_overflow: # Pos sub-slot is the same as infusion sub slot return None, ip_sub_slot if len(curr.finished_sub_slots) > 1: # Have both sub-slots return curr.finished_sub_slots[-2], ip_sub_slot prev_curr: Optional[FullBlock] = await self.block_store.get_full_block( curr.prev_header_hash) if prev_curr is None: assert curr.sub_block_height == 0 prev_curr = curr prev_curr_sbr = self.sub_blocks[curr.header_hash] else: prev_curr_sbr = self.sub_blocks[curr.prev_header_hash] assert prev_curr_sbr is not None while prev_curr_sbr.sub_block_height > 0: if prev_curr_sbr.first_in_sub_slot: prev_curr = await self.block_store.get_full_block( prev_curr_sbr.header_hash) assert prev_curr is not None break prev_curr_sbr = self.sub_blocks[prev_curr_sbr.prev_hash] if len(prev_curr.finished_sub_slots) == 0: return None, ip_sub_slot return prev_curr.finished_sub_slots[-1], ip_sub_slot def get_recent_reward_challenges(self) -> List[Tuple[bytes32, uint128]]: peak = self.get_peak() if peak is None: return [] recent_rc: List[Tuple[bytes32, uint128]] = [] curr = self.sub_blocks.get(peak.prev_hash, None) while curr is not None and len( recent_rc) < 2 * self.constants.MAX_SUB_SLOT_SUB_BLOCKS: recent_rc.append( (curr.reward_infusion_new_challenge, curr.total_iters)) if curr.first_in_sub_slot: assert curr.finished_reward_slot_hashes is not None sub_slot_total_iters = curr.ip_sub_slot_total_iters( self.constants) # Start from the most recent for rc in reversed(curr.finished_reward_slot_hashes): recent_rc.append((rc, sub_slot_total_iters)) sub_slot_total_iters = uint128(sub_slot_total_iters - curr.sub_slot_iters) curr = self.sub_blocks.get(curr.prev_hash, None) return list(reversed(recent_rc)) async def validate_unfinished_block( self, block: UnfinishedBlock, skip_overflow_ss_validation=True ) -> Tuple[Optional[uint64], Optional[Err]]: if (block.prev_header_hash not in self.sub_blocks and not block.prev_header_hash == self.constants.GENESIS_PREV_HASH): return None, Err.INVALID_PREV_BLOCK_HASH unfinished_header_block = UnfinishedHeaderBlock( block.finished_sub_slots, block.reward_chain_sub_block, block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage_sub_block, block.foliage_block, b"", ) prev_sb = self.sub_blocks.get(unfinished_header_block.prev_header_hash, None) sub_slot_iters, difficulty = get_sub_slot_iters_and_difficulty( self.constants, unfinished_header_block, self.sub_height_to_hash, prev_sb, self.sub_blocks) required_iters, error = validate_unfinished_header_block( self.constants, self.sub_blocks, unfinished_header_block, False, difficulty, sub_slot_iters, skip_overflow_ss_validation, ) if error is not None: return None, error.code prev_sub_height = ( -1 if block.prev_header_hash == self.constants.GENESIS_PREV_HASH else self.sub_blocks[block.prev_header_hash].sub_block_height) if block.is_block(): assert block.foliage_block is not None height: Optional[uint32] = block.foliage_block.height else: height = None error_code = await validate_block_body( self.constants, self.sub_blocks, self.sub_height_to_hash, self.block_store, self.coin_store, self.get_peak(), block, uint32(prev_sub_height + 1), height, ) if error_code is not None: return None, error_code return required_iters, None async def pre_validate_blocks_multiprocessing( self, blocks: List[FullBlock], ) -> Optional[List[PreValidationResult]]: return await pre_validate_blocks_multiprocessing( self.constants, self.constants_json, self.sub_blocks, self.sub_height_to_hash, blocks, self.pool)
def do_test3(workers): param = {"max_workers": workers} loop = asyncio.new_event_loop() lock = threading.Lock() tresult = [] presult = [] cresult = [] pre_input1 = input_generator(workers, 0) pre_input2 = input_generator(workers, max(pre_input1)) pre_input3 = input_generator(workers, max(pre_input2)) def result_checker(list, lock, fut): with lock: try: list.append(fut.result()) except Exception as e: list.append(e) texec = ThreadPoolExecutor(**param) pexec = ProcessPoolExecutor(**param) cexec = CoroutinePoolExecutor(**param, loop=loop) tstart = round(time.time() + 1) input1 = [tstart + i for i in pre_input1] input2 = [tstart + i for i in pre_input2] input3 = [tstart + i for i in pre_input3] for x in input1: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) result_iter = texec.map(wake_at, input2) for x in input3: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) for x in result_iter: with lock: tresult.append(x) texec.shutdown(True) pstart = round(time.time() + _start_warm_up) input1 = [pstart + i for i in pre_input1] input2 = [pstart + i for i in pre_input2] input3 = [pstart + i for i in pre_input3] for x in input1: future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) result_iter = pexec.map(wake_at, input2) for x in input3: future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) for x in result_iter: with lock: presult.append(x) pexec.shutdown(True) cstart = round(time.time() + _start_warm_up) input1 = [cstart + i for i in pre_input1] input2 = [cstart + i for i in pre_input2] input3 = [cstart + i for i in pre_input3] async def async_main(): for x in input1: future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) result_iter = cexec.map(async_wake_at, input2) for x in input3: future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) async for x in result_iter: with lock: cresult.append(x) await cexec.shutdown(False) loop.run_until_complete(async_main()) try: loop.run_until_complete(cexec.shutdown(True)) texec.shutdown(True) pexec.shutdown(True) finally: loop.close() tresult = [round((x - tstart) / _precision) for x in tresult] presult = [round((x - pstart) / _precision) for x in presult] cresult = [round((x - cstart) / _precision) for x in cresult] result = True for (t, p, c) in zip(tresult, presult, cresult): result = result and (t == p) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (p == c) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (c == t) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False return result
class Blockchain(BlockchainInterface): constants: ConsensusConstants constants_json: Dict # peak of the blockchain _peak_height: Optional[uint32] # All blocks in peak path are guaranteed to be included, can include orphan blocks __block_records: Dict[bytes32, BlockRecord] # all hashes of blocks in block_record by height, used for garbage collection __heights_in_cache: Dict[uint32, Set[bytes32]] # maps block height (of the current heaviest chain) to block hash and sub # epoch summaries __height_map: BlockHeightMap # Unspent Store coin_store: CoinStore # Store block_store: BlockStore # Used to verify blocks in parallel pool: ProcessPoolExecutor # Set holding seen compact proofs, in order to avoid duplicates. _seen_compact_proofs: Set[Tuple[VDFInfo, uint32]] # Whether blockchain is shut down or not _shut_down: bool # Lock to prevent simultaneous reads and writes lock: asyncio.Lock compact_proof_lock: asyncio.Lock hint_store: HintStore @staticmethod async def create( coin_store: CoinStore, block_store: BlockStore, consensus_constants: ConsensusConstants, hint_store: HintStore, blockchain_dir: Path, reserved_cores: int, ): """ Initializes a blockchain with the BlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config. """ self = Blockchain() self.lock = asyncio.Lock() # External lock handled by full node self.compact_proof_lock = asyncio.Lock() cpu_count = multiprocessing.cpu_count() if cpu_count > 61: cpu_count = 61 # Windows Server 2016 has an issue https://bugs.python.org/issue26903 num_workers = max(cpu_count - reserved_cores, 1) self.pool = ProcessPoolExecutor(max_workers=num_workers) log.info(f"Started {num_workers} processes for block validation") self.constants = consensus_constants self.coin_store = coin_store self.block_store = block_store self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) self._shut_down = False await self._load_chain_from_store(blockchain_dir) self._seen_compact_proofs = set() self.hint_store = hint_store return self def shut_down(self): self._shut_down = True self.pool.shutdown(wait=True) async def _load_chain_from_store(self, blockchain_dir): """ Initializes the state of the Blockchain class from the database. """ self.__height_map = await BlockHeightMap.create( blockchain_dir, self.block_store.db_wrapper) self.__block_records = {} self.__heights_in_cache = {} block_records, peak = await self.block_store.get_block_records_close_to_peak( self.constants.BLOCKS_CACHE_SIZE) for block in block_records.values(): self.add_block_record(block) if len(block_records) == 0: assert peak is None self._peak_height = None return assert peak is not None self._peak_height = self.block_record(peak).height assert self.__height_map.contains_height(self._peak_height) assert not self.__height_map.contains_height(self._peak_height + 1) def get_peak(self) -> Optional[BlockRecord]: """ Return the peak of the blockchain """ if self._peak_height is None: return None return self.height_to_block_record(self._peak_height) async def get_full_peak(self) -> Optional[FullBlock]: if self._peak_height is None: return None """ Return list of FullBlocks that are peaks""" # TODO: address hint error and remove ignore # error: Argument 1 to "get_full_block" of "BlockStore" has incompatible type "Optional[bytes32]"; # expected "bytes32" [arg-type] block = await self.block_store.get_full_block( self.height_to_hash(self._peak_height)) # type: ignore[arg-type] assert block is not None return block async def get_full_block(self, header_hash: bytes32) -> Optional[FullBlock]: return await self.block_store.get_full_block(header_hash) async def receive_block( self, block: FullBlock, pre_validation_result: PreValidationResult, fork_point_with_peak: Optional[uint32] = None, ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32], Tuple[ List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], ]: """ This method must be called under the blockchain lock Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case of a new peak. Args: block: The FullBlock to be validated. pre_validation_result: A result of successful pre validation fork_point_with_peak: The fork point, for efficiency reasons, if None, it will be recomputed Returns: The result of adding the block to the blockchain (NEW_PEAK, ADDED_AS_ORPHAN, INVALID_BLOCK, DISCONNECTED_BLOCK, ALREDY_HAVE_BLOCK) An optional error if the result is not NEW_PEAK or ADDED_AS_ORPHAN A fork point if the result is NEW_PEAK A list of changes to the coin store, and changes to hints, if the result is NEW_PEAK """ genesis: bool = block.height == 0 if self.contains_block(block.header_hash): return ReceiveBlockResult.ALREADY_HAVE_BLOCK, None, None, ([], {}) if not self.contains_block(block.prev_header_hash) and not genesis: return (ReceiveBlockResult.DISCONNECTED_BLOCK, Err.INVALID_PREV_BLOCK_HASH, None, ([], {})) if not genesis and (self.block_record(block.prev_header_hash).height + 1) != block.height: return ReceiveBlockResult.INVALID_BLOCK, Err.INVALID_HEIGHT, None, ( [], {}) npc_result: Optional[NPCResult] = pre_validation_result.npc_result required_iters = pre_validation_result.required_iters if pre_validation_result.error is not None: return ReceiveBlockResult.INVALID_BLOCK, Err( pre_validation_result.error), None, ([], {}) assert required_iters is not None error_code, _ = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, block.height, npc_result, fork_point_with_peak, self.get_block_generator, # If we did not already validate the signature, validate it now validate_signature=not pre_validation_result.validated_signature, ) if error_code is not None: return ReceiveBlockResult.INVALID_BLOCK, error_code, None, ([], {}) block_record = block_to_block_record( self.constants, self, required_iters, block, None, ) # Always add the block to the database async with self.block_store.db_wrapper.lock: try: header_hash: bytes32 = block.header_hash # Perform the DB operations to update the state, and rollback if something goes wrong await self.block_store.db_wrapper.begin_transaction() await self.block_store.add_full_block(header_hash, block, block_record, False) fork_height, peak_height, records, ( coin_record_change, hint_changes) = await self._reconsider_peak( block_record, genesis, fork_point_with_peak, npc_result) await self.block_store.db_wrapper.commit_transaction() # Then update the memory cache. It is important that this task is not cancelled and does not throw self.add_block_record(block_record) for fetched_block_record in records: self.__height_map.update_height( fetched_block_record.height, fetched_block_record.header_hash, fetched_block_record.sub_epoch_summary_included, ) if peak_height is not None: self._peak_height = peak_height await self.__height_map.maybe_flush() except BaseException as e: self.block_store.rollback_cache_block(header_hash) await self.block_store.db_wrapper.rollback_transaction() log.error( f"Error while adding block {block.header_hash} height {block.height}," f" rolling back: {traceback.format_exc()} {e}") raise if fork_height is not None: # new coin records added assert coin_record_change is not None return ReceiveBlockResult.NEW_PEAK, None, fork_height, ( coin_record_change, hint_changes) else: return ReceiveBlockResult.ADDED_AS_ORPHAN, None, None, ([], {}) def get_hint_list(self, npc_result: NPCResult) -> List[Tuple[bytes32, bytes]]: h_list = [] for npc in npc_result.npc_list: for opcode, conditions in npc.conditions: if opcode == ConditionOpcode.CREATE_COIN: for condition in conditions: if len(condition.vars ) > 2 and condition.vars[2] != b"": puzzle_hash, amount_bin = condition.vars[ 0], condition.vars[1] amount = int_from_bytes(amount_bin) # TODO: address hint error and remove ignore # error: Argument 2 to "Coin" has incompatible type "bytes"; expected "bytes32" # [arg-type] coin_id = Coin( npc.coin_name, puzzle_hash, amount).name() # type: ignore[arg-type] h_list.append((coin_id, condition.vars[2])) return h_list async def _reconsider_peak( self, block_record: BlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32], npc_result: Optional[NPCResult], ) -> Tuple[Optional[uint32], Optional[uint32], List[BlockRecord], Tuple[ List[CoinRecord], Dict[bytes, Dict[bytes32, CoinRecord]]], ]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there was no update to the heaviest chain. """ peak = self.get_peak() lastest_coin_state: Dict[bytes32, CoinRecord] = {} hint_coin_state: Dict[bytes, Dict[bytes32, CoinRecord]] = {} if genesis: if peak is None: block: Optional[ FullBlock] = await self.block_store.get_full_block( block_record.header_hash) assert block is not None if npc_result is not None: tx_removals, tx_additions = tx_removals_and_additions( npc_result.npc_list) else: tx_removals, tx_additions = [], [] if block.is_transaction_block(): assert block.foliage_transaction_block is not None added = await self.coin_store.new_block( block.height, block.foliage_transaction_block.timestamp, block.get_included_reward_coins(), tx_additions, tx_removals, ) else: added, _ = [], [] await self.block_store.set_in_chain([ (block_record.header_hash, ) ]) await self.block_store.set_peak(block_record.header_hash) return uint32(0), uint32(0), [block_record], (added, {}) return None, None, [], ([], {}) assert peak is not None if block_record.weight > peak.weight: # Find the fork. if the block is just being appended, it will return the peak # If no blocks in common, returns -1, and reverts all blocks if block_record.prev_hash == peak.header_hash: fork_height: int = peak.height elif fork_point_with_peak is not None: fork_height = fork_point_with_peak else: fork_height = find_fork_point_in_chain(self, block_record, peak) if block_record.prev_hash != peak.header_hash: roll_changes: List[ CoinRecord] = await self.coin_store.rollback_to_block( fork_height) for coin_record in roll_changes: lastest_coin_state[coin_record.name] = coin_record # Rollback sub_epoch_summaries self.__height_map.rollback(fork_height) await self.block_store.rollback(fork_height) # Collect all blocks from fork point to new peak blocks_to_add: List[Tuple[FullBlock, BlockRecord]] = [] curr = block_record.header_hash while fork_height < 0 or curr != self.height_to_hash( uint32(fork_height)): fetched_full_block: Optional[ FullBlock] = await self.block_store.get_full_block(curr) fetched_block_record: Optional[ BlockRecord] = await self.block_store.get_block_record(curr ) assert fetched_full_block is not None assert fetched_block_record is not None blocks_to_add.append( (fetched_full_block, fetched_block_record)) if fetched_full_block.height == 0: # Doing a full reorg, starting at height 0 break curr = fetched_block_record.prev_hash records_to_add = [] for fetched_full_block, fetched_block_record in reversed( blocks_to_add): records_to_add.append(fetched_block_record) if fetched_full_block.is_transaction_block(): if fetched_block_record.header_hash == block_record.header_hash: tx_removals, tx_additions, npc_res = await self.get_tx_removals_and_additions( fetched_full_block, npc_result) else: tx_removals, tx_additions, npc_res = await self.get_tx_removals_and_additions( fetched_full_block, None) assert fetched_full_block.foliage_transaction_block is not None added_rec = await self.coin_store.new_block( fetched_full_block.height, fetched_full_block.foliage_transaction_block.timestamp, fetched_full_block.get_included_reward_coins(), tx_additions, tx_removals, ) removed_rec: List[Optional[CoinRecord]] = [ await self.coin_store.get_coin_record(name) for name in tx_removals ] # Set additions first, then removals in order to handle ephemeral coin state # Add in height order is also required record: Optional[CoinRecord] for record in added_rec: assert record lastest_coin_state[record.name] = record for record in removed_rec: assert record lastest_coin_state[record.name] = record if npc_res is not None: hint_list: List[Tuple[ bytes32, bytes]] = self.get_hint_list(npc_res) await self.hint_store.add_hints(hint_list) # There can be multiple coins for the same hint for coin_id, hint in hint_list: key = hint if key not in hint_coin_state: hint_coin_state[key] = {} hint_coin_state[key][coin_id] = lastest_coin_state[ coin_id] await self.block_store.set_in_chain([(br.header_hash, ) for br in records_to_add]) # Changes the peak to be the new peak await self.block_store.set_peak(block_record.header_hash) return ( uint32(max(fork_height, 0)), block_record.height, records_to_add, (list(lastest_coin_state.values()), hint_coin_state), ) # This is not a heavier block than the heaviest we have seen, so we don't change the coin set return None, None, [], ([], {}) async def get_tx_removals_and_additions( self, block: FullBlock, npc_result: Optional[NPCResult] = None ) -> Tuple[List[bytes32], List[Coin], Optional[NPCResult]]: if block.is_transaction_block(): if block.transactions_generator is not None: if npc_result is None: block_generator: Optional[ BlockGenerator] = await self.get_block_generator(block) assert block_generator is not None npc_result = get_name_puzzle_conditions( block_generator, self.constants.MAX_BLOCK_COST_CLVM, cost_per_byte=self.constants.COST_PER_BYTE, mempool_mode=False, height=block.height, ) tx_removals, tx_additions = tx_removals_and_additions( npc_result.npc_list) return tx_removals, tx_additions, npc_result else: return [], [], None else: return [], [], None def get_next_difficulty(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.DIFFICULTY_STARTING return get_next_sub_slot_iters_and_difficulty(self.constants, new_slot, curr, self)[1] def get_next_slot_iters(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.SUB_SLOT_ITERS_STARTING return get_next_sub_slot_iters_and_difficulty(self.constants, new_slot, curr, self)[0] async def get_sp_and_ip_sub_slots( self, header_hash: bytes32 ) -> Optional[Tuple[Optional[EndOfSubSlotBundle], Optional[EndOfSubSlotBundle]]]: block: Optional[FullBlock] = await self.block_store.get_full_block( header_hash) if block is None: return None curr_br: BlockRecord = self.block_record(block.header_hash) is_overflow = curr_br.overflow curr: Optional[FullBlock] = block assert curr is not None while True: if curr_br.first_in_sub_slot: curr = await self.block_store.get_full_block( curr_br.header_hash) assert curr is not None break if curr_br.height == 0: break curr_br = self.block_record(curr_br.prev_hash) if len(curr.finished_sub_slots) == 0: # This means we got to genesis and still no sub-slots return None, None ip_sub_slot = curr.finished_sub_slots[-1] if not is_overflow: # Pos sub-slot is the same as infusion sub slot return None, ip_sub_slot if len(curr.finished_sub_slots) > 1: # Have both sub-slots return curr.finished_sub_slots[-2], ip_sub_slot prev_curr: Optional[FullBlock] = await self.block_store.get_full_block( curr.prev_header_hash) if prev_curr is None: assert curr.height == 0 prev_curr = curr prev_curr_br = self.block_record(curr.header_hash) else: prev_curr_br = self.block_record(curr.prev_header_hash) assert prev_curr_br is not None while prev_curr_br.height > 0: if prev_curr_br.first_in_sub_slot: prev_curr = await self.block_store.get_full_block( prev_curr_br.header_hash) assert prev_curr is not None break prev_curr_br = self.block_record(prev_curr_br.prev_hash) if len(prev_curr.finished_sub_slots) == 0: return None, ip_sub_slot return prev_curr.finished_sub_slots[-1], ip_sub_slot def get_recent_reward_challenges(self) -> List[Tuple[bytes32, uint128]]: peak = self.get_peak() if peak is None: return [] recent_rc: List[Tuple[bytes32, uint128]] = [] curr: Optional[BlockRecord] = peak while curr is not None and len( recent_rc) < 2 * self.constants.MAX_SUB_SLOT_BLOCKS: if curr != peak: recent_rc.append( (curr.reward_infusion_new_challenge, curr.total_iters)) if curr.first_in_sub_slot: assert curr.finished_reward_slot_hashes is not None sub_slot_total_iters = curr.ip_sub_slot_total_iters( self.constants) # Start from the most recent for rc in reversed(curr.finished_reward_slot_hashes): if sub_slot_total_iters < curr.sub_slot_iters: break recent_rc.append((rc, sub_slot_total_iters)) sub_slot_total_iters = uint128(sub_slot_total_iters - curr.sub_slot_iters) curr = self.try_block_record(curr.prev_hash) return list(reversed(recent_rc)) async def validate_unfinished_block( self, block: UnfinishedBlock, npc_result: Optional[NPCResult], skip_overflow_ss_validation=True) -> PreValidationResult: if (not self.contains_block(block.prev_header_hash) and not block.prev_header_hash == self.constants.GENESIS_CHALLENGE): return PreValidationResult( uint16(Err.INVALID_PREV_BLOCK_HASH.value), None, None, False) unfinished_header_block = UnfinishedHeaderBlock( block.finished_sub_slots, block.reward_chain_block, block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage, block.foliage_transaction_block, b"", ) prev_b = self.try_block_record( unfinished_header_block.prev_header_hash) sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty( self.constants, len(unfinished_header_block.finished_sub_slots) > 0, prev_b, self) required_iters, error = validate_unfinished_header_block( self.constants, self, unfinished_header_block, False, difficulty, sub_slot_iters, skip_overflow_ss_validation, ) if error is not None: return PreValidationResult(uint16(error.code.value), None, None, False) prev_height = (-1 if block.prev_header_hash == self.constants.GENESIS_CHALLENGE else self.block_record(block.prev_header_hash).height) error_code, cost_result = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, uint32(prev_height + 1), npc_result, None, self.get_block_generator, validate_signature= False, # Signature was already validated before calling this method, no need to validate ) if error_code is not None: return PreValidationResult(uint16(error_code.value), None, None, False) return PreValidationResult(None, required_iters, cost_result, False) async def pre_validate_blocks_multiprocessing( self, blocks: List[FullBlock], npc_results: Dict[ uint32, NPCResult], # A cache of the result of running CLVM, optional (you can use {}) batch_size: int = 4, wp_summaries: Optional[List[SubEpochSummary]] = None, *, validate_signatures: bool, ) -> List[PreValidationResult]: return await pre_validate_blocks_multiprocessing( self.constants, self.constants_json, self, blocks, self.pool, True, npc_results, self.get_block_generator, batch_size, wp_summaries, validate_signatures=validate_signatures, ) async def run_generator(self, unfinished_block: bytes, generator: BlockGenerator, height: uint32) -> NPCResult: task = asyncio.get_running_loop().run_in_executor( self.pool, _run_generator, self.constants_json, unfinished_block, bytes(generator), height, ) npc_result_bytes = await task if npc_result_bytes is None: raise ConsensusError(Err.UNKNOWN) ret = NPCResult.from_bytes(npc_result_bytes) if ret.error is not None: raise ConsensusError(ret.error) return ret def contains_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory. """ return header_hash in self.__block_records def block_record(self, header_hash: bytes32) -> BlockRecord: return self.__block_records[header_hash] def height_to_block_record(self, height: uint32) -> BlockRecord: header_hash = self.height_to_hash(height) # TODO: address hint error and remove ignore # error: Argument 1 to "block_record" of "Blockchain" has incompatible type "Optional[bytes32]"; expected # "bytes32" [arg-type] return self.block_record(header_hash) # type: ignore[arg-type] def get_ses_heights(self) -> List[uint32]: return self.__height_map.get_ses_heights() def get_ses(self, height: uint32) -> SubEpochSummary: return self.__height_map.get_ses(height) def height_to_hash(self, height: uint32) -> Optional[bytes32]: return self.__height_map.get_hash(height) def contains_height(self, height: uint32) -> bool: return self.__height_map.contains_height(height) def get_peak_height(self) -> Optional[uint32]: return self._peak_height async def warmup(self, fork_point: uint32): """ Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last block height to load in the cache """ if self._peak_height is None: return None block_records = await self.block_store.get_block_records_in_range( max(fork_point - self.constants.BLOCKS_CACHE_SIZE, uint32(0)), fork_point) for block_record in block_records.values(): self.add_block_record(block_record) def clean_block_record(self, height: int): """ Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return None blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) while blocks_to_remove is not None and height >= 0: for header_hash in blocks_to_remove: del self.__block_records[header_hash] # remove from blocks del self.__heights_in_cache[uint32( height)] # remove height from heights in cache if height == 0: break height = height - 1 blocks_to_remove = self.__heights_in_cache.get( uint32(height), None) def clean_block_records(self): """ Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__block_records) < self.constants.BLOCKS_CACHE_SIZE: return None assert self._peak_height is not None if self._peak_height - self.constants.BLOCKS_CACHE_SIZE < 0: return None self.clean_block_record(self._peak_height - self.constants.BLOCKS_CACHE_SIZE) async def get_block_records_in_range( self, start: int, stop: int) -> Dict[bytes32, BlockRecord]: return await self.block_store.get_block_records_in_range(start, stop) async def get_header_blocks_in_range( self, start: int, stop: int, tx_filter: bool = True) -> Dict[bytes32, HeaderBlock]: hashes = [] for height in range(start, stop + 1): if self.contains_height(uint32(height)): # TODO: address hint error and remove ignore # error: Incompatible types in assignment (expression has type "Optional[bytes32]", variable has # type "bytes32") [assignment] header_hash: bytes32 = self.height_to_hash( uint32(height)) # type: ignore[assignment] hashes.append(header_hash) blocks: List[FullBlock] = [] for hash in hashes.copy(): block = self.block_store.block_cache.get(hash) if block is not None: blocks.append(block) hashes.remove(hash) blocks_on_disk: List[ FullBlock] = await self.block_store.get_blocks_by_hash(hashes) blocks.extend(blocks_on_disk) header_blocks: Dict[bytes32, HeaderBlock] = {} for block in blocks: if self.height_to_hash(block.height) != block.header_hash: raise ValueError( f"Block at {block.header_hash} is no longer in the blockchain (it's in a fork)" ) if tx_filter is False: header = get_block_header(block, [], []) else: tx_additions: List[CoinRecord] = [ c for c in (await self.coin_store.get_coins_added_at_height( block.height)) if not c.coinbase ] removed: List[ CoinRecord] = await self.coin_store.get_coins_removed_at_height( block.height) header = get_block_header( block, [record.coin for record in tx_additions], [record.coin.name() for record in removed]) header_blocks[header.header_hash] = header return header_blocks async def get_header_block_by_height( self, height: int, header_hash: bytes32, tx_filter: bool = True) -> Optional[HeaderBlock]: header_dict: Dict[bytes32, HeaderBlock] = await self.get_header_blocks_in_range( height, height, tx_filter) if len(header_dict) == 0: return None if header_hash not in header_dict: return None return header_dict[header_hash] async def get_block_records_at(self, heights: List[uint32], batch_size=900) -> List[BlockRecord]: """ gets block records by height (only blocks that are part of the chain) """ records: List[BlockRecord] = [] hashes = [] assert batch_size < 999 # sqlite in python 3.7 has a limit on 999 variables in queries for height in heights: hashes.append(self.height_to_hash(height)) if len(hashes) > batch_size: # TODO: address hint error and remove ignore # error: Argument 1 to "get_block_records_by_hash" of "BlockStore" has incompatible type # "List[Optional[bytes32]]"; expected "List[bytes32]" [arg-type] res = await self.block_store.get_block_records_by_hash( hashes) # type: ignore[arg-type] records.extend(res) hashes = [] if len(hashes) > 0: # TODO: address hint error and remove ignore # error: Argument 1 to "get_block_records_by_hash" of "BlockStore" has incompatible type # "List[Optional[bytes32]]"; expected "List[bytes32]" [arg-type] res = await self.block_store.get_block_records_by_hash( hashes) # type: ignore[arg-type] records.extend(res) return records async def get_block_record_from_db( self, header_hash: bytes32) -> Optional[BlockRecord]: if header_hash in self.__block_records: return self.__block_records[header_hash] return await self.block_store.get_block_record(header_hash) def remove_block_record(self, header_hash: bytes32): sbr = self.block_record(header_hash) del self.__block_records[header_hash] self.__heights_in_cache[sbr.height].remove(header_hash) def add_block_record(self, block_record: BlockRecord): """ Adds a block record to the cache. """ self.__block_records[block_record.header_hash] = block_record if block_record.height not in self.__heights_in_cache.keys(): self.__heights_in_cache[block_record.height] = set() self.__heights_in_cache[block_record.height].add( block_record.header_hash) async def persist_sub_epoch_challenge_segments( self, ses_block_hash: bytes32, segments: List[SubEpochChallengeSegment]): return await self.block_store.persist_sub_epoch_challenge_segments( ses_block_hash, segments) async def get_sub_epoch_challenge_segments( self, ses_block_hash: bytes32, ) -> Optional[List[SubEpochChallengeSegment]]: segments: Optional[List[ SubEpochChallengeSegment]] = await self.block_store.get_sub_epoch_challenge_segments( ses_block_hash) if segments is None: return None return segments # Returns 'True' if the info is already in the set, otherwise returns 'False' and stores it. def seen_compact_proofs(self, vdf_info: VDFInfo, height: uint32) -> bool: pot_tuple = (vdf_info, height) if pot_tuple in self._seen_compact_proofs: return True # Periodically cleanup to keep size small. TODO: make this smarter, like FIFO. if len(self._seen_compact_proofs) > 10000: self._seen_compact_proofs.clear() self._seen_compact_proofs.add(pot_tuple) return False async def get_block_generator( self, block: Union[FullBlock, UnfinishedBlock], additional_blocks=None) -> Optional[BlockGenerator]: if additional_blocks is None: additional_blocks = {} ref_list = block.transactions_generator_ref_list if block.transactions_generator is None: assert len(ref_list) == 0 return None if len(ref_list) == 0: return BlockGenerator(block.transactions_generator, [], []) result: List[SerializedProgram] = [] previous_block_hash = block.prev_header_hash if (self.try_block_record(previous_block_hash) and self.height_to_hash( self.block_record(previous_block_hash).height) == previous_block_hash): # We are not in a reorg, no need to look up alternate header hashes # (we can get them from height_to_hash) for ref_height in block.transactions_generator_ref_list: header_hash = self.height_to_hash(ref_height) # if ref_height is invalid, this block should have failed with # FUTURE_GENERATOR_REFS before getting here assert header_hash is not None ref_block = await self.block_store.get_full_block(header_hash) assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(ref_block.transactions_generator) else: # First tries to find the blocks in additional_blocks reorg_chain: Dict[uint32, FullBlock] = {} curr: Union[FullBlock, UnfinishedBlock] = block additional_height_dict = {} while curr.prev_header_hash in additional_blocks: prev: FullBlock = additional_blocks[curr.prev_header_hash] additional_height_dict[prev.height] = prev if isinstance(curr, FullBlock): assert curr.height == prev.height + 1 reorg_chain[prev.height] = prev curr = prev peak: Optional[BlockRecord] = self.get_peak() if self.contains_block(curr.prev_header_hash) and peak is not None: # Then we look up blocks up to fork point one at a time, backtracking previous_block_hash = curr.prev_header_hash prev_block_record = await self.block_store.get_block_record( previous_block_hash) prev_block = await self.block_store.get_full_block( previous_block_hash) assert prev_block is not None assert prev_block_record is not None fork = find_fork_point_in_chain(self, peak, prev_block_record) curr_2: Optional[FullBlock] = prev_block assert curr_2 is not None and isinstance(curr_2, FullBlock) reorg_chain[curr_2.height] = curr_2 while curr_2.height > fork and curr_2.height > 0: curr_2 = await self.block_store.get_full_block( curr_2.prev_header_hash) assert curr_2 is not None reorg_chain[curr_2.height] = curr_2 for ref_height in block.transactions_generator_ref_list: if ref_height in reorg_chain: ref_block = reorg_chain[ref_height] assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(ref_block.transactions_generator) else: if ref_height in additional_height_dict: ref_block = additional_height_dict[ref_height] else: header_hash = self.height_to_hash(ref_height) # TODO: address hint error and remove ignore # error: Argument 1 to "get_full_block" of "Blockchain" has incompatible type # "Optional[bytes32]"; expected "bytes32" [arg-type] ref_block = await self.get_full_block( header_hash) # type: ignore[arg-type] assert ref_block is not None if ref_block.transactions_generator is None: raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) result.append(ref_block.transactions_generator) assert len(result) == len(ref_list) return BlockGenerator(block.transactions_generator, result, [])
class MempoolManager: def __init__(self, coin_store: CoinStore, consensus_constants: ConsensusConstants): self.constants: ConsensusConstants = consensus_constants self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) # Keep track of seen spend_bundles self.seen_bundle_hashes: Dict[bytes32, bytes32] = {} self.coin_store = coin_store self.lock = asyncio.Lock() # The fee per cost must be above this amount to consider the fee "nonzero", and thus able to kick out other # transactions. This prevents spam. This is equivalent to 0.055 XCH per block, or about 0.00005 XCH for two # spends. self.nonzero_fee_minimum_fpc = 5 self.limit_factor = 0.5 self.mempool_max_total_cost = int(self.constants.MAX_BLOCK_COST_CLVM * self.constants.MEMPOOL_BLOCK_BUFFER) # Transactions that were unable to enter mempool, used for retry. (they were invalid) self.potential_cache = PendingTxCache( self.constants.MAX_BLOCK_COST_CLVM * 1) self.seen_cache_size = 10000 self.pool = ProcessPoolExecutor(max_workers=2) # The mempool will correspond to a certain peak self.peak: Optional[BlockRecord] = None self.mempool: Mempool = Mempool(self.mempool_max_total_cost) def shut_down(self): self.pool.shutdown(wait=True) async def create_bundle_from_mempool( self, last_tb_header_hash: bytes32 ) -> Optional[Tuple[SpendBundle, List[Coin], List[Coin]]]: """ Returns aggregated spendbundle that can be used for creating new block, additions and removals in that spend_bundle """ if self.peak is None or self.peak.header_hash != last_tb_header_hash: return None cost_sum = 0 # Checks that total cost does not exceed block maximum fee_sum = 0 # Checks that total fees don't exceed 64 bits spend_bundles: List[SpendBundle] = [] removals = [] additions = [] broke_from_inner_loop = False log.info( f"Starting to make block, max cost: {self.constants.MAX_BLOCK_COST_CLVM}" ) for dic in reversed(self.mempool.sorted_spends.values()): if broke_from_inner_loop: break for item in dic.values(): log.info( f"Cumulative cost: {cost_sum}, fee per cost: {item.fee / item.cost}" ) if (item.cost + cost_sum <= self.limit_factor * self.constants.MAX_BLOCK_COST_CLVM and item.fee + fee_sum <= self.constants.MAX_COIN_AMOUNT): spend_bundles.append(item.spend_bundle) cost_sum += item.cost fee_sum += item.fee removals.extend(item.removals) additions.extend(item.additions) else: broke_from_inner_loop = True break if len(spend_bundles) > 0: log.info( f"Cumulative cost of block (real cost should be less) {cost_sum}. Proportion " f"full: {cost_sum / self.constants.MAX_BLOCK_COST_CLVM}") agg = SpendBundle.aggregate(spend_bundles) return agg, additions, removals else: return None def get_filter(self) -> bytes: all_transactions: Set[bytes32] = set() byte_array_list = [] for key, _ in self.mempool.spends.items(): if key not in all_transactions: all_transactions.add(key) byte_array_list.append(bytearray(key)) tx_filter: PyBIP158 = PyBIP158(byte_array_list) return bytes(tx_filter.GetEncoded()) def is_fee_enough(self, fees: uint64, cost: uint64) -> bool: """ Determines whether any of the pools can accept a transaction with a given fees and cost. """ if cost == 0: return False fees_per_cost = fees / cost if not self.mempool.at_full_capacity(cost) or ( fees_per_cost >= self.nonzero_fee_minimum_fpc and fees_per_cost > self.mempool.get_min_fee_rate(cost)): return True return False def add_and_maybe_pop_seen(self, spend_name: bytes32): self.seen_bundle_hashes[spend_name] = spend_name while len(self.seen_bundle_hashes) > self.seen_cache_size: first_in = list(self.seen_bundle_hashes.keys())[0] self.seen_bundle_hashes.pop(first_in) def seen(self, bundle_hash: bytes32) -> bool: """Return true if we saw this spendbundle recently""" return bundle_hash in self.seen_bundle_hashes def remove_seen(self, bundle_hash: bytes32): if bundle_hash in self.seen_bundle_hashes: self.seen_bundle_hashes.pop(bundle_hash) @staticmethod def get_min_fee_increase() -> int: # 0.00001 XCH return 10000000 def can_replace( self, conflicting_items: Dict[bytes32, MempoolItem], removals: Dict[bytes32, CoinRecord], fees: uint64, fees_per_cost: float, ) -> bool: conflicting_fees = 0 conflicting_cost = 0 for item in conflicting_items.values(): conflicting_fees += item.fee conflicting_cost += item.cost # All coins spent in all conflicting items must also be spent in the new item. (superset rule). This is # important because otherwise there exists an attack. A user spends coin A. An attacker replaces the # bundle with AB with a higher fee. An attacker then replaces the bundle with just B with a higher # fee than AB therefore kicking out A altogether. The better way to solve this would be to keep a cache # of booted transactions like A, and retry them after they get removed from mempool due to a conflict. for coin in item.removals: if coin.name() not in removals: log.debug( f"Rejecting conflicting tx as it does not spend conflicting coin {coin.name()}" ) return False # New item must have higher fee per cost conflicting_fees_per_cost = conflicting_fees / conflicting_cost if fees_per_cost <= conflicting_fees_per_cost: log.debug( f"Rejecting conflicting tx due to not increasing fees per cost " f"({fees_per_cost} <= {conflicting_fees_per_cost})") return False # New item must increase the total fee at least by a certain amount fee_increase = fees - conflicting_fees if fee_increase < self.get_min_fee_increase(): log.debug( f"Rejecting conflicting tx due to low fee increase ({fee_increase})" ) return False log.info( f"Replacing conflicting tx in mempool. New tx fee: {fees}, old tx fees: {conflicting_fees}" ) return True async def pre_validate_spendbundle(self, new_spend: SpendBundle, new_spend_bytes: Optional[bytes], spend_name: bytes32) -> NPCResult: """ Errors are included within the cached_result. This runs in another process so we don't block the main thread """ start_time = time.time() if new_spend_bytes is None: new_spend_bytes = bytes(new_spend) err, cached_result_bytes, new_cache_entries = await asyncio.get_running_loop( ).run_in_executor( self.pool, validate_clvm_and_signature, new_spend_bytes, int(self.limit_factor * self.constants.MAX_BLOCK_COST_CLVM), self.constants.COST_PER_BYTE, self.constants.AGG_SIG_ME_ADDITIONAL_DATA, ) if err is not None: raise ValidationError(err) for cache_entry_key, cached_entry_value in new_cache_entries.items(): LOCAL_CACHE.put(cache_entry_key, GTElement.from_bytes(cached_entry_value)) ret = NPCResult.from_bytes(cached_result_bytes) end_time = time.time() log.debug( f"pre_validate_spendbundle took {end_time - start_time:0.4f} seconds for {spend_name}" ) return ret async def add_spendbundle( self, new_spend: SpendBundle, npc_result: NPCResult, spend_name: bytes32, program: Optional[SerializedProgram] = None, ) -> Tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]: """ Tries to add spend bundle to the mempool Returns the cost (if SUCCESS), the result (MempoolInclusion status), and an optional error """ start_time = time.time() if self.peak is None: return None, MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_INITIALIZED npc_list = npc_result.npc_list assert npc_result.error is None if program is None: program = simple_solution_generator(new_spend).program cost = calculate_cost_of_program(program, npc_result, self.constants.COST_PER_BYTE) log.debug(f"Cost: {cost}") if cost > int(self.limit_factor * self.constants.MAX_BLOCK_COST_CLVM): # we shouldn't ever end up here, since the cost is limited when we # execute the CLVM program. return None, MempoolInclusionStatus.FAILED, Err.BLOCK_COST_EXCEEDS_MAX # build removal list removal_names: List[bytes32] = [npc.coin_name for npc in npc_list] if set(removal_names) != set([s.name() for s in new_spend.removals()]): return None, MempoolInclusionStatus.FAILED, Err.INVALID_SPEND_BUNDLE additions = additions_for_npc(npc_list) additions_dict: Dict[bytes32, Coin] = {} for add in additions: additions_dict[add.name()] = add addition_amount = uint64(0) # Check additions for max coin amount for coin in additions: if coin.amount < 0: return ( None, MempoolInclusionStatus.FAILED, Err.COIN_AMOUNT_NEGATIVE, ) if coin.amount > self.constants.MAX_COIN_AMOUNT: return ( None, MempoolInclusionStatus.FAILED, Err.COIN_AMOUNT_EXCEEDS_MAXIMUM, ) addition_amount = uint64(addition_amount + coin.amount) # Check for duplicate outputs addition_counter = collections.Counter(_.name() for _ in additions) for k, v in addition_counter.items(): if v > 1: return None, MempoolInclusionStatus.FAILED, Err.DUPLICATE_OUTPUT # Check for duplicate inputs removal_counter = collections.Counter(name for name in removal_names) for k, v in removal_counter.items(): if v > 1: return None, MempoolInclusionStatus.FAILED, Err.DOUBLE_SPEND # Skip if already added if spend_name in self.mempool.spends: return uint64(cost), MempoolInclusionStatus.SUCCESS, None removal_record_dict: Dict[bytes32, CoinRecord] = {} removal_coin_dict: Dict[bytes32, Coin] = {} removal_amount = uint64(0) for name in removal_names: removal_record = await self.coin_store.get_coin_record(name) if removal_record is None and name not in additions_dict: return None, MempoolInclusionStatus.FAILED, Err.UNKNOWN_UNSPENT elif name in additions_dict: removal_coin = additions_dict[name] # TODO(straya): what timestamp to use here? assert self.peak.timestamp is not None removal_record = CoinRecord( removal_coin, uint32( self.peak.height + 1), # In mempool, so will be included in next height uint32(0), False, uint64(self.peak.timestamp + 1), ) assert removal_record is not None removal_amount = uint64(removal_amount + removal_record.coin.amount) removal_record_dict[name] = removal_record removal_coin_dict[name] = removal_record.coin removals: List[Coin] = [coin for coin in removal_coin_dict.values()] if addition_amount > removal_amount: print(addition_amount, removal_amount) return None, MempoolInclusionStatus.FAILED, Err.MINTING_COIN fees = uint64(removal_amount - addition_amount) assert_fee_sum: uint64 = uint64(0) for npc in npc_list: if ConditionOpcode.RESERVE_FEE in npc.condition_dict: fee_list: List[ConditionWithArgs] = npc.condition_dict[ ConditionOpcode.RESERVE_FEE] for cvp in fee_list: fee = int_from_bytes(cvp.vars[0]) if fee < 0: return None, MempoolInclusionStatus.FAILED, Err.RESERVE_FEE_CONDITION_FAILED assert_fee_sum = assert_fee_sum + fee if fees < assert_fee_sum: return ( None, MempoolInclusionStatus.FAILED, Err.RESERVE_FEE_CONDITION_FAILED, ) if cost == 0: return None, MempoolInclusionStatus.FAILED, Err.UNKNOWN fees_per_cost: float = fees / cost # If pool is at capacity check the fee, if not then accept even without the fee if self.mempool.at_full_capacity(cost): if fees_per_cost < self.nonzero_fee_minimum_fpc: return None, MempoolInclusionStatus.FAILED, Err.INVALID_FEE_TOO_CLOSE_TO_ZERO if fees_per_cost <= self.mempool.get_min_fee_rate(cost): return None, MempoolInclusionStatus.FAILED, Err.INVALID_FEE_LOW_FEE # Check removals against UnspentDB + DiffStore + Mempool + SpendBundle # Use this information later when constructing a block fail_reason, conflicts = await self.check_removals(removal_record_dict) # If there is a mempool conflict check if this spendbundle has a higher fee per cost than all others tmp_error: Optional[Err] = None conflicting_pool_items: Dict[bytes32, MempoolItem] = {} if fail_reason is Err.MEMPOOL_CONFLICT: for conflicting in conflicts: sb: MempoolItem = self.mempool.removals[conflicting.name()] conflicting_pool_items[sb.name] = sb if not self.can_replace(conflicting_pool_items, removal_record_dict, fees, fees_per_cost): potential = MempoolItem(new_spend, uint64(fees), npc_result, cost, spend_name, additions, removals, program) self.potential_cache.add(potential) return ( uint64(cost), MempoolInclusionStatus.PENDING, Err.MEMPOOL_CONFLICT, ) elif fail_reason: return None, MempoolInclusionStatus.FAILED, fail_reason if tmp_error: return None, MempoolInclusionStatus.FAILED, tmp_error # Verify conditions, create hash_key list for aggsig check error: Optional[Err] = None for npc in npc_list: coin_record: CoinRecord = removal_record_dict[npc.coin_name] # Check that the revealed removal puzzles actually match the puzzle hash if npc.puzzle_hash != coin_record.coin.puzzle_hash: log.warning( "Mempool rejecting transaction because of wrong puzzle_hash" ) log.warning( f"{npc.puzzle_hash} != {coin_record.coin.puzzle_hash}") return None, MempoolInclusionStatus.FAILED, Err.WRONG_PUZZLE_HASH chialisp_height = (self.peak.prev_transaction_block_height if not self.peak.is_transaction_block else self.peak.height) assert self.peak.timestamp is not None error = mempool_check_conditions_dict( coin_record, npc.condition_dict, uint32(chialisp_height), self.peak.timestamp, ) if error: if error is Err.ASSERT_HEIGHT_ABSOLUTE_FAILED or error is Err.ASSERT_HEIGHT_RELATIVE_FAILED: potential = MempoolItem(new_spend, uint64(fees), npc_result, cost, spend_name, additions, removals, program) self.potential_cache.add(potential) return uint64(cost), MempoolInclusionStatus.PENDING, error break if error: return None, MempoolInclusionStatus.FAILED, error # Remove all conflicting Coins and SpendBundles if fail_reason: mempool_item: MempoolItem for mempool_item in conflicting_pool_items.values(): self.mempool.remove_from_pool(mempool_item) new_item = MempoolItem(new_spend, uint64(fees), npc_result, cost, spend_name, additions, removals, program) self.mempool.add_to_pool(new_item) now = time.time() log.log( logging.DEBUG, f"add_spendbundle {spend_name} took {now - start_time:0.2f} seconds. " f"Cost: {cost} ({round(100.0 * cost/self.constants.MAX_BLOCK_COST_CLVM, 3)}% of max block cost)", ) return uint64(cost), MempoolInclusionStatus.SUCCESS, None async def check_removals( self, removals: Dict[bytes32, CoinRecord]) -> Tuple[Optional[Err], List[Coin]]: """ This function checks for double spends, unknown spends and conflicting transactions in mempool. Returns Error (if any), dictionary of Unspents, list of coins with conflict errors (if any any). Note that additions are not checked for duplicates, because having duplicate additions requires also having duplicate removals. """ assert self.peak is not None conflicts: List[Coin] = [] for record in removals.values(): removal = record.coin # 1. Checks if it's been spent already if record.spent == 1: return Err.DOUBLE_SPEND, [] # 2. Checks if there's a mempool conflict if removal.name() in self.mempool.removals: conflicts.append(removal) if len(conflicts) > 0: return Err.MEMPOOL_CONFLICT, conflicts # 5. If coins can be spent return list of unspents as we see them in local storage return None, [] def get_spendbundle(self, bundle_hash: bytes32) -> Optional[SpendBundle]: """Returns a full SpendBundle if it's inside one the mempools""" if bundle_hash in self.mempool.spends: return self.mempool.spends[bundle_hash].spend_bundle return None def get_mempool_item(self, bundle_hash: bytes32) -> Optional[MempoolItem]: """Returns a MempoolItem if it's inside one the mempools""" if bundle_hash in self.mempool.spends: return self.mempool.spends[bundle_hash] return None async def new_peak( self, new_peak: Optional[BlockRecord], coin_changes: List[CoinRecord] ) -> List[Tuple[SpendBundle, NPCResult, bytes32]]: """ Called when a new peak is available, we try to recreate a mempool for the new tip. """ if new_peak is None: return [] if new_peak.is_transaction_block is False: return [] if self.peak == new_peak: return [] assert new_peak.timestamp is not None use_optimization: bool = self.peak is not None and new_peak.prev_transaction_block_hash == self.peak.header_hash self.peak = new_peak if use_optimization: # We don't reinitialize a mempool, just kick removed items for coin_record in coin_changes: if coin_record.name in self.mempool.removals: item = self.mempool.removals[coin_record.name] self.mempool.remove_from_pool(item) self.remove_seen(item.spend_bundle_name) else: old_pool = self.mempool self.mempool = Mempool(self.mempool_max_total_cost) for item in old_pool.spends.values(): _, result, _ = await self.add_spendbundle( item.spend_bundle, item.npc_result, item.spend_bundle_name, item.program) # If the spend bundle was confirmed or conflicting (can no longer be in mempool), it won't be # successfully added to the new mempool. In this case, remove it from seen, so in the case of a reorg, # it can be resubmitted if result != MempoolInclusionStatus.SUCCESS: self.remove_seen(item.spend_bundle_name) potential_txs = self.potential_cache.drain() txs_added = [] for item in potential_txs.values(): cost, status, error = await self.add_spendbundle( item.spend_bundle, item.npc_result, item.spend_bundle_name, program=item.program) if status == MempoolInclusionStatus.SUCCESS: txs_added.append((item.spend_bundle, item.npc_result, item.spend_bundle_name)) log.info( f"Size of mempool: {len(self.mempool.spends)} spends, cost: {self.mempool.total_mempool_cost} " f"minimum fee to get in: {self.mempool.get_min_fee_rate(100000)}") return txs_added async def get_items_not_in_filter(self, mempool_filter: PyBIP158, limit: int = 100) -> List[MempoolItem]: items: List[MempoolItem] = [] counter = 0 broke_from_inner_loop = False # Send 100 with highest fee per cost for dic in self.mempool.sorted_spends.values(): if broke_from_inner_loop: break for item in dic.values(): if counter == limit: broke_from_inner_loop = True break if mempool_filter.Match(bytearray(item.spend_bundle_name)): continue items.append(item) counter += 1 return items
class Blockchain(BlockchainInterface): constants: ConsensusConstants constants_json: Dict # peak of the blockchain _peak_height: Optional[uint32] # All blocks in peak path are guaranteed to be included, can include orphan blocks __block_records: Dict[bytes32, BlockRecord] # all hashes of blocks in block_record by height, used for garbage collection __heights_in_cache: Dict[uint32, Set[bytes32]] # Defines the path from genesis to the peak, no orphan blocks __height_to_hash: Dict[uint32, bytes32] # All sub-epoch summaries that have been included in the blockchain from the beginning until and including the peak # (height_included, SubEpochSummary). Note: ONLY for the blocks in the path to the peak __sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {} # Unspent Store coin_store: CoinStore # Store block_store: BlockStore # Used to verify blocks in parallel pool: ProcessPoolExecutor # Whether blockchain is shut down or not _shut_down: bool # Lock to prevent simultaneous reads and writes lock: asyncio.Lock @staticmethod async def create( coin_store: CoinStore, block_store: BlockStore, consensus_constants: ConsensusConstants, ): """ Initializes a blockchain with the BlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config. """ self = Blockchain() self.lock = asyncio.Lock() # External lock handled by full node cpu_count = multiprocessing.cpu_count() if cpu_count > 61: cpu_count = 61 # Windows Server 2016 has an issue https://bugs.python.org/issue26903 num_workers = max(cpu_count - 2, 1) self.pool = ProcessPoolExecutor(max_workers=num_workers) log.info(f"Started {num_workers} processes for block validation") self.constants = consensus_constants self.coin_store = coin_store self.block_store = block_store self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) self._shut_down = False await self._load_chain_from_store() return self def shut_down(self): self._shut_down = True self.pool.shutdown(wait=True) async def _load_chain_from_store(self) -> None: """ Initializes the state of the Blockchain class from the database. """ height_to_hash, sub_epoch_summaries = await self.block_store.get_peak_height_dicts( ) self.__height_to_hash = height_to_hash self.__sub_epoch_summaries = sub_epoch_summaries self.__block_records = {} self.__heights_in_cache = {} block_records, peak = await self.block_store.get_block_records_close_to_peak( self.constants.BLOCKS_CACHE_SIZE) for block in block_records.values(): self.add_block_record(block) if len(block_records) == 0: assert peak is None self._peak_height = None return assert peak is not None self._peak_height = self.block_record(peak).height assert len(self.__height_to_hash) == self._peak_height + 1 def get_peak(self) -> Optional[BlockRecord]: """ Return the peak of the blockchain """ if self._peak_height is None: return None return self.height_to_block_record(self._peak_height) async def get_full_peak(self) -> Optional[FullBlock]: if self._peak_height is None: return None """ Return list of FullBlocks that are peaks""" block = await self.block_store.get_full_block( self.height_to_hash(self._peak_height)) assert block is not None return block def is_child_of_peak(self, block: UnfinishedBlock) -> bool: """ True if the block is the direct ancestor of the peak """ peak = self.get_peak() if peak is None: return False return block.prev_header_hash == peak.header_hash async def get_full_block(self, header_hash: bytes32) -> Optional[FullBlock]: return await self.block_store.get_full_block(header_hash) async def receive_block( self, block: FullBlock, pre_validation_result: Optional[PreValidationResult] = None, fork_point_with_peak: Optional[uint32] = None, ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32]]: """ This method must be called under the blockchain lock Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case of a new peak. """ genesis: bool = block.height == 0 if self.contains_block(block.header_hash): return ReceiveBlockResult.ALREADY_HAVE_BLOCK, None, None if not self.contains_block(block.prev_header_hash) and not genesis: return ( ReceiveBlockResult.DISCONNECTED_BLOCK, Err.INVALID_PREV_BLOCK_HASH, None, ) if pre_validation_result is None: if block.height == 0: prev_b: Optional[BlockRecord] = None else: prev_b = self.block_record(block.prev_header_hash) sub_slot_iters, difficulty = get_sub_slot_iters_and_difficulty( self.constants, block, prev_b, self) required_iters, error = validate_finished_header_block( self.constants, self, block.get_block_header(), False, difficulty, sub_slot_iters, ) if error is not None: return ReceiveBlockResult.INVALID_BLOCK, error.code, None else: required_iters = pre_validation_result.required_iters assert pre_validation_result.error is None assert required_iters is not None error_code, _ = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, block.height, pre_validation_result.cost_result if pre_validation_result is not None else None, fork_point_with_peak, ) if error_code is not None: return ReceiveBlockResult.INVALID_BLOCK, error_code, None block_record = block_to_block_record( self.constants, self, required_iters, block, None, ) # Always add the block to the database await self.block_store.add_full_block(block, block_record) self.add_block_record(block_record) fork_height: Optional[uint32] = await self._reconsider_peak( block_record, genesis, fork_point_with_peak) if fork_height is not None: return ReceiveBlockResult.NEW_PEAK, None, fork_height else: return ReceiveBlockResult.ADDED_AS_ORPHAN, None, None async def _reconsider_peak( self, block_record: BlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32]) -> Optional[uint32]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there was no update to the heaviest chain. """ peak = self.get_peak() if genesis: if peak is None: block: Optional[ FullBlock] = await self.block_store.get_full_block( block_record.header_hash) assert block is not None # Begins a transaction, because we want to ensure that the coin store and block store are only updated # in sync. await self.block_store.begin_transaction() try: await self.coin_store.new_block(block) self.__height_to_hash[uint32(0)] = block.header_hash self._peak_height = uint32(0) await self.block_store.set_peak(block.header_hash) await self.block_store.commit_transaction() except Exception: await self.block_store.rollback_transaction() raise return uint32(0) return None assert peak is not None if block_record.weight > peak.weight: # Find the fork. if the block is just being appended, it will return the peak # If no blocks in common, returns -1, and reverts all blocks if fork_point_with_peak is not None: fork_height: int = fork_point_with_peak else: fork_height = find_fork_point_in_chain(self, block_record, peak) # Begins a transaction, because we want to ensure that the coin store and block store are only updated # in sync. await self.block_store.begin_transaction() try: # Rollback to fork await self.coin_store.rollback_to_block(fork_height) # Rollback sub_epoch_summaries heights_to_delete = [] for ses_included_height in self.__sub_epoch_summaries.keys(): if ses_included_height > fork_height: heights_to_delete.append(ses_included_height) for height in heights_to_delete: log.info(f"delete ses at height {height}") del self.__sub_epoch_summaries[height] if len(heights_to_delete) > 0: # remove segments from prev fork log.info(f"remove segments for se above {fork_height}") await self.block_store.delete_sub_epoch_challenge_segments( uint32(fork_height)) # Collect all blocks from fork point to new peak blocks_to_add: List[Tuple[FullBlock, BlockRecord]] = [] curr = block_record.header_hash while fork_height < 0 or curr != self.height_to_hash( uint32(fork_height)): fetched_full_block: Optional[ FullBlock] = await self.block_store.get_full_block(curr ) fetched_block_record: Optional[ BlockRecord] = await self.block_store.get_block_record( curr) assert fetched_full_block is not None assert fetched_block_record is not None blocks_to_add.append( (fetched_full_block, fetched_block_record)) if fetched_full_block.height == 0: # Doing a full reorg, starting at height 0 break curr = fetched_block_record.prev_hash for fetched_full_block, fetched_block_record in reversed( blocks_to_add): self.__height_to_hash[ fetched_block_record. height] = fetched_block_record.header_hash if fetched_block_record.is_transaction_block: await self.coin_store.new_block(fetched_full_block) if fetched_block_record.sub_epoch_summary_included is not None: self.__sub_epoch_summaries[ fetched_block_record. height] = fetched_block_record.sub_epoch_summary_included # Changes the peak to be the new peak await self.block_store.set_peak(block_record.header_hash) self._peak_height = block_record.height await self.block_store.commit_transaction() except Exception: await self.block_store.rollback_transaction() raise return uint32(max(fork_height, 0)) # This is not a heavier block than the heaviest we have seen, so we don't change the coin set return None def get_next_difficulty(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.DIFFICULTY_STARTING return get_next_difficulty( self.constants, self, header_hash, curr.height, uint64(curr.weight - self.block_record(curr.prev_hash).weight), curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) def get_next_slot_iters(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_block(header_hash) curr = self.block_record(header_hash) if curr.height <= 2: return self.constants.SUB_SLOT_ITERS_STARTING return get_next_sub_slot_iters( self.constants, self, header_hash, curr.height, curr.sub_slot_iters, curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) async def get_sp_and_ip_sub_slots( self, header_hash: bytes32 ) -> Optional[Tuple[Optional[EndOfSubSlotBundle], Optional[EndOfSubSlotBundle]]]: block: Optional[FullBlock] = await self.block_store.get_full_block( header_hash) if block is None: return None curr_br: BlockRecord = self.block_record(block.header_hash) is_overflow = curr_br.overflow curr: Optional[FullBlock] = block assert curr is not None while True: if curr_br.first_in_sub_slot: curr = await self.block_store.get_full_block( curr_br.header_hash) assert curr is not None break if curr_br.height == 0: break curr_br = self.block_record(curr_br.prev_hash) if len(curr.finished_sub_slots) == 0: # This means we got to genesis and still no sub-slots return None, None ip_sub_slot = curr.finished_sub_slots[-1] if not is_overflow: # Pos sub-slot is the same as infusion sub slot return None, ip_sub_slot if len(curr.finished_sub_slots) > 1: # Have both sub-slots return curr.finished_sub_slots[-2], ip_sub_slot prev_curr: Optional[FullBlock] = await self.block_store.get_full_block( curr.prev_header_hash) if prev_curr is None: assert curr.height == 0 prev_curr = curr prev_curr_br = self.block_record(curr.header_hash) else: prev_curr_br = self.block_record(curr.prev_header_hash) assert prev_curr_br is not None while prev_curr_br.height > 0: if prev_curr_br.first_in_sub_slot: prev_curr = await self.block_store.get_full_block( prev_curr_br.header_hash) assert prev_curr is not None break prev_curr_br = self.block_record(prev_curr_br.prev_hash) if len(prev_curr.finished_sub_slots) == 0: return None, ip_sub_slot return prev_curr.finished_sub_slots[-1], ip_sub_slot def get_recent_reward_challenges(self) -> List[Tuple[bytes32, uint128]]: peak = self.get_peak() if peak is None: return [] recent_rc: List[Tuple[bytes32, uint128]] = [] curr = self.try_block_record(peak.prev_hash) while curr is not None and len( recent_rc) < 2 * self.constants.MAX_SUB_SLOT_BLOCKS: recent_rc.append( (curr.reward_infusion_new_challenge, curr.total_iters)) if curr.first_in_sub_slot: assert curr.finished_reward_slot_hashes is not None sub_slot_total_iters = curr.ip_sub_slot_total_iters( self.constants) # Start from the most recent for rc in reversed(curr.finished_reward_slot_hashes): recent_rc.append((rc, sub_slot_total_iters)) sub_slot_total_iters = uint128(sub_slot_total_iters - curr.sub_slot_iters) curr = self.try_block_record(curr.prev_hash) return list(reversed(recent_rc)) async def validate_unfinished_block( self, block: UnfinishedBlock, skip_overflow_ss_validation=True) -> PreValidationResult: if (not self.contains_block(block.prev_header_hash) and not block.prev_header_hash == self.constants.GENESIS_CHALLENGE): return PreValidationResult( uint16(Err.INVALID_PREV_BLOCK_HASH.value), None, None) unfinished_header_block = UnfinishedHeaderBlock( block.finished_sub_slots, block.reward_chain_block, block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage, block.foliage_transaction_block, b"", ) prev_b = self.try_block_record( unfinished_header_block.prev_header_hash) sub_slot_iters, difficulty = get_sub_slot_iters_and_difficulty( self.constants, unfinished_header_block, prev_b, self) required_iters, error = validate_unfinished_header_block( self.constants, self, unfinished_header_block, False, difficulty, sub_slot_iters, skip_overflow_ss_validation, ) if error is not None: return PreValidationResult(uint16(error.code.value), None, None) prev_height = (-1 if block.prev_header_hash == self.constants.GENESIS_CHALLENGE else self.block_record(block.prev_header_hash).height) error_code, cost_result = await validate_block_body( self.constants, self, self.block_store, self.coin_store, self.get_peak(), block, uint32(prev_height + 1), None, ) if error_code is not None: return PreValidationResult(uint16(error_code.value), None, None) return PreValidationResult(None, required_iters, cost_result) async def pre_validate_blocks_multiprocessing( self, blocks: List[FullBlock], validate_transactions: bool = True ) -> Optional[List[PreValidationResult]]: return await pre_validate_blocks_multiprocessing( self.constants, self.constants_json, self, blocks, self.pool, validate_transactions, True) def contains_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory. """ return header_hash in self.__block_records def block_record(self, header_hash: bytes32) -> BlockRecord: return self.__block_records[header_hash] def height_to_block_record(self, height: uint32) -> BlockRecord: header_hash = self.height_to_hash(height) return self.block_record(header_hash) def get_ses_heights(self) -> List[uint32]: return sorted(self.__sub_epoch_summaries.keys()) def get_ses(self, height: uint32) -> SubEpochSummary: return self.__sub_epoch_summaries[height] def height_to_hash(self, height: uint32) -> Optional[bytes32]: return self.__height_to_hash[height] def contains_height(self, height: uint32) -> bool: return height in self.__height_to_hash def get_peak_height(self) -> Optional[uint32]: return self._peak_height async def warmup(self, fork_point: uint32): """ Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last block height to load in the cache """ if self._peak_height is None: return block_records = await self.block_store.get_block_records_in_range( max(fork_point - self.constants.BLOCKS_CACHE_SIZE, uint32(0)), fork_point) for block_record in block_records.values(): self.add_block_record(block_record) def clean_block_record(self, height: int): """ Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) while blocks_to_remove is not None and height >= 0: for header_hash in blocks_to_remove: del self.__block_records[header_hash] # remove from blocks del self.__heights_in_cache[uint32( height)] # remove height from heights in cache height = height - 1 blocks_to_remove = self.__heights_in_cache.get( uint32(height), None) def clean_block_records(self): """ Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__block_records) < self.constants.BLOCKS_CACHE_SIZE: return peak = self.get_peak() assert peak is not None if peak.height - self.constants.BLOCKS_CACHE_SIZE < 0: return self.clean_block_record(peak.height - self.constants.BLOCKS_CACHE_SIZE) async def get_block_records_in_range( self, start: int, stop: int) -> Dict[bytes32, BlockRecord]: return await self.block_store.get_block_records_in_range(start, stop) async def get_header_blocks_in_range( self, start: int, stop: int) -> Dict[bytes32, HeaderBlock]: return await self.block_store.get_header_blocks_in_range(start, stop) async def get_block_record_from_db( self, header_hash: bytes32) -> Optional[BlockRecord]: if header_hash in self.__block_records: return self.__block_records[header_hash] return await self.block_store.get_block_record(header_hash) def remove_block_record(self, header_hash: bytes32): sbr = self.block_record(header_hash) del self.__block_records[header_hash] self.__heights_in_cache[sbr.height].remove(header_hash) def add_block_record(self, block_record: BlockRecord): """ Adds a block record to the cache. """ self.__block_records[block_record.header_hash] = block_record if block_record.height not in self.__heights_in_cache.keys(): self.__heights_in_cache[block_record.height] = set() self.__heights_in_cache[block_record.height].add( block_record.header_hash) async def get_header_block(self, header_hash: bytes32) -> Optional[HeaderBlock]: block = await self.block_store.get_full_block(header_hash) if block is None: return None return block.get_block_header() async def persist_sub_epoch_challenge_segments( self, sub_epoch_summary_height: uint32, segments: List[SubEpochChallengeSegment]): return await self.block_store.persist_sub_epoch_challenge_segments( sub_epoch_summary_height, segments) async def get_sub_epoch_challenge_segments( self, sub_epoch_summary_height: uint32, ) -> Optional[List[SubEpochChallengeSegment]]: segments: Optional[List[ SubEpochChallengeSegment]] = await self.block_store.get_sub_epoch_challenge_segments( sub_epoch_summary_height) if segments is None: return None return segments
def do_test1(workers): param = {"max_workers": workers} start = round(time.time() + _start_warm_up) input = input_generator(workers, start) loop = asyncio.new_event_loop() lock = threading.Lock() tresult = [] presult = [] cresult = [] def result_checker(list, lock, fut): with lock: try: list.append(fut.result()) except Exception as e: list.append(e) texec = ThreadPoolExecutor(**param) pexec = ProcessPoolExecutor(**param) cexec = CoroutinePoolExecutor(**param, loop=loop) for x in input: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) texec.shutdown(False) pexec.shutdown(False) loop.run_until_complete(cexec.shutdown(False)) try: loop.run_until_complete(cexec.shutdown(True)) texec.shutdown(True) pexec.shutdown(True) finally: loop.close() tresult = [round((x - start) / _precision) for x in tresult] presult = [round((x - start) / _precision) for x in presult] cresult = [round((x - start) / _precision) for x in cresult] result = True for (t, p, c) in zip(tresult, presult, cresult): result = result and (t == p) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (p == c) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (c == t) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False return result
class MempoolManager: def __init__(self, coin_store: CoinStore, consensus_constants: ConsensusConstants): self.constants: ConsensusConstants = consensus_constants self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) # Transactions that were unable to enter mempool, used for retry. (they were invalid) self.potential_txs: Dict[bytes32, Tuple[SpendBundle, CostResult, bytes32]] = {} # Keep track of seen spend_bundles self.seen_bundle_hashes: Dict[bytes32, bytes32] = {} self.coin_store = coin_store self.mempool_max_total_cost = int(self.constants.MAX_BLOCK_COST_CLVM * self.constants.MEMPOOL_BLOCK_BUFFER) self.potential_cache_max_total_cost = int( self.constants.MAX_BLOCK_COST_CLVM * self.constants.MEMPOOL_BLOCK_BUFFER) self.potential_cache_cost: int = 0 self.seen_cache_size = 10000 self.pool = ProcessPoolExecutor(max_workers=1) # The mempool will correspond to a certain peak self.peak: Optional[BlockRecord] = None self.mempool: Mempool = Mempool(self.mempool_max_total_cost) def shut_down(self): self.pool.shutdown(wait=True) async def create_bundle_from_mempool( self, peak_header_hash: bytes32 ) -> Optional[Tuple[SpendBundle, List[Coin], List[Coin]]]: """ Returns aggregated spendbundle that can be used for creating new block, additions and removals in that spend_bundle """ if (self.peak is None or self.peak.header_hash != peak_header_hash or self.peak.height <= self.constants.INITIAL_FREEZE_PERIOD): return None cost_sum = 0 # Checks that total cost does not exceed block maximum fee_sum = 0 # Checks that total fees don't exceed 64 bits spend_bundles: List[SpendBundle] = [] removals = [] additions = [] broke_from_inner_loop = False log.info( f"Starting to make block, max cost: {self.constants.MAX_BLOCK_COST_CLVM}" ) for dic in self.mempool.sorted_spends.values(): if broke_from_inner_loop: break for item in dic.values(): log.info(f"Cumulative cost: {cost_sum}") if (item.cost_result.cost + cost_sum <= self.constants.MAX_BLOCK_COST_CLVM and item.fee + fee_sum <= self.constants.MAX_COIN_AMOUNT): spend_bundles.append(item.spend_bundle) cost_sum += item.cost_result.cost fee_sum += item.fee removals.extend(item.removals) additions.extend(item.additions) else: broke_from_inner_loop = True break if len(spend_bundles) > 0: return SpendBundle.aggregate(spend_bundles), additions, removals else: return None def get_filter(self) -> bytes: all_transactions: Set[bytes32] = set() byte_array_list = [] for key, _ in self.mempool.spends.items(): if key not in all_transactions: all_transactions.add(key) byte_array_list.append(bytearray(key)) tx_filter: PyBIP158 = PyBIP158(byte_array_list) return bytes(tx_filter.GetEncoded()) def is_fee_enough(self, fees: uint64, cost: uint64) -> bool: """ Determines whether any of the pools can accept a transaction with a given fees and cost. """ if cost == 0: return False fees_per_cost = fees / cost if not self.mempool.at_full_capacity( cost) or fees_per_cost > self.mempool.get_min_fee_rate(cost): return True return False def add_and_maybe_pop_seen(self, spend_name: bytes32): self.seen_bundle_hashes[spend_name] = spend_name while len(self.seen_bundle_hashes) > self.seen_cache_size: first_in = list(self.seen_bundle_hashes.keys())[0] self.seen_bundle_hashes.pop(first_in) def seen(self, bundle_hash: bytes32) -> bool: """ Return true if we saw this spendbundle before """ return bundle_hash in self.seen_bundle_hashes def remove_seen(self, bundle_hash: bytes32): if bundle_hash in self.seen_bundle_hashes: self.seen_bundle_hashes.pop(bundle_hash) def get_min_fee_increase(self): # 0.00001 XCH return 10000000 def can_replace(self, conflicting_items, removals, fees, fees_per_cost): conflicting_fees = 0 conflicting_cost = 0 for item in conflicting_items.values(): conflicting_fees += item.fee conflicting_cost += item.cost_result.cost # All coins spent in all conflicting items must also be spent in # the new item for coin in item.removals: if coin.name() not in removals: return False # New item must have higher fee per cost if fees_per_cost <= conflicting_fees / conflicting_cost: return False # New item must increase the total fee at least by a certain amount if fees < conflicting_fees + self.get_min_fee_increase(): return False return True async def pre_validate_spendbundle(self, new_spend: SpendBundle) -> CostResult: """ Errors are included within the cached_result. This runs in another process so we don't block the main thread """ start_time = time.time() cached_result_bytes = await asyncio.get_running_loop().run_in_executor( self.pool, validate_transaction_multiprocess, self.constants_json, bytes(new_spend)) end_time = time.time() log.info( f"It took {end_time - start_time} to pre validate transaction") return CostResult.from_bytes(cached_result_bytes) async def add_spendbundle( self, new_spend: SpendBundle, cost_result: CostResult, spend_name: bytes32, validate_signature=True, ) -> Tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]: """ Tries to add spendbundle to either self.mempools or to_pool if it's specified. Returns true if it's added in any of pools, Returns error if it fails. """ start_time = time.time() if self.peak is None: return None, MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_INITIALIZED npc_list = cost_result.npc_list cost = cost_result.cost log.debug(f"Cost: {cost}") if cost > self.constants.MAX_BLOCK_COST_CLVM: return None, MempoolInclusionStatus.FAILED, Err.BLOCK_COST_EXCEEDS_MAX if cost_result.error is not None: return None, MempoolInclusionStatus.FAILED, Err(cost_result.error) # build removal list removal_names: List[bytes32] = new_spend.removal_names() additions = additions_for_npc(npc_list) additions_dict: Dict[bytes32, Coin] = {} for add in additions: additions_dict[add.name()] = add addition_amount = uint64(0) # Check additions for max coin amount for coin in additions: if coin.amount > self.constants.MAX_COIN_AMOUNT: return ( None, MempoolInclusionStatus.FAILED, Err.COIN_AMOUNT_EXCEEDS_MAXIMUM, ) addition_amount = uint64(addition_amount + coin.amount) # Check for duplicate outputs addition_counter = collections.Counter(_.name() for _ in additions) for k, v in addition_counter.items(): if v > 1: return None, MempoolInclusionStatus.FAILED, Err.DUPLICATE_OUTPUT # Check for duplicate inputs removal_counter = collections.Counter(name for name in removal_names) for k, v in removal_counter.items(): if v > 1: return None, MempoolInclusionStatus.FAILED, Err.DOUBLE_SPEND # Skip if already added if spend_name in self.mempool.spends: return uint64(cost), MempoolInclusionStatus.SUCCESS, None removal_record_dict: Dict[bytes32, CoinRecord] = {} removal_coin_dict: Dict[bytes32, Coin] = {} unknown_unspent_error: bool = False removal_amount = uint64(0) for name in removal_names: removal_record = await self.coin_store.get_coin_record(name) if removal_record is None and name not in additions_dict: unknown_unspent_error = True break elif name in additions_dict: removal_coin = additions_dict[name] # TODO(straya): what timestamp to use here? removal_record = CoinRecord( removal_coin, uint32( self.peak.height + 1), # In mempool, so will be included in next height uint32(0), False, False, uint64(int(time.time())), ) assert removal_record is not None removal_amount = uint64(removal_amount + removal_record.coin.amount) removal_record_dict[name] = removal_record removal_coin_dict[name] = removal_record.coin if unknown_unspent_error: return None, MempoolInclusionStatus.FAILED, Err.UNKNOWN_UNSPENT if addition_amount > removal_amount: print(addition_amount, removal_amount) return None, MempoolInclusionStatus.FAILED, Err.MINTING_COIN fees = removal_amount - addition_amount assert_fee_sum: uint64 = uint64(0) for npc in npc_list: if ConditionOpcode.RESERVE_FEE in npc.condition_dict: fee_list: List[ConditionWithArgs] = npc.condition_dict[ ConditionOpcode.RESERVE_FEE] for cvp in fee_list: fee = int_from_bytes(cvp.vars[0]) assert_fee_sum = assert_fee_sum + fee if fees < assert_fee_sum: return ( None, MempoolInclusionStatus.FAILED, Err.RESERVE_FEE_CONDITION_FAILED, ) if cost == 0: return None, MempoolInclusionStatus.FAILED, Err.UNKNOWN fees_per_cost: float = fees / cost # If pool is at capacity check the fee, if not then accept even without the fee if self.mempool.at_full_capacity(cost): if fees == 0: return None, MempoolInclusionStatus.FAILED, Err.INVALID_FEE_LOW_FEE if fees_per_cost <= self.mempool.get_min_fee_rate(cost): return None, MempoolInclusionStatus.FAILED, Err.INVALID_FEE_LOW_FEE # Check removals against UnspentDB + DiffStore + Mempool + SpendBundle # Use this information later when constructing a block fail_reason, conflicts = await self.check_removals(removal_record_dict) # If there is a mempool conflict check if this spendbundle has a higher fee per cost than all others tmp_error: Optional[Err] = None conflicting_pool_items: Dict[bytes32, MempoolItem] = {} if fail_reason is Err.MEMPOOL_CONFLICT: for conflicting in conflicts: sb: MempoolItem = self.mempool.removals[conflicting.name()] conflicting_pool_items[sb.name] = sb if not self.can_replace(conflicting_pool_items, removal_record_dict, fees, fees_per_cost): self.add_to_potential_tx_set(new_spend, spend_name, cost_result) return ( uint64(cost), MempoolInclusionStatus.PENDING, Err.MEMPOOL_CONFLICT, ) elif fail_reason: return None, MempoolInclusionStatus.FAILED, fail_reason if tmp_error: return None, MempoolInclusionStatus.FAILED, tmp_error # Verify conditions, create hash_key list for aggsig check pks: List[G1Element] = [] msgs: List[bytes32] = [] error: Optional[Err] = None coin_announcements_in_spend: Set[ bytes32] = coin_announcements_names_for_npc(npc_list) puzzle_announcements_in_spend: Set[ bytes32] = puzzle_announcements_names_for_npc(npc_list) for npc in npc_list: coin_record: CoinRecord = removal_record_dict[npc.coin_name] # Check that the revealed removal puzzles actually match the puzzle hash if npc.puzzle_hash != coin_record.coin.puzzle_hash: log.warning( "Mempool rejecting transaction because of wrong puzzle_hash" ) log.warning( f"{npc.puzzle_hash} != {coin_record.coin.puzzle_hash}") return None, MempoolInclusionStatus.FAILED, Err.WRONG_PUZZLE_HASH chialisp_height = (self.peak.prev_transaction_block_height if not self.peak.is_transaction_block else self.peak.height) error = mempool_check_conditions_dict( coin_record, coin_announcements_in_spend, puzzle_announcements_in_spend, npc.condition_dict, uint32(chialisp_height), ) if error: if error is Err.ASSERT_HEIGHT_ABSOLUTE_FAILED or error is Err.ASSERT_HEIGHT_RELATIVE_FAILED: self.add_to_potential_tx_set(new_spend, spend_name, cost_result) return uint64(cost), MempoolInclusionStatus.PENDING, error break if validate_signature: for pk, message in pkm_pairs_for_conditions_dict( npc.condition_dict, npc.coin_name, self.constants.AGG_SIG_ME_ADDITIONAL_DATA): pks.append(pk) msgs.append(message) if error: return None, MempoolInclusionStatus.FAILED, error if validate_signature: # Verify aggregated signature if not AugSchemeMPL.aggregate_verify( pks, msgs, new_spend.aggregated_signature): log.warning( f"Aggsig validation error {pks} {msgs} {new_spend}") return None, MempoolInclusionStatus.FAILED, Err.BAD_AGGREGATE_SIGNATURE # Remove all conflicting Coins and SpendBundles if fail_reason: mempool_item: MempoolItem for mempool_item in conflicting_pool_items.values(): self.mempool.remove_from_pool(mempool_item) removals: List[Coin] = [coin for coin in removal_coin_dict.values()] new_item = MempoolItem(new_spend, uint64(fees), cost_result, spend_name, additions, removals) self.mempool.add_to_pool(new_item, additions, removal_coin_dict) log.info(f"add_spendbundle took {time.time() - start_time} seconds") return uint64(cost), MempoolInclusionStatus.SUCCESS, None async def check_removals( self, removals: Dict[bytes32, CoinRecord]) -> Tuple[Optional[Err], List[Coin]]: """ This function checks for double spends, unknown spends and conflicting transactions in mempool. Returns Error (if any), dictionary of Unspents, list of coins with conflict errors (if any any). Note that additions are not checked for duplicates, because having duplicate additions requires also having duplicate removals. """ assert self.peak is not None conflicts: List[Coin] = [] for record in removals.values(): removal = record.coin # 1. Checks if it's been spent already if record.spent == 1: return Err.DOUBLE_SPEND, [] # 2. Checks if there's a mempool conflict if removal.name() in self.mempool.removals: conflicts.append(removal) if len(conflicts) > 0: return Err.MEMPOOL_CONFLICT, conflicts # 5. If coins can be spent return list of unspents as we see them in local storage return None, [] def add_to_potential_tx_set(self, spend: SpendBundle, spend_name: bytes32, cost_result: CostResult): """ Adds SpendBundles that have failed to be added to the pool in potential tx set. This is later used to retry to add them. """ if spend_name in self.potential_txs: return self.potential_txs[spend_name] = spend, cost_result, spend_name self.potential_cache_cost += cost_result.cost while self.potential_cache_cost > self.potential_cache_max_total_cost: first_in = list(self.potential_txs.keys())[0] self.potential_cache_max_total_cost -= self.potential_txs[ first_in][1].cost self.potential_txs.pop(first_in) def get_spendbundle(self, bundle_hash: bytes32) -> Optional[SpendBundle]: """ Returns a full SpendBundle if it's inside one the mempools""" if bundle_hash in self.mempool.spends: return self.mempool.spends[bundle_hash].spend_bundle return None def get_mempool_item(self, bundle_hash: bytes32) -> Optional[MempoolItem]: """ Returns a MempoolItem if it's inside one the mempools""" if bundle_hash in self.mempool.spends: return self.mempool.spends[bundle_hash] return None async def new_peak( self, new_peak: Optional[BlockRecord] ) -> List[Tuple[SpendBundle, CostResult, bytes32]]: """ Called when a new peak is available, we try to recreate a mempool for the new tip. """ if new_peak is None: return [] if self.peak == new_peak: return [] if new_peak.height <= self.constants.INITIAL_FREEZE_PERIOD: return [] self.peak = new_peak old_pool = self.mempool self.mempool = Mempool(self.mempool_max_total_cost) for item in old_pool.spends.values(): await self.add_spendbundle(item.spend_bundle, item.cost_result, item.spend_bundle_name, False) potential_txs_copy = self.potential_txs.copy() self.potential_txs = {} txs_added = [] for tx, cached_result, cached_name in potential_txs_copy.values(): cost, status, error = await self.add_spendbundle( tx, cached_result, cached_name) if status == MempoolInclusionStatus.SUCCESS: txs_added.append((tx, cached_result, cached_name)) log.debug( f"Size of mempool: {len(self.mempool.spends)} spends, cost: {self.mempool.total_mempool_cost} " f"minimum fee to get in: {self.mempool.get_min_fee_rate(100000)}") return txs_added async def get_items_not_in_filter( self, mempool_filter: PyBIP158) -> List[MempoolItem]: items: List[MempoolItem] = [] checked_items: Set[bytes32] = set() for key, item in self.mempool.spends.items(): if key in checked_items: continue if mempool_filter.Match(bytearray(key)): checked_items.add(key) continue checked_items.add(key) items.append(item) return items
def do_test1(workers): param = {"max_workers": workers} start = round(time.time() + _start_warm_up) input = input_generator(workers, start) loop = asyncio.new_event_loop() lock = threading.Lock() tresult = [] presult = [] cresult = [] def result_checker(list, lock, fut): with lock: try: list.append(fut.result()) except Exception as e: list.append(e) texec = ThreadPoolExecutor(**param) pexec = ProcessPoolExecutor(**param) cexec = CoroutinePoolExecutor(**param, loop=loop) for x in input: future = texec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, tresult, lock)) future = pexec.submit(wake_at, x) future.add_done_callback( functools.partial(result_checker, presult, lock)) future = cexec.submit(async_wake_at, x) future.add_done_callback( functools.partial(result_checker, cresult, lock)) texec.shutdown(False) pexec.shutdown(False) loop.run_until_complete(cexec.shutdown(False)) try: loop.run_until_complete(cexec.shutdown(True)) texec.shutdown(True) pexec.shutdown(True) finally: loop.close() tresult = [round((x - start) / _precision) for x in tresult] presult = [round((x - start) / _precision) for x in presult] cresult = [round((x - start) / _precision) for x in cresult] result = True for (t, p, c) in zip(tresult, presult, cresult): result = result and (t == p) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (p == c) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False result = result and (c == t) if not result: print(tresult) print(presult) print(cresult) print(t, p, c) assert False return result
class WalletBlockchain(BlockchainInterface): constants: ConsensusConstants constants_json: Dict # peak of the blockchain peak_height: Optional[uint32] # All sub blocks in peak path are guaranteed to be included, can include orphan sub-blocks __sub_blocks: Dict[bytes32, SubBlockRecord] # Defines the path from genesis to the peak, no orphan sub-blocks __height_to_hash: Dict[uint32, bytes32] # all hashes of sub blocks in sub_block_record by height, used for garbage collection __heights_in_cache: Dict[uint32, Set[bytes32]] # All sub-epoch summaries that have been included in the blockchain from the beginning until and including the peak # (height_included, SubEpochSummary). Note: ONLY for the sub-blocks in the path to the peak __sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {} # Unspent Store coin_store: WalletCoinStore # Store block_store: WalletBlockStore # Used to verify blocks in parallel pool: ProcessPoolExecutor coins_of_interest_received: Any reorg_rollback: Any # Whether blockchain is shut down or not _shut_down: bool # Lock to prevent simultaneous reads and writes lock: asyncio.Lock log: logging.Logger @staticmethod async def create( block_store: WalletBlockStore, consensus_constants: ConsensusConstants, coins_of_interest_received: Callable, # f(removals: List[Coin], additions: List[Coin], height: uint32) reorg_rollback: Callable, ): """ Initializes a blockchain with the SubBlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config. """ self = WalletBlockchain() self.lock = asyncio.Lock() # External lock handled by full node cpu_count = multiprocessing.cpu_count() if cpu_count > 61: cpu_count = 61 # Windows Server 2016 has an issue https://bugs.python.org/issue26903 num_workers = max(cpu_count - 2, 1) self.pool = ProcessPoolExecutor(max_workers=num_workers) log.info(f"Started {num_workers} processes for block validation") self.constants = consensus_constants self.constants_json = recurse_jsonify( dataclasses.asdict(self.constants)) self.block_store = block_store self._shut_down = False self.coins_of_interest_received = coins_of_interest_received self.reorg_rollback = reorg_rollback self.log = logging.getLogger(__name__) await self._load_chain_from_store() return self def shut_down(self): self._shut_down = True self.pool.shutdown(wait=True) async def _load_chain_from_store(self) -> None: """ Initializes the state of the Blockchain class from the database. """ height_to_hash, sub_epoch_summaries = await self.block_store.get_peak_heights_dicts( ) self.__height_to_hash = height_to_hash self.__sub_epoch_summaries = sub_epoch_summaries self.__sub_blocks = {} self.__heights_in_cache = {} sub_blocks, peak = await self.block_store.get_sub_block_records_close_to_peak( self.constants.SUB_BLOCKS_CACHE_SIZE) for sub_block in sub_blocks.values(): self.add_sub_block(sub_block) if len(sub_blocks) == 0: assert peak is None self.peak_height = None return assert peak is not None self.peak_height = self.sub_block_record(peak).height assert len(self.__height_to_hash) == self.peak_height + 1 def get_peak(self) -> Optional[SubBlockRecord]: """ Return the peak of the blockchain """ if self.peak_height is None: return None return self.height_to_sub_block_record(self.peak_height) async def get_full_peak(self) -> Optional[HeaderBlock]: """ Return a peak transaction block""" if self.peak_height is None: return None curr: Optional[SubBlockRecord] = self.height_to_sub_block_record( self.peak_height) while curr is not None and not curr.is_block: curr = self.try_sub_block(curr.prev_hash) if curr is None: return None block = await self.block_store.get_header_block(curr.header_hash) assert block is not None return block def is_child_of_peak(self, block: UnfinishedBlock) -> bool: """ True iff the block is the direct ancestor of the peak """ peak = self.get_peak() if peak is None: return False return block.prev_header_hash == peak.header_hash async def get_full_block(self, header_hash: bytes32) -> Optional[HeaderBlock]: return await self.block_store.get_header_block(header_hash) async def receive_block( self, block_record: HeaderBlockRecord, pre_validation_result: Optional[PreValidationResult] = None, trusted: bool = False, fork_point_with_peak: Optional[uint32] = None, ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32]]: """ Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case of a new peak. """ block = block_record.header genesis: bool = block.height == 0 if self.contains_sub_block(block.header_hash): return ReceiveBlockResult.ALREADY_HAVE_BLOCK, None, None if not self.contains_sub_block(block.prev_header_hash) and not genesis: return ( ReceiveBlockResult.DISCONNECTED_BLOCK, Err.INVALID_PREV_BLOCK_HASH, None, ) if block.height == 0: prev_sb: Optional[SubBlockRecord] = None else: prev_sb = self.sub_block_record(block.prev_header_hash) sub_slot_iters, difficulty = get_sub_slot_iters_and_difficulty( self.constants, block, prev_sb, self) if trusted is False and pre_validation_result is None: required_iters, error = validate_finished_header_block( self.constants, self, block, False, difficulty, sub_slot_iters) elif trusted: unfinished_header_block = UnfinishedHeaderBlock( block.finished_sub_slots, block.reward_chain_sub_block.get_unfinished(), block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage_sub_block, block.foliage_block, block.transactions_filter, ) required_iters, val_error = validate_unfinished_header_block( self.constants, self, unfinished_header_block, False, difficulty, sub_slot_iters, False, True) error = ValidationError( Err(val_error)) if val_error is not None else None else: assert pre_validation_result is not None required_iters = pre_validation_result.required_iters error = (ValidationError(Err(pre_validation_result.error)) if pre_validation_result.error is not None else None) if error is not None: return ReceiveBlockResult.INVALID_BLOCK, error.code, None assert required_iters is not None sub_block = block_to_sub_block_record( self.constants, self, required_iters, None, block, ) # Always add the block to the database await self.block_store.add_block_record(block_record, sub_block) self.add_sub_block(sub_block) self.clean_sub_block_record(sub_block.height - self.constants.SUB_BLOCKS_CACHE_SIZE) fork_height: Optional[uint32] = await self._reconsider_peak( sub_block, genesis, fork_point_with_peak) if fork_height is not None: self.log.info( f"💰 Updated wallet peak to sub height {sub_block.height}, weight {sub_block.weight}, " ) return ReceiveBlockResult.NEW_PEAK, None, fork_height else: return ReceiveBlockResult.ADDED_AS_ORPHAN, None, None async def _reconsider_peak( self, sub_block: SubBlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32]) -> Optional[uint32]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there was no update to the heaviest chain. """ peak = self.get_peak() if genesis: if peak is None: block: Optional[ HeaderBlockRecord] = await self.block_store.get_header_block_record( sub_block.header_hash) assert block is not None self.__height_to_hash[uint32(0)] = block.header_hash for removed in block.removals: self.log.debug(f"Removed: {removed.name()}") await self.coins_of_interest_received(block.removals, block.additions, block.height) self.peak_height = uint32(0) return uint32(0) return None assert peak is not None if sub_block.weight > peak.weight: # Find the fork. if the block is just being appended, it will return the peak # If no blocks in common, returns -1, and reverts all blocks if fork_point_with_peak is not None: fork_h: int = fork_point_with_peak else: fork_h = find_fork_point_in_chain(self, sub_block, peak) # Rollback to fork self.log.debug( f"fork_h: {fork_h}, SB: {sub_block.height}, peak: {peak.height}" ) await self.reorg_rollback(fork_h) # Rollback sub_epoch_summaries heights_to_delete = [] for ses_included_height in self.__sub_epoch_summaries.keys(): if ses_included_height > fork_h: heights_to_delete.append(ses_included_height) for height in heights_to_delete: del self.__sub_epoch_summaries[height] # Collect all blocks from fork point to new peak blocks_to_add: List[Tuple[HeaderBlockRecord, SubBlockRecord]] = [] curr = sub_block.header_hash while fork_h < 0 or curr != self.height_to_hash(uint32(fork_h)): fetched_block: Optional[ HeaderBlockRecord] = await self.block_store.get_header_block_record( curr) fetched_sub_block: Optional[ SubBlockRecord] = await self.block_store.get_sub_block_record( curr) assert fetched_block is not None assert fetched_sub_block is not None blocks_to_add.append((fetched_block, fetched_sub_block)) if fetched_block.height == 0: # Doing a full reorg, starting at height 0 break curr = fetched_sub_block.prev_hash for fetched_block, fetched_sub_block in reversed(blocks_to_add): self.__height_to_hash[ fetched_sub_block.height] = fetched_sub_block.header_hash if fetched_sub_block.is_block: await self.coins_of_interest_received( fetched_block.removals, fetched_block.additions, fetched_block.height, ) if fetched_sub_block.sub_epoch_summary_included is not None: self.__sub_epoch_summaries[ fetched_sub_block. height] = fetched_sub_block.sub_epoch_summary_included # Changes the peak to be the new peak await self.block_store.set_peak(sub_block.header_hash) self.peak_height = sub_block.height return uint32(min(fork_h, 0)) # This is not a heavier block than the heaviest we have seen, so we don't change the coin set return None def get_next_difficulty(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_sub_block(header_hash) curr = self.sub_block_record(header_hash) if curr.height <= 2: return self.constants.DIFFICULTY_STARTING return get_next_difficulty( self.constants, self, header_hash, curr.height, uint64(curr.weight - self.__sub_blocks[curr.prev_hash].weight), curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) def get_next_slot_iters(self, header_hash: bytes32, new_slot: bool) -> uint64: assert self.contains_sub_block(header_hash) curr = self.sub_block_record(header_hash) if curr.height <= 2: return self.constants.SUB_SLOT_ITERS_STARTING return get_next_sub_slot_iters( self.constants, self, header_hash, curr.height, curr.sub_slot_iters, curr.deficit, new_slot, curr.sp_total_iters(self.constants), ) async def pre_validate_blocks_multiprocessing( self, blocks: List[HeaderBlock], ) -> Optional[List[PreValidationResult]]: return await pre_validate_blocks_multiprocessing( self.constants, self.constants_json, self, blocks, self.pool) def contains_sub_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan sub-blocks that we have added but no longer keep in memory. """ return header_hash in self.__sub_blocks def sub_block_record(self, header_hash: bytes32) -> SubBlockRecord: return self.__sub_blocks[header_hash] def height_to_sub_block_record(self, height: uint32, check_db=False) -> SubBlockRecord: header_hash = self.height_to_hash(height) return self.sub_block_record(header_hash) def get_ses_heights(self) -> List[uint32]: return sorted(self.__sub_epoch_summaries.keys()) def get_ses(self, height: uint32) -> SubEpochSummary: return self.__sub_epoch_summaries[height] def height_to_hash(self, height: uint32) -> Optional[bytes32]: return self.__height_to_hash[height] def contains_height(self, height: uint32) -> bool: return height in self.__height_to_hash def get_peak_height(self) -> Optional[uint32]: return self.peak_height async def warmup(self, fork_point: uint32): """ Loads sub blocks into the cache. The sub-blocks loaded include all blocks from fork point - SUB_BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last sub-block height to load in the cache """ if self.peak_height is None: return sub_blocks = await self.block_store.get_sub_block_records_in_range( fork_point - self.constants.SUB_BLOCKS_CACHE_SIZE, self.peak_height) for sub_block in sub_blocks.values(): self.add_sub_block(sub_block) def clean_sub_block_record(self, height: int): """ Clears all sub block records in the cache which have sub_block < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) while blocks_to_remove is not None and height >= 0: for header_hash in blocks_to_remove: del self.__sub_blocks[header_hash] del self.__heights_in_cache[uint32( height)] # remove height from heights in cache height -= 1 blocks_to_remove = self.__heights_in_cache.get( uint32(height), None) def clean_sub_block_records(self): """ Cleans the cache so that we only maintain relevant sub-blocks. This removes sub-block records that have sub height < peak - SUB_BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__sub_blocks) < self.constants.SUB_BLOCKS_CACHE_SIZE: return peak = self.get_peak() assert peak is not None if peak.height - self.constants.SUB_BLOCKS_CACHE_SIZE < 0: return self.clean_sub_block_record(peak.height - self.constants.SUB_BLOCKS_CACHE_SIZE) async def get_sub_block_records_in_range( self, start: int, stop: int) -> Dict[bytes32, SubBlockRecord]: return await self.block_store.get_sub_block_records_in_range( start, stop) async def get_header_blocks_in_range( self, start: int, stop: int) -> Dict[bytes32, HeaderBlock]: return await self.block_store.get_header_blocks_in_range(start, stop) async def get_sub_block_from_db( self, header_hash: bytes32) -> Optional[SubBlockRecord]: if header_hash in self.__sub_blocks: return self.__sub_blocks[header_hash] return await self.block_store.get_sub_block_record(header_hash) def remove_sub_block(self, header_hash: bytes32): sbr = self.sub_block_record(header_hash) del self.__sub_blocks[header_hash] self.__heights_in_cache[sbr.height].remove(header_hash) def add_sub_block(self, sub_block: SubBlockRecord): self.__sub_blocks[sub_block.header_hash] = sub_block if sub_block.height not in self.__heights_in_cache.keys(): self.__heights_in_cache[sub_block.height] = set() self.__heights_in_cache[sub_block.height].add(sub_block.header_hash) async def get_header_block(self, header_hash: bytes32) -> Optional[HeaderBlock]: return await self.block_store.get_header_block(header_hash)
end = unit while end <= total_no_of_results: ranges.append([start, end]) start = end end = end + unit def genResults(the_range): print(f"start:{the_range[0]} - end:{the_range[1]}") rs_store = [] for i in range(the_range[0], the_range[1]): rs_loto = Game649().playMaxGameUnits() rs_store.append(rs_loto) for rs in rs_store: for r in rs.results: wd = WinningsDetector(rc, r) wd.getWinning() if wd.match_count > 5: print(wd.match_count) if __name__ == "__main__": start = tm.default_timer() prl = ProcessPoolExecutor(4) future_results = prl.map(genResults, ranges) prl.shutdown() rs_store = [] end = tm.default_timer() - start print(end)