before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
@pytest.mark.anyio @pytest.mark.parametrize("spend_singleton", [True, False]) @pytest.mark.parametrize("spend_plain", [True, False]) @pytest.mark.parametrize("use_optimization", [True, False]) @pytest.mark.parametrize("reverse_spend_order", [True, False]) async def test_new_peak_ff_eviction( spend_singleton: bool,...
This is an `int` not a `uint64` (already addressed).
await mempool.new_peak(br, spent_coins) invariant_check_mempool(mempool.mempool) @pytest.mark.anyio @pytest.mark.parametrize("spend_singleton", [True, False]) @pytest.mark.parametrize("spend_plain", [True, False]) @pytest.mark.parametrize("use_optimization", [True, False]) @pytest.mark.parametrize("reverse_s...
@@ -2453,7 +2444,7 @@ async def test_new_peak_ff_eviction( bundle_add_info = await mempool_manager.add_spend_bundle( bundle, - make_test_conds(spend_ids=[(singleton_spend.coin, ELIGIBLE_FOR_FF), (TEST_COIN, 0)], cost=1000000), + make_test_conds(spend_ids=[(singleton_spend.coin, ELIGIBLE_FO...
chia/_tests/core/mempool/test_mempool_manager.py
26
Python
0.357
suggestion
52
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
""" cost_saving = 0 unique_coin_spends: list[CoinSpend] = [] unique_additions: list[Coin] = [] # Map of coin ID to deduplication information new_dedup_spends: dict[bytes32, DedupCoinSpend] = {} # See if this item has coin spends that are eligible for deduplication...
`max_cost` is no longer needed (addressed already in addendum).
cost_saving = 0 unique_coin_spends: list[CoinSpend] = [] unique_additions: list[Coin] = [] # Map of coin ID to deduplication information new_dedup_spends: dict[bytes32, DedupCoinSpend] = {} # See if this item has coin spends that are eligible for deduplication for...
@@ -180,30 +167,7 @@ def get_deduplication_info( # solution we see from the relatively highest FPC item, to avoid # severe performance and/or time-complexity impact raise SkipDedup("Solution is different from what we're deduplicating on") - # Let's calculate...
chia/full_node/eligible_coin_spends.py
26
Python
0.357
suggestion
63
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
if spend.seconds_relative is not None: s = uint64(removal_coin_records[bytes32(spend.coin_id)].timestamp + spend.seconds_relative) ret.assert_seconds = max(ret.assert_seconds, s) if spend.before_height_relative is not None: h = uint32( removal_coin_re...
This is unrelated to the patch, it's a result of altering `add_spendbundle`'s failure path (addressed in the addendum).
if spend.seconds_relative is not None: s = uint64(removal_coin_records[bytes32(spend.coin_id)].timestamp + spend.seconds_relative) ret.assert_seconds = max(ret.assert_seconds, s) if spend.before_height_relative is not None: h = uint32( removal_coin_re...
@@ -124,7 +124,7 @@ def compute_assert_height( @dataclass class SpendBundleAddInfo: - cost: Optional[uint64] + cost: uint64
chia/full_node/mempool_manager.py
26
Python
0.5
bug
119
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
spend_name, first_added_height, get_coin_records, get_unspent_lineage_info_for_puzzle_hash, ) if err is None: # No error, immediately add to mempool, after removing conflicting TXs. assert item is not None conflict = sel...
This is the unrelated change to `add_spend_bundle` that triggered several other changes in this patch (addressed already).
spend_name, first_added_height, get_coin_records, get_unspent_lineage_info_for_puzzle_hash, ) if err is None: # No error, immediately add to mempool, after removing conflicting TXs. assert item is not None conflict = sel...
@@ -545,7 +545,7 @@ async def add_spend_bundle( return SpendBundleAddInfo(item.cost, MempoolInclusionStatus.PENDING, [], err) else: # Cannot add to the mempool or pending pool. - return SpendBundleAddInfo(None, MempoolInclusionStatus.FAILED, [], err) + return Spe...
chia/full_node/mempool_manager.py
26
Python
0.571
suggestion
122
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, uint64(coin.amount - actual_fee)]) sb = spend_bundle_from_conditions(conditions, coin) ...
The highest fee per cost we consider here belongs to the mempool item that contains the spend, not the spend with the highest fee per cost, right?
if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, uint64(coin.amount - actual_fee)]) sb = spend_bundle_from_conditions(conditions, coin) ...
@@ -3129,69 +3109,86 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 - conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_...
chia/_tests/core/mempool/test_mempool.py
26
Python
0.429
question
146
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
def test_dedup_by_fee() -> None: """ We pick the solution to use for dedup based on the spend with the highest fee per cost, not based on which one would give the overall best fee per cost """ mempool = construct_mempool() def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None: ...
Considering we changed the test name and most of its body, can we parameterize old and new block generator calls and use them instead of `create_bundle_from_mempool_items` calls?
@pytest.mark.parametrize("old", [True, False]) def test_dedup_by_fee(old: bool) -> None: """ We pick the solution to use for dedup based on the spendbundle with the highest fee per cost, not based on which one would give the overall best fee per cost """ mempool = construct_mempool() def add_...
@@ -3129,69 +3109,86 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 - conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_...
chia/_tests/core/mempool/test_mempool.py
26
Python
0.571
question
178
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
We pick the solution to use for dedup based on the spend with the highest fee per cost, not based on which one would give the overall best fee per cost """ mempool = construct_mempool() def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None: sb = SpendBundle.aggregate(spend_bundles...
We keep calling `make_coin` using 0, 1 and 2 values, can we give these resulting coins names so that reading the test is easier?
""" We pick the solution to use for dedup based on the spendbundle with the highest fee per cost, not based on which one would give the overall best fee per cost """ mempool = construct_mempool() def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None: sb = SpendBundle.aggregate...
@@ -3129,69 +3109,86 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 - conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_...
chia/_tests/core/mempool/test_mempool.py
26
Python
0.5
question
128
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
# validate that dedup happens at all for sb_A result = mempool.create_bundle_from_mempool_items(test_constants, uint32(0)) assert result is not None agg, _ = result # Make sure both items would be processed assert [c.coin for c in agg.coin_spends] == [make_coin(0), make_coin(1), make_coin(2)] ...
Can we clarify what this number means?
add_spend_bundles([sb_A, sb_high_rate]) # Create a spend bundle, with a low fee, that spends the dedup coin using the same solution A sb_low_rate = make_test_spendbundle(COIN_A2, fee=10) add_spend_bundles([sb_A, sb_low_rate]) create_block = mempool.create_block_generator if old else mempool.create...
@@ -3129,69 +3109,86 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, i] for i in range(3)]) actual_fee += 3 - conditions.append([ConditionOpcode.CREATE_COIN, IDENTITY_...
chia/_tests/core/mempool/test_mempool.py
26
Python
0.071
question
38
51
51
false
use per-puzzle cost to estimate DEDUP savings
19,811
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
unf = UnfinishedBlock( finished_ss, block.reward_chain_block.get_unfinished(), block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage, block.foliage_transaction_block, block.tr...
```suggestion with pytest.raises(ValueError, matches="not found"): await client.get_block(bytes32([1] * 32)) ``` I think every test in your patch would benefit from this change
unf = UnfinishedBlock( finished_ss, block.reward_chain_block.get_unfinished(), block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage, block.foliage_transaction_block, block.tr...
@@ -88,8 +88,12 @@ async def test1( peak_block = await client.get_block(state["peak"].header_hash) assert peak_block == blocks[-1] - assert (await client.get_block(bytes32([1] * 32))) is None - + try: + await client.get_block(bytes32([1] * 32)) + except ValueError as ...
chia/_tests/core/test_full_node_rpc.py
26
Python
1
suggestion
200
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
arvidn
jack60612
def coin_record_dict_backwards_compat(coin_record: dict[str, Any]) -> dict[str, Any]: del coin_record["spent"] return coin_record class FullNodeRpcClient(RpcClient): """ Client to Chia RPC, connects to a local full node. Uses HTTP/JSON, and converts back from JSON into native python objects befor...
this looks suspicious. what if you make a request to a node by hostname and you get "host not found". Is there a good reason to not pass through the `ResponseFailureError`? This applies to the other places here too.
def coin_record_dict_backwards_compat(coin_record: dict[str, Any]) -> dict[str, Any]: del coin_record["spent"] return coin_record class FullNodeRpcClient(RpcClient): """ Client to Chia RPC, connects to a local full node. Uses HTTP/JSON, and converts back from JSON into native python objects befor...
@@ -36,11 +36,13 @@ async def get_blockchain_state(self) -> dict[str, Any]: response["blockchain_state"]["peak"] = BlockRecord.from_json_dict(response["blockchain_state"]["peak"]) return cast(dict[str, Any], response["blockchain_state"]) - async def get_block(self, header_hash: bytes32) -> Op...
chia/full_node/full_node_rpc_client.py
26
Python
0.714
bug
216
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
arvidn
jack60612
async def get_puzzle_and_solution(self, coin_id: bytes32, height: uint32) -> CoinSpend: response = await self.fetch("get_puzzle_and_solution", {"coin_id": coin_id.hex(), "height": height}) return CoinSpend.from_json_dict(response["coin_solution"]) async def get_all_mempool_tx_ids(self) -> list[...
I think comparing strings is really error prone
converted: dict[bytes32, dict[str, Any]] = {} for tx_id_hex, item in response["mempool_items"].items(): converted[bytes32.from_hexstr(tx_id_hex)] = item return converted async def get_mempool_item_by_tx_id( self, tx_id: bytes32, include_pending: bool = Fa...
@@ -256,14 +247,16 @@ async def get_mempool_item_by_tx_id( self, tx_id: bytes32, include_pending: bool = False, - ) -> Optional[dict[str, Any]]: + ) -> dict[str, Any]: try: response = await self.fetch( "get_mempool_item_by_tx_id", {"tx_id": tx_id.h...
chia/full_node/full_node_rpc_client.py
26
Python
0.214
suggestion
47
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
arvidn
jack60612
assert len(await client.get_coin_records_by_puzzle_hash(ph_receiver)) == 0 blocks = bt.get_consecutive_blocks( 2, block_list_input=blocks, guarantee_transaction_block=True, farmer_reward_puzzle_hash=ph, pool_reward_puzzle_hash=ph, ) ...
I'm pretty sure this line won't be executed. I think it would need its own `with pytest.raises(...):` context
assert len(await client.get_coin_records_by_puzzle_hash(ph_receiver)) == 0 blocks = bt.get_consecutive_blocks( 2, block_list_input=blocks, guarantee_transaction_block=True, farmer_reward_puzzle_hash=ph, pool_reward_puzzle_hash=ph, ) ...
@@ -150,8 +150,9 @@ async def test1( assert len(await client.get_all_mempool_items()) == 0 assert len(await client.get_all_mempool_tx_ids()) == 0 - assert (await client.get_mempool_item_by_tx_id(spend_bundle.name())) is None - assert (await client.get_mempool_item_by_tx_id(spend_bundle...
chia/_tests/core/test_full_node_rpc.py
26
Python
0.5
suggestion
110
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
arvidn
jack60612
full_node_api_2 = full_node_service_2._api server_1 = full_node_api_1.full_node.server server_2 = full_node_api_2.full_node.server config = bt.config self_hostname = config["self_hostname"] peer = await connect_and_get_peer(server_1, server_2, self_hostname) assert full_node_service_1.rpc_...
same comment here. I don't think this will be exercised
full_node_api_1 = full_node_service_1._api full_node_api_2 = full_node_service_2._api server_1 = full_node_api_1.full_node.server server_2 = full_node_api_2.full_node.server config = bt.config self_hostname = config["self_hostname"] peer = await connect_and_get_peer(server_1, server_2, sel...
@@ -454,17 +456,14 @@ async def test_signage_points( full_node_service_1.config, ) as client: # Only provide one - res = await client.get_recent_signage_point_or_eos(None, None) - assert res is None - res = await client.get_recent_signage_point_or_eos(std_hash(b"0"), std_hash...
chia/_tests/core/test_full_node_rpc.py
26
Python
0.214
suggestion
55
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
arvidn
jack60612
if start_height is None: start_height = 0 asyncio.run( cli_async( root_path=root_path_path, rpc_port=rpc_port, spends_with_conditions=spends_with_conditions, block_spends=block_spends, additions_and_removals=additions_and_removals, ...
an option, fyi ```suggestion except Exception: print(f"ERROR: [{height}] get_block_spends_with_conditions returned invalid result") raise ```
if start_height is None: start_height = 0 asyncio.run( cli_async( root_path=root_path_path, rpc_port=rpc_port, spends_with_conditions=spends_with_conditions, block_spends=block_spends, additions_and_removals=additions_and_removals, ...
@@ -153,29 +153,35 @@ async def node_spends_with_conditions( block_hash: bytes32, height: int, ) -> None: - result = await node_client.get_block_spends_with_conditions(block_hash) - if result is None: + try: + await node_client.get_block_spends_with_conditions(block_hash) + except Exceptio...
tools/validate_rpcs.py
26
Python
0.857
suggestion
168
51
51
false
CHIA-3396 Remove Exception Catching from node RPC
19,825
Chia-Network/chia-blockchain
10,822
Python
altendky
jack60612
retrieved_keys_values = {node.key: node.value for node in terminal_nodes} assert retrieved_keys_values == inserted_keys_values @pytest.mark.anyio @boolean_datacases(name="test_confirmation", true="confirm blobs", false="don't confirm blobs") async def test_unconfirmed_keys_values( data_store: DataStore, ...
https://docs.python.org/3.13/library/random.html#random.randbytes > _Added in version 3.9._ we're finally allowed to use `.randbytes()`! `:]` :tada: ```suggestion key = seeded_random.randbytes(size) value = seeded_random.randbytes(size) ``` this reminded me to make https://github...
terminal_nodes = await data_store.get_keys_values(store_id=store_id) retrieved_keys_values = {node.key: node.value for node in terminal_nodes} assert retrieved_keys_values == inserted_keys_values @pytest.mark.anyio @boolean_datacases(name="success", false="invalid file", true="valid file") async def tes...
@@ -2258,3 +2258,54 @@ async def test_get_keys_values_both_disk_and_db( retrieved_keys_values = {node.key: node.value for node in terminal_nodes} assert retrieved_keys_values == inserted_keys_values + + +@pytest.mark.anyio +@boolean_datacases(name="test_confirmation", true="confirm blobs", false="don't conf...
chia/_tests/core/data_layer/test_data_store.py
26
Python
0.857
suggestion
364
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
await data_store.write_tree_to_file(root, root_hash, store_id, False, writer) log.info(f"Successfully written full tree filename {filename_full_tree}.") else: log.info(f"Skipping full file generation for {existing_generation}") ...
would this be safer before the rollback? either now or in general against future refactors.
await data_store.write_tree_to_file(root, root_hash, store_id, False, writer) log.info(f"Successfully written full tree filename {filename_full_tree}.") else: log.info(f"Skipping full file generation for {existing_generation}") ...
@@ -257,6 +257,7 @@ async def insert_from_delta_file( # Don't penalize this server if we didn't download the file from it. await data_store.server_misses_file(store_id, server_info, timestamp) await data_store.rollback_to_generation(store_id, existing_generation - 1) + ...
chia/data_layer/download_data.py
26
Python
0.286
refactor
92
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
) from chia.util.batches import to_batches from chia.util.db_wrapper import SQLITE_MAX_VARIABLE_NUMBER, DBWrapper2 from chia.util.log_exceptions import log_exceptions from chia.util.lru_cache import LRUCache log = logging.getLogger(__name__) # TODO: review exceptions for values that shouldn't be displayed # TODO: pi...
```suggestion unconfirmed_keys_values: defaultdict[bytes32, list[bytes32]] = field(default_factory=functools.partial(defaultdict, list)) ```
) from chia.util.batches import to_batches from chia.util.db_wrapper import SQLITE_MAX_VARIABLE_NUMBER, DBWrapper2 from chia.util.log_exceptions import log_exceptions from chia.util.lru_cache import LRUCache log = logging.getLogger(__name__) # TODO: review exceptions for values that shouldn't be displayed # TODO: pi...
@@ -82,6 +82,7 @@ class DataStore: recent_merkle_blobs: LRUCache[bytes32, MerkleBlob] merkle_blobs_path: Path key_value_blobs_path: Path + unconfirmed_keys_values: defaultdict[bytes32, list[bytes32]]
chia/data_layer/data_store.py
26
Python
0.714
suggestion
146
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
self.unconfirmed_keys_values[store_id].append(blob_hash) except sqlite3.IntegrityError as e: if "UNIQUE constraint failed" in str(e): kv_id = await self.get_kvid(blob, store_id) if kv_id is None: raise Exception("Internal error") fr...
i... think in this case it's reasonable to attempt to continue after logging regardless of the failure. but always good to question ideas like this... ```suggestion with log_exceptions(log=log, consume=True): path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) ...
if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) self.unconfirmed_keys_values[store_id].append(blob_hash) # TOD...
@@ -659,11 +674,23 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) + async def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: + for blob_hash in self.unconfirmed_keys_value...
chia/data_layer/data_store.py
26
Python
0.929
bug
509
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
for _ in range(num_keys): use_file = seeded_random.choice([True, False]) assert tmp_data_store.prefer_db_kv_blob_length > 7 size = tmp_data_store.prefer_db_kv_blob_length + 1 if use_file else 8 key = bytes(seeded_random.getrandbits(8) for _ in range(size)) ...
not sure why ruff or mypy aren't complaining ```suggestion assert sum(1 for path in keys_value_path.rglob("*") if path.is_file()) == 0 ```
await tmp_data_store.create_tree(store_id, status=Status.COMMITTED) changelist: list[dict[str, Any]] = [] for _ in range(num_keys): use_file = seeded_random.choice([True, False]) assert tmp_data_store.prefer_db_kv_blob_length > 7 size = tmp_data_store.prefer_d...
@@ -2258,3 +2258,80 @@ async def test_get_keys_values_both_disk_and_db( retrieved_keys_values = {node.key: node.value for node in terminal_nodes} assert retrieved_keys_values == inserted_keys_values + + +@pytest.mark.anyio +@boolean_datacases(name="success", false="invalid file", true="valid file") +async d...
chia/_tests/core/data_layer/test_data_store.py
26
Python
0.714
suggestion
147
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
store_id=store_id, existing_generation=0, target_generation=1, root_hashes=[root_hash], server_info=sinfo, client_foldername=files_path, timeout=aiohttp.ClientTimeout(total=15, sock_connect=5), log=log, proxy_url="", downloader=None, ) ...
```suggestion if success: assert sum(1 for path in keys_value_path.rglob("*") if path.is_file()) > 0 else: assert sum(1 for path in keys_value_path.rglob("*") if path.is_file()) == 0 ```
is_success = await insert_from_delta_file( data_store=data_store, store_id=store_id, existing_generation=0, target_generation=1, root_hashes=[root_hash], server_info=sinfo, client_foldername=files_path, timeout=aiohttp.ClientTimeout(total=15, sock_conn...
@@ -2258,3 +2258,80 @@ async def test_get_keys_values_both_disk_and_db( retrieved_keys_values = {node.key: node.value for node in terminal_nodes} assert retrieved_keys_values == inserted_keys_values + + +@pytest.mark.anyio +@boolean_datacases(name="success", false="invalid file", true="valid file") +async d...
chia/_tests/core/data_layer/test_data_store.py
26
Python
0.786
suggestion
215
27
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
found = await anyio.to_thread.run_sync( delta_reader.collect_and_return_from_merkle_blobs, jobs, missing_hashes, ) async with self.db_wrapper.writer() as writer: await writer.executemany( """ ...
in most places we only pass a writer when it is critical for performance. that doesn't seem like it would be the case here. the nesting should just naturally work. is there another reason to be passing the writer in?
jobs, missing_hashes, ) async with self.db_wrapper.writer() as writer: await writer.executemany( """ INSERT OR IGNORE INTO nodes(store_id, hash, root_hash, generation, idx) ...
@@ -340,49 +349,48 @@ async def build_cache_and_collect_missing_hashes( log.info(f"Missing hashes: added old hashes from generation {current_generation}") async def read_from_file( - self, filename: Path, store_id: bytes32 + self, filename: Path, store_id: bytes32, writer: aiosqlite.Co...
chia/data_layer/data_store.py
26
Python
0.643
performance
219
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
async def get_terminal_node(self, kid: KeyId, vid: ValueId, store_id: bytes32) -> TerminalNode: key = await self.get_blob_from_kvid(kid.raw, store_id) value = await self.get_blob_from_kvid(vid.raw, store_id) if key is None or value is None: raise Exception("Cannot find the key/va...
what do you think of locating this down below right before the path is actually written?
value = await self.get_blob_from_kvid(vid.raw, store_id) if key is None or value is None: raise Exception("Cannot find the key/value pair") return TerminalNode(hash=leaf_hash(key, value), key=key, value=value) async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aio...
@@ -641,6 +649,8 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne store_id, ), ) + if use_file: + self.unconfirmed_keys_values[store_id].append(blob_hash)
chia/data_layer/data_store.py
26
Python
0.214
question
88
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
path.parent.mkdir(parents=True, exist_ok=True) # TODO: consider file-system based locking of either the file or the store directory path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: fo...
my first thought is to cleanup in all cases. `except Exception:` will not cleanup on async cancellation nor on ctrl+c or whatever. db wrapper uses `except:` to trigger a rollback. ```suggestion except: ```
return KeyOrValueId(row[0]) def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: for blob_hash in self.unconfirmed_keys_values[store_id]: with log_exceptions(log=log, consume=True): path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) ...
@@ -659,6 +669,32 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) + def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: + for blob_hash in self.unconfirmed_keys_values[store...
chia/data_layer/data_store.py
26
Python
1
suggestion
220
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
if "UNIQUE constraint failed" in str(e): kv_id = await self.get_kvid(blob, store_id) if kv_id is None: raise Exception("Internal error") from e return kv_id raise if row is None: raise Exception("Internal e...
```suggestion del self.unconfirmed_keys_values[store_id] ```
return kv_id raise if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) self.unconfirmed_keys_valu...
@@ -659,6 +669,32 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) + def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: + for blob_hash in self.unconfirmed_keys_values[store...
chia/data_layer/data_store.py
26
Python
0.571
suggestion
70
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
raise Exception("Internal error") from e return kv_id raise if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parent...
```suggestion del self.unconfirmed_keys_values[store_id] ```
if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) self.unconfirmed_keys_values[store_id].append(blob_hash) # TOD...
@@ -659,6 +669,32 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) + def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: + for blob_hash in self.unconfirmed_keys_values[store...
chia/data_layer/data_store.py
26
Python
0.571
suggestion
70
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) # TODO: consider file-system based locking of either the file or the store...
```suggestion d = {} if self.unconfirmed_keys_values.setdefault(store_id, d) is not d: ``` or, a bit less fancy pants... ```suggestion if store_id not in self.unconfirmed_keys_values: self.unconfirmed_keys_values[store_id] = {} else: ```
path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) self.unconfirmed_keys_values[store_id].append(blob_hash) # TODO: consider file-system based locking of either the file or the store directory ...
@@ -659,6 +669,32 @@ async def add_kvid(self, blob: bytes, store_id: bytes32, writer: aiosqlite.Conne path.write_bytes(zstd.compress(blob)) return KeyOrValueId(row[0]) + def delete_unconfirmed_kvids(self, store_id: bytes32) -> None: + for blob_hash in self.unconfirmed_keys_values[store...
chia/data_layer/data_store.py
26
Python
0.786
suggestion
294
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
from chia.util.db_wrapper import SQLITE_MAX_VARIABLE_NUMBER, DBWrapper2 from chia.util.log_exceptions import log_exceptions from chia.util.lru_cache import LRUCache log = logging.getLogger(__name__) # TODO: review exceptions for values that shouldn't be displayed # TODO: pick exception types other than Exception Ke...
```suggestion unconfirmed_keys_values: dict[bytes32, list[bytes32]] = field(default_factory=dict) ```
from chia.util.log_exceptions import log_exceptions from chia.util.lru_cache import LRUCache log = logging.getLogger(__name__) # TODO: review exceptions for values that shouldn't be displayed # TODO: pick exception types other than Exception KeyOrValueId = int64 default_prefer_file_kv_blob_length: int = 4096 @da...
@@ -82,6 +83,9 @@ class DataStore: recent_merkle_blobs: LRUCache[bytes32, MerkleBlob] merkle_blobs_path: Path key_value_blobs_path: Path + unconfirmed_keys_values: defaultdict[bytes32, list[bytes32]] = field( + default_factory=functools.partial(defaultdict, list) + )
chia/data_layer/data_store.py
26
Python
0.714
suggestion
107
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
delta_reader.collect_and_return_from_merkle_blobs, jobs, missing_hashes, ) async with self.db_wrapper.writer() as writer: await writer.executemany( """ INSERT OR IGNORE INT...
is there a reason for this to move from below up to here?
delta_reader.collect_and_return_from_merkle_blobs, jobs, missing_hashes, ) async with self.db_wrapper.writer() as writer: await writer.executemany( """ INSERT OR IGNORE INT...
@@ -342,11 +348,11 @@ async def build_cache_and_collect_missing_hashes( async def read_from_file( self, filename: Path, store_id: bytes32 ) -> tuple[dict[bytes32, tuple[bytes32, bytes32]], dict[bytes32, tuple[KeyId, ValueId]]]: - internal_nodes: dict[bytes32, tuple[bytes32, bytes32]] = {} - ...
chia/data_layer/data_store.py
26
Python
0.286
question
57
51
51
false
Cleanup keys/values db.
19,829
Chia-Network/chia-blockchain
10,822
Python
altendky
fchirica
if num == 0: return None parallel_read: bool = config["harvester"].get("parallel_read", True) v = Verifier() log.info(f"Loading plots in config.yaml using plot_manager loading code (parallel read: {parallel_read})\n") # Prompts interactively if the keyring is protected by a master passphra...
I wonder why mypy missed this earlier
if num == 0: return None parallel_read: bool = config["harvester"].get("parallel_read", True) v = Verifier() log.info(f"Loading plots in config.yaml using plot_manager loading code (parallel read: {parallel_read})\n") # Prompts interactively if the keyring is protected by a master passphra...
@@ -133,7 +133,7 @@ def check_plots( log.info("") log.info("") log.info(f"Starting to test each plot with {num} challenges each\n") - total_good_plots: Counter[str] = Counter() + total_good_plots: Counter[uint8] = Counter()
chia/plotting/check_plots.py
26
Python
0.071
suggestion
37
51
51
false
Plotmanager v2
19,832
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
config["harvester"]["decompressor_thread_count"] = decompressor_thread_count if recursive_plot_scan is not None: config["harvester"]["recursive_plot_scan"] = recursive_plot_scan if refresh_parameter is not None: config["harvester"]["plots_refresh_parameter"] = refresh...
I think this is quite slow. maybe that's fine for now. We'll probably have 6 months for optimizations between the 3.0 release and activation. An alternative would be to use the glob pattern `*.plot?`
config["harvester"]["parallel_decompressor_count"] = parallel_decompressor_count if decompressor_thread_count is not None: config["harvester"]["decompressor_thread_count"] = decompressor_thread_count if recursive_plot_scan is not None: config["harvester"]["recursive_p...
@@ -233,16 +235,22 @@ def get_filenames(directory: Path, recursive: bool, follow_links: bool) -> list[ if follow_links and recursive: import glob - files = glob.glob(str(directory / "**" / "*.plot"), recursive=True) - for file in files: + v1_file_strs = glob.glob...
chia/plotting/util.py
26
Python
0.571
performance
199
51
51
false
Plotmanager v2
19,832
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
NPM_GLOBAL="${SCRIPT_DIR}/build_scripts/npm_global" # install-gui.sh can be executed echo "cd ${NPM_GLOBAL}" cd "${NPM_GLOBAL}" if [ "$NPM_VERSION" -lt "6" ]; then # Ubuntu image of Amazon ec2 instance surprisingly uses nodejs@3.5.2 # which doesn't support `npm ci` as of 27th Jan, 2022 ...
This line should be updated to only support `npm >= 10`
NPM_GLOBAL="${SCRIPT_DIR}/build_scripts/npm_global" # install-gui.sh can be executed echo "cd ${NPM_GLOBAL}" cd "${NPM_GLOBAL}" if [ "$NPM_VERSION" -lt "6" ]; then # Ubuntu image of Amazon ec2 instance surprisingly uses nodejs@3.5.2 # which doesn't support `npm ci` as of 27th Jan, 2022 ...
@@ -70,13 +70,13 @@ do_install_npm_locally() { export N_PREFIX=${SCRIPT_DIR}/.n PATH="${N_PREFIX}/bin:$(npm prefix)/node_modules/.bin:${PATH}" export PATH - # `n 18` here installs nodejs@18 under $N_PREFIX directory - echo "n 18" - n 18 + # `n 20` here installs nodejs@20 under $N_PREFIX direc...
install-gui.sh
26
Shell
0.429
suggestion
55
51
51
false
Change minimium node version to 20 and npm version to 10
19,845
Chia-Network/chia-blockchain
10,822
Python
ChiaMineJP
emlowe
fi if [ "$(id -u)" = 0 ]; then echo "The Chia Blockchain GUI can not be installed or run by the root user." exit 1 fi # Allows overriding the branch or commit to build in chia-blockchain-gui SUBMODULE_BRANCH=$1 nodejs_is_installed() { if ! npm version >/dev/null 2>&1; then return 1 fi return 0 } do_in...
This should be `if [ "$NPM_VERSION" -lt "10" ]; then`
fi if [ "$(id -u)" = 0 ]; then echo "The Chia Blockchain GUI can not be installed or run by the root user." exit 1 fi # Allows overriding the branch or commit to build in chia-blockchain-gui SUBMODULE_BRANCH=$1 nodejs_is_installed() { if ! npm version >/dev/null 2>&1; then return 1 fi return 0 } do_in...
@@ -40,17 +40,17 @@ do_install_npm_locally() { NODEJS_VERSION="$(node -v | cut -d'.' -f 1 | sed -e 's/^v//')" NPM_VERSION="$(npm -v | cut -d'.' -f 1)" - if [ "$NODEJS_VERSION" -lt "18" ] || [ "$NPM_VERSION" -lt "9" ]; then - if [ "$NODEJS_VERSION" -lt "18" ]; then - echo "Current NodeJS version($(node ...
install-gui.sh
26
Shell
0.429
suggestion
53
51
51
false
Change minimium node version to 20 and npm version to 10
19,845
Chia-Network/chia-blockchain
10,822
Python
ChiaMineJP
emlowe
"pending_coin_removal_count": -2, } }, ), WalletStateTransition( pre_block_balance_updates={}, post_block_balance_updates={}, ), ] ) ...
i think? maybe? ```suggestion assert "0x" + b"Test".hex() in txs["transactions"][0]["memos"].values() ```
"pending_coin_removal_count": -2, } }, ), WalletStateTransition( pre_block_balance_updates={}, post_block_balance_updates={}, ), ] ) ...
@@ -587,7 +587,7 @@ async def test_wallet_clawback_sent_self(self, wallet_environments: WalletTestFr assert txs["transactions"][0]["confirmed"] assert txs["transactions"][1]["confirmed"] assert txs["transactions"][0]["memos"] != txs["transactions"][1]["memos"] - assert next(iter(txs["t...
chia/_tests/wallet/test_wallet.py
26
Python
0.714
suggestion
119
51
51
false
[CHIA-3418] Change `TransactionRecord` to use dict instead of list of tuples for memos
19,846
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
def recurse_jsonify( d: Any, next_recursion_step: Optional[Callable[[Any, Any], Any]] = None, **next_recursion_env: Any ) -> Any: """ Makes bytes objects into strings with 0x, and makes large ints into strings. """ if next_recursion_step is None: next_recursion_step = recurse_jsonify i...
we need to recurse on the key? i thought json could only have string keys in objects.
def recurse_jsonify( d: Any, next_recursion_step: Optional[Callable[[Any, Any], Any]] = None, **next_recursion_env: Any ) -> Any: """ Makes bytes objects into strings with 0x, and makes large ints into strings. """ if next_recursion_step is None: next_recursion_step = recurse_jsonify i...
@@ -303,7 +303,9 @@ def recurse_jsonify( elif isinstance(d, dict): new_dict = {} for name, val in d.items(): - new_dict[name] = next_recursion_step(val, None, **next_recursion_env) + new_dict[next_recursion_step(name, None, **next_recursion_env)] = next_recursion_step(
chia/util/streamable.py
26
Python
0.286
suggestion
86
51
51
false
[CHIA-3418] Change `TransactionRecord` to use dict instead of list of tuples for memos
19,846
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
rows = await conn.execute_fetchall( "SELECT confirmed_index, spent_index, coinbase, puzzle_hash, " "coin_parent, amount, timestamp, coin_name FROM coin_record WHERE confirmed_index>?", (block_index,), ) for row in rows: ...
```suggestion record = CoinRecord(coin, row[0], uint32(0), row[2] != 0, row[6]) ```
""" Note that block_index can be negative, in which case everything is rolled back Returns a map of coin ID to coin record for modified items. """ coin_changes: dict[bytes32, CoinRecord] = {} # Add coins that are confirmed in the reverted blocks to the list of updated co...
@@ -574,7 +583,8 @@ async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecord] ) for row in rows: coin = self.row_to_coin(row) - record = CoinRecord(coin, row[0], uint32(0), row[2], row[6]) + coinbase = False if row[2] == 0 e...
chia/full_node/coin_store.py
26
Python
0.714
suggestion
101
51
51
false
Import check_time_locks() and CoinRecord
19,848
Chia-Network/chia-blockchain
10,822
Python
arvidn
matt-o-how
async with self.db_wrapper.writer_maybe_transaction() as conn: rows = await conn.execute_fetchall( "SELECT confirmed_index, spent_index, coinbase, puzzle_hash, " "coin_parent, amount, timestamp, coin_name FROM coin_record WHERE confirmed_index>?", (blo...
I would suggest this or the alternative below. ```suggestion coinbase = row[2] != 0 ```
async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecord]: """ Note that block_index can be negative, in which case everything is rolled back Returns a map of coin ID to coin record for modified items. """ coin_changes: dict[bytes32, CoinRecord] = {} ...
@@ -574,7 +583,8 @@ async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecord] ) for row in rows: coin = self.row_to_coin(row) - record = CoinRecord(coin, row[0], uint32(0), row[2], row[6]) + coinbase = False if row[2] == 0 e...
chia/full_node/coin_store.py
26
Python
0.714
suggestion
106
51
51
false
Import check_time_locks() and CoinRecord
19,848
Chia-Network/chia-blockchain
10,822
Python
arvidn
matt-o-how
(make_test_conds(birth_height=10), None), (make_test_conds(birth_height=11), Err.ASSERT_MY_BIRTH_HEIGHT_FAILED), # coin timestamp is 10000 (make_test_conds(birth_seconds=uint64(COIN_TIMESTAMP - 1)), Err.ASSERT_MY_BIRTH_SECONDS_FAILED), (make_test_conds(birth_s...
this is the rust function. I don't think it will ever return `Err`, will it? It looks like `res` is mistyped
(make_test_conds(birth_height=10), None), (make_test_conds(birth_height=11), Err.ASSERT_MY_BIRTH_HEIGHT_FAILED), # coin timestamp is 10000 (make_test_conds(birth_seconds=uint64(COIN_TIMESTAMP - 1)), Err.ASSERT_MY_BIRTH_SECONDS_FAILED), (make_test_conds(birth_s...
@@ -436,15 +436,17 @@ def test_conditions( conds: SpendBundleConditions, expected: Err | None, ) -> None: - assert ( - check_time_locks( - dict(self.REMOVALS), - conds, - self.PREV_BLOCK_HEIGHT, - self.PREV_BLOCK_TIMEST...
chia/_tests/core/mempool/test_mempool_manager.py
26
Python
0.643
suggestion
108
51
51
false
Import check_time_locks() and CoinRecord
19,848
Chia-Network/chia-blockchain
10,822
Python
arvidn
matt-o-how
# reserve fee cannot be greater than UINT64_MAX per consensus rule. # run_generator() would fail assert_fee_sum = uint64(0 if conds is None else conds.reserve_fee) # 17. Check that the assert fee sum <= fees, and that each reserved fee is non-negative if fees < assert_fee_sum: return Err.R...
I think it would be good to clarify that `error` is `int | None` here too. It is, right?
# reserve fee cannot be greater than UINT64_MAX per consensus rule. # run_generator() would fail assert_fee_sum = uint64(0 if conds is None else conds.reserve_fee) # 17. Check that the assert fee sum <= fees, and that each reserved fee is non-negative if fees < assert_fee_sum: return Err.R...
chia/consensus/block_body_validation.py
26
Python
0.5
question
88
41
41
false
Import check_time_locks() and CoinRecord
19,848
Chia-Network/chia-blockchain
10,822
Python
arvidn
matt-o-how
""" This function checks for double spends, unknown spends and conflicting transactions in mempool. Returns Error (if any), the set of existing MempoolItems with conflicting spends (if any). Note that additions are not checked for duplicates, because having duplicate additions requires also having d...
Am I understanding this correctly, that the underlying issue is that we change `latest_singleton_lineage.coin_id` without updating the corresponding dictionary key in `item.bundle_coin_spends`.
""" This function checks for double spends, unknown spends and conflicting transactions in mempool. Returns Error (if any), the set of existing MempoolItems with conflicting spends (if any). Note that additions are not checked for duplicates, because having duplicate additions requires also having d...
@@ -258,7 +258,22 @@ def check_removals( for item in conflicting_items: if item in conflicts: continue - conflict_bcs = item.bundle_coin_spends[coin_id] + conflict_bcs = item.bundle_coin_spends.get(coin_id) + if conflict_bcs is None: + ...
chia/full_node/mempool_manager.py
26
Python
0.571
suggestion
193
51
51
false
CHIA-3484 Handle items that spend an older ff version when newer lineage exists
19,865
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
async with self.db_wrapper.reader_no_transaction() as conn: async with conn.execute( "SELECT header_hash,block_record FROM full_blocks " "WHERE height >= ? AND height <= ? AND in_main_chain=1", (start, stop), ) as cursor: fo...
```suggestion assert self.db_wrapper.db_version == 2 ```
async with self.db_wrapper.reader_no_transaction() as conn: async with conn.execute( "SELECT header_hash,block_record FROM full_blocks " "WHERE height >= ? AND height <= ? AND in_main_chain=1", (start, stop), ) as cursor: fo...
@@ -468,7 +478,8 @@ async def get_block_bytes_in_range( No orphan blocks. """ - assert self.db_wrapper.db_version == 2 + if self.db_wrapper.db_version != 2: + raise RuntimeError("get_block_bytes_in_range requires DB version 2")
chia/full_node/block_store.py
26
Python
0.571
suggestion
66
51
51
false
Simplify `BlockStore`
19,880
Chia-Network/chia-blockchain
10,822
Python
arvidn
richardkiss
for a in range(start, end): if peak_height < uint32(a): self.service.log.warning("requested block is higher than known peak ") break header_hash: Optional[bytes32] = self.service.blockchain.height_to_hash(uint32(a)) if header_hash is None: ...
just drop it entirely then? ```suggestion ```
for a in range(start, end): if peak_height < uint32(a): self.service.log.warning("requested block is higher than known peak ") break header_hash: Optional[bytes32] = self.service.blockchain.height_to_hash(uint32(a)) if header_hash is None: ...
@@ -481,10 +481,10 @@ async def get_block_spends(self, request: dict[str, Any]) -> EndpointResult: if full_block is None: raise ValueError(f"Block {header_hash.hex()} not found") - spends: list[dict[str, list[CoinSpend]]] = [] + spends: dict[str, list[CoinSpend]]
chia/full_node/full_node_rpc_api.py
26
Python
0.429
suggestion
46
51
51
false
Bump chia rs 0.28
19,891
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
*(PluginRemote.unmarshal(marshalled=marshalled) for marshalled in new_uploaders), *conf_file_uploaders, ] old_downloaders = config["data_layer"].get("downloaders", []) new_downloaders = plugins_config.get("downloaders", []) conf_file_uploaders = await load_plugin_configurations(service_...
[nitpick] The trailing comma added here is inconsistent with the existing code style and appears unnecessary for a single function call argument. ```suggestion enable=os.environ.get(f"CHIA_INSTRUMENT_{SERVICE_NAME.upper()}") is not None ```
*(PluginRemote.unmarshal(marshalled=marshalled) for marshalled in new_uploaders), *conf_file_uploaders, ] old_downloaders = config["data_layer"].get("downloaders", []) new_downloaders = plugins_config.get("downloaders", []) conf_file_uploaders = await load_plugin_configurations(service_...
@@ -143,7 +144,7 @@ def main() -> int: root_path = resolve_root_path(override=None) with maybe_manage_task_instrumentation( - enable=os.environ.get(f"CHIA_INSTRUMENT_{SERVICE_NAME.upper()}") is not None + enable=os.environ.get(f"CHIA_INSTRUMENT_{SERVICE_NAME.upper()}") is not None,
chia/data_layer/start_data_layer.py
26
Python
0.786
suggestion
248
33
33
false
Simplify dependencies wrt `chia.server`
19,895
Chia-Network/chia-blockchain
10,822
Python
Copilot
richardkiss
import os import pathlib import sys from typing import Any, Optional from chia_rs import ConsensusConstants from chia.apis import ApiProtocolRegistry from chia.consensus.constants import replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS, update_testnet_overrides from chia.protocols.o...
is this related to the other changes?
import os import pathlib import sys from typing import Any, Optional from chia_rs import ConsensusConstants from chia.apis import ApiProtocolRegistry from chia.consensus.constants import replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS, update_testnet_overrides from chia.protocols.o...
@@ -11,21 +11,18 @@ from chia.consensus.constants import replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS, update_testnet_overrides from chia.protocols.outbound_message import NodeType -from chia.server.aliases import TimelordService from chia.server.resolve_peer_info import get_u...
chia/timelord/start_timelord.py
26
Python
0.143
question
37
51
51
false
Simplify dependencies wrt `chia.server`
19,895
Chia-Network/chia-blockchain
10,822
Python
altendky
richardkiss
async def create_full_node_service( root_path: pathlib.Path, config: dict[str, Any], consensus_constants: ConsensusConstants, connect_to_daemon: bool = True, override_capabilities: Optional[list[tuple[uint16, str]]] = None, ) -> FullNodeService: service_config = config[SERVICE_NAME] network...
at a glance anyways, i like this change. i think it should be applied either consistently or not at all. or maybe not at all here and consistently in another pr. whatever.
async def create_full_node_service( root_path: pathlib.Path, config: dict[str, Any], consensus_constants: ConsensusConstants, connect_to_daemon: bool = True, override_capabilities: Optional[list[tuple[uint16, str]]] = None, ) -> FullNodeService: service_config = config[SERVICE_NAME] network...
@@ -56,7 +56,7 @@ async def create_full_node_service( if service_config.get("start_rpc_server", True): rpc_info = (FullNodeRpcApi, service_config["rpc_port"]) - return Service( + return FullNodeService(
chia/full_node/start_full_node.py
26
Python
0.429
suggestion
174
51
51
false
Simplify dependencies wrt `chia.server`
19,895
Chia-Network/chia-blockchain
10,822
Python
altendky
richardkiss
from __future__ import annotations import os import pathlib import sys from typing import Any, Optional from chia.apis import ApiProtocolRegistry from chia.full_node.full_node_rpc_api import FullNodeRpcApi from chia.introducer.introducer import Introducer from chia.introducer.introducer_api import IntroducerAPI from ...
i think, for consistency, this belongs in a new file `chia/introducer/introducer_service.py`?
from __future__ import annotations import os import pathlib import sys from typing import Any, Optional from chia.apis import ApiProtocolRegistry from chia.introducer.introducer import Introducer from chia.introducer.introducer_api import IntroducerAPI from chia.introducer.introducer_service import IntroducerService ...
@@ -22,6 +22,8 @@ SERVICE_NAME = "introducer" +IntroducerService = Service[Introducer, IntroducerAPI, FullNodeRpcApi] +
chia/introducer/start_introducer.py
26
Python
0.357
question
93
51
51
false
Simplify dependencies wrt `chia.server`
19,895
Chia-Network/chia-blockchain
10,822
Python
altendky
richardkiss
rows_updated: int = 0 for batch in to_batches(coin_names, SQLITE_MAX_VARIABLE_NUMBER): name_params = ",".join(["?"] * len(batch.entries)) ret: Cursor = await conn.execute( f"UPDATE coin_record INDEXED BY sqlite_autoindex_coin_record_1 " ...
it seems really unlikely that performing 2 queries instead of 1 would ever be faster. If we want to do this, I think `CoinStore` would have to know which index to use. I also think we need more than a hunch to put this in the release branch
async def _set_spent(self, coin_names: list[bytes32], index: uint32) -> None: assert len(coin_names) == 0 or index > 0 if len(coin_names) == 0: return None async with self.db_wrapper.writer_maybe_transaction() as conn: rows_updated: int = 0 for batch in ...
@@ -634,11 +636,19 @@ async def _set_spent(self, coin_names: list[bytes32], index: uint32) -> None: # Lookup the most recent unspent lineage that matches a puzzle hash async def get_unspent_lineage_info_for_puzzle_hash(self, puzzle_hash: bytes32) -> Optional[UnspentLineageInfo]: async with self.db_wr...
chia/full_node/coin_store.py
26
Python
0.643
suggestion
240
51
51
false
CHIA-3595 Be explicit about falling back to coin_puzzle_hash index in get_unspent_lineage_info_for_puzzle_hash
19,909
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
log.info("DB: Creating index coin_parent_index") await conn.execute("CREATE INDEX IF NOT EXISTS coin_parent_index on coin_record(coin_parent)") async with conn.execute("SELECT 1 FROM coin_record LIMIT 1") as cursor: is_new_db = await cursor.fetchone() is None ...
this is not right. you only use the new index on the first ever run of the full node. You should base this in whether the index exists or not
log.info("DB: Creating index coin_parent_index") await conn.execute("CREATE INDEX IF NOT EXISTS coin_parent_index on coin_record(coin_parent)") async with conn.execute("SELECT 1 FROM coin_record LIMIT 1") as cursor: is_new_db = await cursor.fetchone() is None ...
@@ -82,6 +85,7 @@ async def create(cls, db_wrapper: DBWrapper2) -> CoinStore: WHERE spent_index = -1 """ ) + self._unspent_lineage_for_ph_idx = "coin_record_ph_ff_unspent_idx"
chia/full_node/coin_store.py
26
Python
0.429
suggestion
141
51
51
false
CHIA-3595 Be explicit about falling back to coin_puzzle_hash index in get_unspent_lineage_info_for_puzzle_hash
19,909
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
assert newer_block.timestamp is not None and older_block.timestamp is not None if newer_block.height == older_block.height: # small chain not long enough to have a block in between return None average_block_time = uint32( (newer_block.timestamp - older_block.timestamp) / (newer_block.hei...
this doesn't seem to improve throughput of these RPCs. It's not clear to me why, perhaps there's only a single `asyncio.Task` per RPC connection. In either case, compute heavy work should not be performed on the main thread.
older_block = await get_nearest_transaction_block(blockchain, prev_block) assert newer_block.timestamp is not None and older_block.timestamp is not None if newer_block.height == older_block.height: # small chain not long enough to have a block in between return None average_block_time = uint...
@@ -98,6 +101,7 @@ def __init__(self, service: FullNode) -> None: self.service = service self.service_name = "chia_full_node" self.cached_blockchain_state: Optional[dict[str, Any]] = None + self.executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="node-rpc-")
chia/full_node/full_node_rpc_api.py
26
Python
0.786
suggestion
224
51
51
false
fix validate_rpcs. Run RPC compute heavy jobs in a thread pool
19,922
Chia-Network/chia-blockchain
10,822
Python
arvidn
arvidn
# Set initial values for the loop pipeline: set[asyncio.Task[None]] = set() completed_requests: int = 0 # measure time for performance measurement per segment cycle_start: float = time.monotonic() # also measure time for the whole process start_time: float = cyc...
when running this tool for all 3 RPC calls, each iteration adds 3 pending tasks, but only one was popped off. Without this change, `pipeline` is allowed to grow indefinitely.
# Set initial values for the loop pipeline: set[asyncio.Task[None]] = set() completed_requests: int = 0 # measure time for performance measurement per segment cycle_start: float = time.monotonic() # also measure time for the whole process start_time: float = cyc...
@@ -238,7 +238,7 @@ def add_tasks_for_height(height: int) -> None: for i in range(start_height, end_height + 1): add_tasks_for_height(height=i) # Make Status Updates. - if len(pipeline) >= pipeline_depth: + while len(pipeline) >= pipeline_depth:
tools/validate_rpcs.py
26
Python
0.571
suggestion
174
51
51
false
fix validate_rpcs. Run RPC compute heavy jobs in a thread pool
19,922
Chia-Network/chia-blockchain
10,822
Python
arvidn
arvidn
""" The harvester receives a new signage point from the farmer, this happens at the start of each slot. The harvester does a few things: 1. The harvester applies the plot filter for each of the plots, to select the proportion which are eligible for this signage point and challeng...
i would change to calculate_requierd_strength since the plot strength itself is fixed in the plot and returned in the proof bytes, i think this name is confusing, the var name should be requierd_strength as well
peer: WSChiaConnection, ) -> int: proofs_found = 0 for filename_sublist_awaitable in asyncio.as_completed(awaitables): filename, sublist = await filename_sublist_awaitable time_taken = time.monotonic() - start_time if time_taken > 8: self.h...
@@ -95,6 +96,8 @@ async def new_signage_point_harvester( start = time.monotonic() assert len(new_challenge.challenge_hash) == 32 + plot_strength = calculate_plot_strength(self.harvester.constants, new_challenge.last_tx_height)
chia/harvester/harvester_api.py
26
Python
0.5
suggestion
212
51
51
false
[CHIA-3654] [CHIA-3537] [CHIA-3673] stub chiapos2 API
19,969
Chia-Network/chia-blockchain
10,822
Python
almogdepaz
arvidn
proof_xs, ), ) ) return responses except Exception as e: self.harvester.log.error(f"Unknown error: {e}") return [] ...
im not sure that we would want the filtering done in the prover and not in chia-blockchain for maintainability, unless we expect to wrap the v2prover like we did with v1 then we can filter in the wrapper also this is not relevant to v1 plots right ? so im leaning into doing the filtering here in new_signage_point on...
size = plot_info.prover.get_size().size_v2 assert size is not None return PartialProofsData( new_challenge.challenge_hash, new_challenge.sp_hash, good_partial_proofs[0].hex() + str(filename.resolve()), ...
@@ -108,7 +111,7 @@ def blocking_lookup(filename: Path, plot_info: PlotInfo) -> list[tuple[bytes32, new_challenge.sp_hash, ) try: - quality_strings = plot_info.prover.get_qualities_for_challenge(sp_challenge_hash) + quality_str...
chia/harvester/harvester_api.py
26
Python
0.429
suggestion
364
51
51
false
[CHIA-3654] [CHIA-3537] [CHIA-3673] stub chiapos2 API
19,969
Chia-Network/chia-blockchain
10,822
Python
almogdepaz
arvidn
""" The harvester receives a new signage point from the farmer, this happens at the start of each slot. The harvester does a few things: 1. The harvester applies the plot filter for each of the plots, to select the proportion which are eligible for this signage point and challeng...
i think change var to required_plot_strength as well
""" The harvester receives a new signage point from the farmer, this happens at the start of each slot. The harvester does a few things: 1. The harvester applies the plot filter for each of the plots, to select the proportion which are eligible for this signage point and challeng...
@@ -152,6 +153,8 @@ async def new_signage_point_harvester( start = time.monotonic() assert len(new_challenge.challenge_hash) == 32 + plot_strength = calculate_required_plot_strength(self.harvester.constants, new_challenge.last_tx_height)
chia/harvester/harvester_api.py
26
Python
0.286
suggestion
52
51
51
false
[CHIA-3654] [CHIA-3537] [CHIA-3673] stub chiapos2 API
19,969
Chia-Network/chia-blockchain
10,822
Python
almogdepaz
arvidn
assert prover.get_version() == PlotVersion.V2 assert prover.get_filename() == "/nonexistent/path/test.plot2" def test_v2_prover_get_size_raises_error(self) -> None: prover = V2Prover("/nonexistent/path/test.plot2") with pytest.raises(NotImplementedError, match="V2 plot format is not...
should be AssertionError error right ?
assert prover.get_version() == PlotVersion.V2 assert prover.get_filename() == "/nonexistent/path/test.plot2" def test_v2_prover_get_size_raises_error(self) -> None: prover = V2Prover("/nonexistent/path/test.plot2") with pytest.raises(NotImplementedError, match="V2 plot format is not...
@@ -38,7 +38,9 @@ def test_v2_prover_get_id_raises_error(self) -> None: def test_v2_prover_get_qualities_for_challenge_raises_error(self) -> None: prover = V2Prover("/nonexistent/path/test.plot2") - with pytest.raises(NotImplementedError, match="V2 plot format is not yet implemented"): + w...
chia/_tests/plotting/test_prover.py
26
Python
0.286
question
38
51
51
false
[CHIA-3654] [CHIA-3537] [CHIA-3673] stub chiapos2 API
19,969
Chia-Network/chia-blockchain
10,822
Python
almogdepaz
arvidn
return except RuntimeError as e: if str(e) == "GRResult_NoProof received": log.info(f"Proof dropped due to line point compression. Filepath: {plot_path}") continue else: lo...
what if your plots are not on a machine with a GPU ?
return except RuntimeError as e: if str(e) == "GRResult_NoProof received": log.info(f"Proof dropped due to line point compression. Filepath: {plot_path}") continue else: lo...
@@ -201,12 +217,17 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: caught_exception = True break - for index, quality_str in enumerate(qualities): + for index, proof in enumerate(proofs): # ...
chia/plotting/check_plots.py
26
Python
0.214
question
54
51
51
false
[CHIA-3701] Check plots v2
19,982
Chia-Network/chia-blockchain
10,822
Python
almogdepaz
arvidn
d: Optional[uint8] @streamable @dataclass(frozen=True) class PostInitTestClassList(Streamable): a: list[uint8] b: list[list[G1Element]] @streamable @dataclass(frozen=True) class PostInitTestClassTuple(Streamable): a: tuple[uint8, str] b: tuple[tuple[uint8, str], bytes32] @streamable @dataclass...
how about different names just to avoid confusion with `enum.IntEnum` and `enum.StrEnum`.
d: Optional[uint8] @streamable @dataclass(frozen=True) class PostInitTestClassList(Streamable): a: list[uint8] b: list[list[G1Element]] @streamable @dataclass(frozen=True) class PostInitTestClassTuple(Streamable): a: tuple[uint8, str] b: tuple[tuple[uint8, str], bytes32] @streamable @dataclass...
@@ -423,6 +445,25 @@ class PostInitTestClassDict(Streamable): b: dict[bytes32, dict[uint8, str]] +@streamable_enum(uint32) +class IntEnum(Enum):
chia/_tests/core/util/test_streamable.py
26
Python
0.429
suggestion
89
51
51
false
[CHIA-3703] Add Enum support to streamable
19,983
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
with pytest.raises(AssertionError): TestClassOptional.from_bytes(bytes([])) TestClassOptional.from_bytes(bytes([0])) TestClassOptional.from_bytes(bytes([1, 2])) def test_ambiguous_deserialization_int() -> None: @streamable @dataclass(frozen=True) class TestClassUint(Streamable): ...
is there a clear `message=` that could be passed?
with pytest.raises(AssertionError): TestClassOptional.from_bytes(bytes([])) TestClassOptional.from_bytes(bytes([0])) TestClassOptional.from_bytes(bytes([1, 2])) def test_ambiguous_deserialization_int() -> None: @streamable @dataclass(frozen=True) class TestClassUint(Streamable): ...
@@ -623,6 +671,17 @@ class TestClassUint(Streamable): TestClassUint.from_bytes(b"\x00\x00") +def test_ambiguous_deserialization_int_enum() -> None: + @streamable + @dataclass(frozen=True) + class TestClassIntEnum(Streamable): + a: IntEnum + + # Does not have the required uint size + w...
chia/_tests/core/util/test_streamable.py
26
Python
0.286
question
49
51
51
false
[CHIA-3703] Add Enum support to streamable
19,983
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
# Does not have the required elements with pytest.raises(AssertionError): TestClassOptional.from_bytes(bytes([])) TestClassOptional.from_bytes(bytes([0])) TestClassOptional.from_bytes(bytes([1, 2])) def test_ambiguous_deserialization_int() -> None: @streamable @dataclass(frozen=True) ...
i totally misread this at first. maybe... ```suggestion # passed bytes are incorrect size for serialization proxy ```
# Does not have the required elements with pytest.raises(AssertionError): TestClassOptional.from_bytes(bytes([])) TestClassOptional.from_bytes(bytes([0])) TestClassOptional.from_bytes(bytes([1, 2])) def test_ambiguous_deserialization_int() -> None: @streamable @dataclass(frozen=True) ...
@@ -623,6 +671,17 @@ class TestClassUint(Streamable): TestClassUint.from_bytes(b"\x00\x00") +def test_ambiguous_deserialization_int_enum() -> None: + @streamable + @dataclass(frozen=True) + class TestClassIntEnum(Streamable): + a: IntEnum + + # Does not have the required uint size
chia/_tests/core/util/test_streamable.py
26
Python
0.714
bug
124
51
51
false
[CHIA-3703] Add Enum support to streamable
19,983
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
class TestClassTuple(Streamable): a: tuple[uint8, str] # Does not have the required elements with pytest.raises(AssertionError): TestClassTuple.from_bytes(bytes([0, 0, 100, 24])) def test_ambiguous_deserialization_str() -> None: @streamable @dataclass(frozen=True) class TestCl...
same comment as above and my misunderstanding, but, i'm not sure i understand. is the `StrEnum` implicitly configured for only three character strings because that's what the two values are? or is this more generally saying the bytes don't match any of the values? or...
class TestClassTuple(Streamable): a: tuple[uint8, str] # Does not have the required elements with pytest.raises(AssertionError): TestClassTuple.from_bytes(bytes([0, 0, 100, 24])) def test_ambiguous_deserialization_str() -> None: @streamable @dataclass(frozen=True) class TestCl...
@@ -656,6 +715,17 @@ class TestClassStr(Streamable): TestClassStr.from_bytes(bytes([0, 0, 100, 24, 52])) +def test_ambiguous_deserialization_str_enum() -> None: + @streamable + @dataclass(frozen=True) + class TestClassStr(Streamable): + a: StrEnum + + # Does not have the required str siz...
chia/_tests/core/util/test_streamable.py
26
Python
0.643
suggestion
273
51
51
false
[CHIA-3703] Add Enum support to streamable
19,983
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
@streamable @dataclasses.dataclass(frozen=True) class VersionedBlob(Streamable): version: uint16 blob: bytes @streamable @dataclasses.dataclass(frozen=True) class UInt32Range(Streamable): start: uint32 = uint32(0) stop: uint32 = uint32.MAXIMUM @streamable @dataclasses.dataclass(frozen=True) class U...
this, or can we require the proxy itself be streamable? ```suggestion def streamable_enum(proxy: type[object]) -> Callable[[_T_Enum], _T_Enum]: ``` maybe not in this pr, but maybe we need a type that is like a union of the rust streamableness and `Streamable`. or...
@streamable @dataclasses.dataclass(frozen=True) class VersionedBlob(Streamable): version: uint16 blob: bytes @streamable @dataclasses.dataclass(frozen=True) class UInt32Range(Streamable): start: uint32 = uint32(0) stop: uint32 = uint32.MAXIMUM @streamable @dataclasses.dataclass(frozen=True) class U...
@@ -700,3 +714,15 @@ class UInt32Range(Streamable): class UInt64Range(Streamable): start: uint64 = uint64(0) stop: uint64 = uint64.MAXIMUM + + +_T_Enum = TypeVar("_T_Enum", bound=EnumMeta) + + +def streamable_enum(proxy: type[Any]) -> Callable[[_T_Enum], _T_Enum]:
chia/util/streamable.py
26
Python
0.929
suggestion
269
33
33
false
[CHIA-3703] Add Enum support to streamable
19,983
Chia-Network/chia-blockchain
10,822
Python
altendky
Quexington
if ret.assert_before_height is not None: ret.assert_before_height = min(ret.assert_before_height, h) else: ret.assert_before_height = h if spend.before_seconds_relative is not None: s = uint64(removal_coin_records[bytes32(spend.coin_id)].times...
I think `transaction_id` is a difficult term. Are these spend bundle IDs? If so, I think that would be a better name
if ret.assert_before_height is not None: ret.assert_before_height = min(ret.assert_before_height, h) else: ret.assert_before_height = h if spend.before_seconds_relative is not None: s = uint64(removal_coin_records[bytes32(spend.coin_id)].times...
@@ -133,17 +133,10 @@ class SpendBundleAddInfo: @dataclass class NewPeakInfo: - items: list[NewPeakItem] + transaction_ids: list[bytes32]
chia/full_node/mempool_manager.py
26
Python
0.571
suggestion
116
51
51
false
CHIA-3704 Optimize peak post processing by using transaction IDs instead of NewPeakItem elements
19,985
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
mempool_new_peak_result = await self.mempool_manager.new_peak(self.blockchain.get_tx_peak(), spent_coins) return PeakPostProcessingResult( mempool_new_peak_result.transaction_ids, mempool_new_peak_result.removals, fns_peak_result, hints_to_add, ...
where is `mempool_peak_added_tx_ids` initialized?
mempool_new_peak_result = await self.mempool_manager.new_peak(self.blockchain.get_tx_peak(), spent_coins) return PeakPostProcessingResult( mempool_new_peak_result.spend_bundle_ids, mempool_new_peak_result.removals, fns_peak_result, hints_to_add, ...
@@ -1961,9 +1963,9 @@ async def peak_post_processing_2( record = state_change_summary.peak for signage_point in ppp_result.signage_points: await self.signage_point_post_processing(*signage_point) - for new_peak_item in ppp_result.mempool_peak_result: - self.log.debug(f"A...
chia/full_node/full_node.py
26
Python
0.214
question
49
51
51
false
CHIA-3704 Optimize peak post processing by using transaction IDs instead of NewPeakItem elements
19,985
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
compose_rate_limits_cache: dict[int, dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]]] = {} # this class is used to configure the *rate* limit for a message type. The # limits are counts and size per 60 seconds. @dataclasses.dataclass(frozen=True) class RLSettings: # if true, messages affect and are limit...
not sure it's wrong, but it seems a bit odd that `aggregate_limit.aggregate_limit` is `False`. maybe this value is unused. > [!NOTE] > just formatting change here for clarity ```suggestion aggregate_limit = RLSettings( aggregate_limit=False, frequency=1000, max_size=100 * 1024**3, max_total_size=100...
# this class is used to configure the *rate* limit for a message type. The # limits are counts and size per 60 seconds. @dataclasses.dataclass(frozen=True) class RLSettings: # if true, messages affect and are limited by the per connection aggregate limiter, # which affects messages across message types ag...
@@ -31,186 +33,159 @@ class Unlimited: max_size: int # Max size of each request -def get_rate_limits_to_use(our_capabilities: list[Capability], peer_capabilities: list[Capability]) -> dict[str, Any]: +aggregate_limit = RLSettings(False, 1000, 100 * 1024 * 1024 * 1024, 100 * 1024 * 1024 * 1024)
chia/server/rate_limit_numbers.py
26
Python
0.857
bug
811
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
# this class is used to indicate that a message type is not subject to a rate # limit, but just a per-message size limit. This may be appropriate for response # messages that are implicitly limited by their corresponding request message # Unlimited message types are also not subject to the overall limit across all # m...
i personally find literals to be tidy, clear, non-mutating, and very flexible. ```suggestion composed = { **rate_limits[1], **rate_limits[2], ) ```
# this class is used to indicate that a message type is not subject to a rate # limit, but just a per-message size limit. This may be appropriate for response # messages that are implicitly limited by their corresponding request message # Unlimited message types are also not subject to the overall limit across all # me...
@@ -31,186 +33,159 @@ class Unlimited: max_size: int # Max size of each request -def get_rate_limits_to_use(our_capabilities: list[Capability], peer_capabilities: list[Capability]) -> dict[str, Any]: +aggregate_limit = RLSettings(False, 1000, 100 * 1024 * 1024 * 1024, 100 * 1024 * 1024 * 1024) + + +def get_ra...
chia/server/rate_limit_numbers.py
26
Python
0.714
suggestion
189
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
self.message_counts = Counter() self.message_cumulative_sizes = Counter() self.non_tx_message_counts = 0 self.non_tx_cumulative_size = 0 try: message_type = ProtocolMessageTypes(message.type) except Exception as e: log.warning(f"Inv...
is this accurate? do we mean to also be checking non-zero as the existing code does? ```suggestion assert agg_limit.max_total_size is not None ```
self.message_counts = Counter() self.message_cumulative_sizes = Counter() self.non_tx_message_counts = 0 self.non_tx_cumulative_size = 0 try: message_type = ProtocolMessageTypes(message.type) except Exception as e: log.warning(f"Inv...
@@ -80,40 +80,34 @@ def process_msg_and_check( proportion_of_limit: float = self.percentage_of_limit / 100 ret: bool = False - rate_limits = get_rate_limits_to_use(our_capabilities, peer_capabilities) + rate_limits: dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]] + rate...
chia/server/rate_limits.py
26
Python
0.714
question
164
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
current_slot = int(self.get_time() // self.reset_seconds) if current_slot != self.current_slot: self.current_slot = current_slot self.message_counts = Counter() self.message_cumulative_sizes = Counter() self.non_tx_message_counts = 0 self.non_t...
maybe worth keeping around an error message? like `limits = rate_limits.get(message_type)` and `if limits is None:`. anyways, could at least be: ```suggestion limits: Union[RLSettings, Unlimited] = rate_limits[message_type] ``` or to avoid accidentally expanding the type at some point ```suggestion ...
current_slot = int(self.get_time() // self.reset_seconds) if current_slot != self.current_slot: self.current_slot = current_slot self.message_counts = Counter() self.message_cumulative_sizes = Counter() self.non_tx_message_counts = 0 self.non_t...
@@ -80,40 +80,34 @@ def process_msg_and_check( proportion_of_limit: float = self.percentage_of_limit / 100 ret: bool = False - rate_limits = get_rate_limits_to_use(our_capabilities, peer_capabilities) + rate_limits: dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]] + rate...
chia/server/rate_limits.py
26
Python
1
suggestion
367
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
# This will use the newest possible rate limits that both peers support. At this time there are only two # options, v1 and v2. if Capability.RATE_LIMITS_V2 in our_capabilities and Capability.RATE_LIMITS_V2 in peer_capabilities: # Use V2 rate limits if 2 in compose_rate_limits_cache: ...
would be nice to have a test (in tests) maybe like... ``` @pytest.mark.parametrize(argnames="version", argvalues=[1, 2]) def test_rate_limits_complete(version: int) -> None: assert set(rate_limits[version].keys()) == set(ProtocolMessageTypes) ``` something about the 1 and 2 as well. maybe also tieing them to the...
def get_rate_limits_to_use( our_capabilities: list[Capability], peer_capabilities: list[Capability] ) -> tuple[dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]], RLSettings]: # This will use the newest possible rate limits that both peers support. At this time there are only two # options, v1 and v...
@@ -31,186 +33,159 @@ class Unlimited: max_size: int # Max size of each request -def get_rate_limits_to_use(our_capabilities: list[Capability], peer_capabilities: list[Capability]) -> dict[str, Any]: +aggregate_limit = RLSettings(False, 1000, 100 * 1024 * 1024 * 1024, 100 * 1024 * 1024 * 1024) + + +def get_ra...
chia/server/rate_limit_numbers.py
26
Python
0.929
suggestion
352
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
# * number of bytes / 60 seconds for transaction messages @pytest.mark.anyio @boolean_datacases(name="incoming", true="incoming", false="outgoing") @boolean_datacases(name="tx_msg", true="tx", false="non-tx") @boolean_datacases(name="limit_size", true="size-limit", false="count-limit") async def test_limits_v2(incomi...
is the intent of these 1024s to be `len(message_data)`? if so, might be worth changing the four cases here.
# * number of bytes / 60 seconds for transaction messages @pytest.mark.anyio @boolean_datacases(name="incoming", true="incoming", false="outgoing") @boolean_datacases(name="tx_msg", true="tx", false="non-tx") @boolean_datacases(name="limit_size", true="size-limit", false="count-limit") async def test_limits_v2(incomi...
@@ -66,39 +65,22 @@ async def test_limits_v2(incoming: bool, tx_msg: bool, limit_size: bool, monkeyp message_data = b"\0" * 1024 msg_type = ProtocolMessageTypes.new_transaction - limits: dict[str, Any] = {} + limits: dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]] if limit_size: - ...
chia/_tests/core/server/test_rate_limits.py
26
Python
0.5
suggestion
108
51
51
false
Simplify rate limit numbers
19,991
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
difficulty: uint64 sub_slot_iters: uint64 pool_contract_puzzle_hash: bytes32 @streamable @dataclass(frozen=True) class HarvesterHandshake(Streamable): farmer_public_keys: list[G1Element] pool_public_keys: list[G1Element] @streamable @dataclass(frozen=True) class NewSignagePointHarvester(Streamab...
```suggestion # message format is used if the protocol version is 0.0.37 or higher ```
difficulty: uint64 sub_slot_iters: uint64 pool_contract_puzzle_hash: bytes32 @streamable @dataclass(frozen=True) class HarvesterHandshake(Streamable): farmer_public_keys: list[G1Element] pool_public_keys: list[G1Element] @streamable @dataclass(frozen=True) class NewSignagePointHarvester(Streamab...
@@ -34,6 +34,20 @@ class HarvesterHandshake(Streamable): @streamable @dataclass(frozen=True) class NewSignagePointHarvester(Streamable): + challenge_hash: bytes32 + difficulty: uint64 + sub_slot_iters: uint64 + signage_point_index: uint8 + sp_hash: bytes32 + pool_difficulties: list[PoolDifficulty] ...
chia/protocols/harvester_protocol.py
26
Python
0.643
suggestion
88
51
51
false
support previous harvester protocol
19,994
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
assert latest_singleton_lineage2 is not None assert latest_singleton_lineage2.coin_id == latest_lineage_id # Let's update the lineage with a new version of the singleton new_latest_lineage = Coin(version2_id, singleton_ph, singleton_spend2.coin.amount) new_latest_lineage_id = new_latest_lineage.name...
can you change this to describe what's being tested? is it "tests that transactions that are deferred because of a time-lock is retried once the time-lock allows them"?
assert latest_singleton_lineage2 is not None assert latest_singleton_lineage2.coin_id == latest_lineage_id # Let's update the lineage with a new version of the singleton new_latest_lineage = Coin(version2_id, singleton_ph, singleton_spend2.coin.amount) new_latest_lineage_id = new_latest_lineage.name...
@@ -3260,3 +3261,41 @@ async def test_different_ff_versions() -> None: latest_singleton_lineage2 = new_mi2.bundle_coin_spends[version2_id].latest_singleton_lineage assert latest_singleton_lineage2 is not None assert latest_singleton_lineage2.coin_id == new_latest_lineage_id + + +@pytest.mark.anyio +@pyte...
chia/_tests/core/mempool/test_mempool_manager.py
26
Python
0.429
question
168
51
51
false
CHIA-3706 Cover new peak returning added transactions as a result of retrying potential transactions
20,002
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
@pytest.mark.anyio @pytest.mark.parametrize("optimized_path", [True, False]) async def test_new_peak_txs_added(optimized_path: bool) -> None: """ Covers the scenario where new peak returns added transactions as a result of retrying potential transactions. """ coins = TestCoins([TEST_COIN], {}) m...
does `get_mempool_item()` not return deferred items? It's not obvious that this is correct.
@pytest.mark.anyio @pytest.mark.parametrize( "condition_and_error", [ (ConditionOpcode.ASSERT_HEIGHT_RELATIVE, Err.ASSERT_HEIGHT_RELATIVE_FAILED), (ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, Err.ASSERT_HEIGHT_ABSOLUTE_FAILED), ], ) @pytest.mark.parametrize("optimized_path", [True, False]) async...
@@ -3260,3 +3261,41 @@ async def test_different_ff_versions() -> None: latest_singleton_lineage2 = new_mi2.bundle_coin_spends[version2_id].latest_singleton_lineage assert latest_singleton_lineage2 is not None assert latest_singleton_lineage2.coin_id == new_latest_lineage_id + + +@pytest.mark.anyio +@pyte...
chia/_tests/core/mempool/test_mempool_manager.py
26
Python
0.357
suggestion
92
37
43
false
CHIA-3706 Cover new peak returning added transactions as a result of retrying potential transactions
20,002
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
new_mi1 = mempool_manager.get_mempool_item(mi1.spend_bundle_name) assert new_mi1 is not None latest_singleton_lineage1 = new_mi1.bundle_coin_spends[version1_id].latest_singleton_lineage assert latest_singleton_lineage1 is not None assert latest_singleton_lineage1.coin_id == new_latest_lineage_id ...
I think it would be great to paramaterize this test on the condition as well, to cover `ASSERT_HEIGHT_RELATIVE`, `ASSERT_SECONDS_ABSOLUTE` and `ASSERT_SECONDS_RELATIVE`
new_mi1 = mempool_manager.get_mempool_item(mi1.spend_bundle_name) assert new_mi1 is not None latest_singleton_lineage1 = new_mi1.bundle_coin_spends[version1_id].latest_singleton_lineage assert latest_singleton_lineage1 is not None assert latest_singleton_lineage1.coin_id == new_latest_lineage_id ...
@@ -3260,3 +3261,41 @@ async def test_different_ff_versions() -> None: latest_singleton_lineage2 = new_mi2.bundle_coin_spends[version2_id].latest_singleton_lineage assert latest_singleton_lineage2 is not None assert latest_singleton_lineage2.coin_id == new_latest_lineage_id + + +@pytest.mark.anyio +@pyte...
chia/_tests/core/mempool/test_mempool_manager.py
26
Python
0.5
suggestion
168
49
51
false
CHIA-3706 Cover new peak returning added transactions as a result of retrying potential transactions
20,002
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
@kw_only_dataclass class DIDUpdateMetadata(TransactionEndpointRequest): wallet_id: uint32 = field(default_factory=default_raise) metadata: dict[str, str] = field(default_factory=dict) @streamable @dataclass(frozen=True) class DIDUpdateMetadataResponse(TransactionEndpointResponse): spend_bundle: WalletSpen...
I think if the elif explicitly specifies `is None` it resolves this `elif self.extra_delta is None or self.tail_reveal is None or self.tail_solution is None:`
amount: Optional[uint64] = None inner_address: Optional[str] = None memos: Optional[list[str]] = None coins: Optional[list[Coin]] = None extra_delta: Optional[str] = None # str to support negative ints :( tail_reveal: Optional[bytes] = None tail_solution: Optional[bytes] = None def __p...
@@ -1388,6 +1388,61 @@ class CombineCoinsResponse(TransactionEndpointResponse): pass +# utility for CATSpend +# unfortunate that we can't use CreateCoin but the memos are taken as strings not bytes +@streamable +@dataclass(frozen=True) +class Addition(Streamable): + amount: uint64 + puzzle_hash: bytes32 ...
chia/wallet/wallet_request_types.py
26
Python
0.5
suggestion
159
51
51
false
[CHIA-3605] Port `cat_spend` to `@marshal`
20,007
Chia-Network/chia-blockchain
10,822
Python
geoffwalmsley
Quexington
start_service=start_services, ) ) if start_services: farmer_peer = UnresolvedPeerInfo(block_tools.config["self_hostname"], farmer_service._server.get_port()) else: farmer_peer = None harvester_services = [ await async_exit_s...
did the solver used to connect to the farmer?
b_tools: Optional[BlockTools], b_tools_1: Optional[BlockTools], connect_to_daemon: bool, consensus_constants: ConsensusConstants, db_version: int, keychain1: Keychain, keychain2: Keychain, shared_b_tools: BlockTools, ) -> AsyncIterator[FullSystem]: config_overrides = {"full_node.max_...
@@ -386,7 +388,6 @@ async def setup_farmer_multi_harvester_with_solver( block_tools, # Pass BlockTools so SSL CA can be consistent consensus_constants, start_service=start_services, - farmer_peer=farmer_peer,
chia/_tests/util/setup_nodes.py
26
Python
0.143
question
45
51
51
false
Farmer solver networking
20,019
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
print("Node introducer updated") change_made = True except ValueError: print("Node introducer address must be in format [IP:Port]") if set_farmer_peer: try: host, port = parse_host_port(set_farmer_peer) set_p...
does this work if you upgrade from a previous installation? It seems like the "solver" key may not exist in the config in that case, and this would throw a key error. Or are keys created automatically?
print("Node introducer updated") change_made = True except ValueError: print("Node introducer address must be in format [IP:Port]") if set_farmer_peer: try: host, port = parse_host_port(set_farmer_peer) set_p...
@@ -59,6 +61,22 @@ def configure( change_made = True except ValueError: print("Farmer address must be in format [IP:Port]") + if set_solver_peer: + try: + host, port = parse_host_port(set_solver_peer) + # Set single solver pe...
chia/cmds/configure.py
26
Python
0.571
question
201
51
51
false
Farmer solver networking
20,019
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
if seeder_domain_name is not None and "seeder" in config: config["seeder"]["domain_name"] = seeder_domain_name change_made = True if seeder_nameserver is not None and "seeder" in config: config["seeder"]["nameserver"] = seeder_nameserver change_made = Tru...
If you have a setup with a farmer running on a separate machine, I imagine this has to be run on the farmer machine itself, right?
config["seeder"]["minimum_version_count"] = crawler_minimum_version_count change_made = True if seeder_domain_name is not None and "seeder" in config: config["seeder"]["domain_name"] = seeder_domain_name change_made = True if seeder_nameserver is not Non...
@@ -237,6 +255,12 @@ def configure( ) @click.option("--set-node-introducer", help="Set the introducer for node - IP:Port", type=str) @click.option("--set-farmer-peer", help="Set the farmer peer for harvester - IP:Port", type=str) +@click.option("--set-solver-peer", help="Set the solver peer for farmer - IP:Port", ty...
chia/cmds/configure.py
26
Python
0.357
question
130
51
51
false
Farmer solver networking
20,019
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
if seeder_nameserver is not None and "seeder" in config: config["seeder"]["nameserver"] = seeder_nameserver change_made = True if change_made: print("Restart any running chia services for changes to take effect") save_config(root_path, "config.yaml", con...
does this mean the solver only accepts connections from trusted farmers? or does it mean farmers only make connections to trusted solvers? I think this help message should clarify this. I can see an argument for the trust needing to go both way. A malicious farmer can DoS a solver with tons of work. A malicious solv...
if seeder_domain_name is not None and "seeder" in config: config["seeder"]["domain_name"] = seeder_domain_name change_made = True if seeder_nameserver is not None and "seeder" in config: config["seeder"]["nameserver"] = seeder_nameserver change_made = Tru...
@@ -237,6 +255,12 @@ def configure( ) @click.option("--set-node-introducer", help="Set the introducer for node - IP:Port", type=str) @click.option("--set-farmer-peer", help="Set the farmer peer for harvester - IP:Port", type=str) +@click.option("--set-solver-peer", help="Set the solver peer for farmer - IP:Port", ty...
chia/cmds/configure.py
26
Python
0.5
question
375
51
51
false
Farmer solver networking
20,019
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
@contextlib.asynccontextmanager async def manage(self) -> AsyncIterator[None]: try: self.log.info("Starting solver service") self.started = True self.log.info("Solver service started successfully") yield finally: self.log.info("Shuttin...
I would swap these check around, and make this log clearly state that we accepted a connection from an *untrusted* farmer
self.log.info("Solver initialization complete") @contextlib.asynccontextmanager async def manage(self) -> AsyncIterator[None]: try: self.log.info("Starting solver service") self.started = True self.log.info("Solver service started successfully") y...
@@ -74,7 +75,14 @@ def get_connections(self, request_node_type: Optional[NodeType]) -> list[dict[st return default_get_connections(server=self.server, request_node_type=request_node_type) async def on_connect(self, connection: WSChiaConnection) -> None: - pass + if not self.config.get("tru...
chia/solver/solver.py
26
Python
0.357
security
121
41
47
false
Farmer solver networking
20,019
Chia-Network/chia-blockchain
10,822
Python
arvidn
almogdepaz
logging.DEBUG if duration < 2 else logging.WARNING, f"pre_validate_spendbundle took {duration:0.4f} seconds " f"for {spend_bundle_id} (queue-size: {self._worker_queue_size})", ) return sbc async def add_spend_bundle( self, new_spend: SpendBundle, ...
I can't point to it directly but it's a little below, I think `conds` needs to be updated.
logging.DEBUG if duration < 2 else logging.WARNING, f"pre_validate_spendbundle took {duration:0.4f} seconds " f"for {spend_bundle_id} (queue-size: {self._worker_queue_size})", ) return sbc async def add_spend_bundle( self, new_spend: SpendBundle, ...
@@ -507,9 +501,11 @@ async def add_spend_bundle( ] = None, ) -> SpendBundleAddInfo: """ - Validates and adds to mempool a new_spend with the given NPCResult, and spend_name, and the current mempool. - The mempool should be locked during this call (blockchain lock). If there are memp...
chia/full_node/mempool_manager.py
26
Python
0.357
suggestion
90
51
51
false
remove unnecessary NPCResult in mempool_manager
20,022
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
f"for {spend_bundle_id} (queue-size: {self._worker_queue_size})", ) return sbc async def add_spend_bundle( self, new_spend: SpendBundle, conds: SpendBundleConditions, spend_name: bytes32, first_added_height: uint32, get_coin_records: Optio...
We're only dealing with a single spend bundle, and in consistency with the rest of args docs I would make it: ```suggestion conds: SpendBundleConditions resulting from running the clvm in the spend bundle's coin spends ```
f"for {spend_bundle_id} (queue-size: {self._worker_queue_size})", ) return sbc async def add_spend_bundle( self, new_spend: SpendBundle, conds: SpendBundleConditions, spend_name: bytes32, first_added_height: uint32, get_coin_records: Optio...
@@ -507,14 +501,16 @@ async def add_spend_bundle( ] = None, ) -> SpendBundleAddInfo: """ - Validates and adds to mempool a new_spend with the given NPCResult, and spend_name, and the current mempool. - The mempool should be locked during this call (blockchain lock). If there are mem...
chia/full_node/mempool_manager.py
26
Python
0.786
suggestion
237
51
51
false
remove unnecessary NPCResult in mempool_manager
20,022
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
spend_data=spend_data, fast_forward_spends=self.fast_forward_spends, ) new_bundle_coin_spends[new_coin_spend.coin.name()] = BundleCoinSpend( coin_spend=new_coin_spend, eligible_for_dedup=spend_data.eligible_for_dedup, ...
```suggestion # get_conditions_from_spendbundle raises a ValueError with an error code ```
spend_data=spend_data, fast_forward_spends=self.fast_forward_spends, ) new_bundle_coin_spends[new_coin_spend.coin.name()] = BundleCoinSpend( coin_spend=new_coin_spend, eligible_for_dedup=spend_data.eligible_for_dedup, ...
@@ -278,10 +278,10 @@ def process_fast_forward_spends( # care about here is whether this call throws or not. get_conditions_from_spendbundle(new_sb, mempool_item.conds.cost, constants, height) # get_conditions_from_spendbundle raises a TypeError with an error code
chia/full_node/eligible_coin_spends.py
26
Python
0.714
suggestion
98
37
37
false
bump chia_rs dependency
20,023
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
async def pre_validate_spendbundle( self, spend_bundle: SpendBundle, spend_bundle_id: Optional[bytes32] = None, bls_cache: Optional[BLSCache] = None ) -> SpendBundleConditions: """ Errors are included within the cached_result. This runs in another process so we don't block the m...
```suggestion # validate_clvm_and_signature raises a ValueError with an error code ```
async def pre_validate_spendbundle( self, spend_bundle: SpendBundle, spend_bundle_id: Optional[bytes32] = None, bls_cache: Optional[BLSCache] = None ) -> SpendBundleConditions: """ Errors are included within the cached_result. This runs in another process so we don't block the m...
@@ -467,10 +467,10 @@ async def pre_validate_spendbundle( flags | MEMPOOL_MODE, ) # validate_clvm_and_signature raises a TypeError with an error code
chia/full_node/mempool_manager.py
26
Python
0.714
suggestion
94
51
51
false
bump chia_rs dependency
20,023
Chia-Network/chia-blockchain
10,822
Python
altendky
arvidn
) return spend_bundle def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) -> bool: assert block1.finished_sub_slots == block2.finished_sub_slots, "Mismatch in finished_sub_slots" assert block1.reward_chain_block == block2.reward_chain_block, "Mismatch in reward_chain_block"...
```suggestion "condition, error", ```
) return spend_bundle def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) -> bool: assert block1.finished_sub_slots == block2.finished_sub_slots, "Mismatch in finished_sub_slots" assert block1.reward_chain_block == block2.reward_chain_block, "Mismatch in reward_chain_block"...
@@ -3294,3 +3294,65 @@ def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) # Final assertion to check the entire block assert block1 == block2, "The entire block objects are not identical" return True + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "condition_and_error...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.571
suggestion
43
51
51
false
CHIA-3731 Cover peak post processing w.r.t. added transactions as a result of retrying potential transactions
20,044
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
assert block1.challenge_chain_sp_proof == block2.challenge_chain_sp_proof, "Mismatch in challenge_chain_sp_proof" assert block1.reward_chain_sp_proof == block2.reward_chain_sp_proof, "Mismatch in reward_chain_sp_proof" assert block1.total_iters == block2.total_iters, "Mismatch in total_iters" assert blo...
```suggestion condition: ConditionOpcode, error: str, ```
assert block1.challenge_chain_sp_proof == block2.challenge_chain_sp_proof, "Mismatch in challenge_chain_sp_proof" assert block1.reward_chain_sp_proof == block2.reward_chain_sp_proof, "Mismatch in reward_chain_sp_proof" assert block1.total_iters == block2.total_iters, "Mismatch in total_iters" assert blo...
@@ -3294,3 +3294,65 @@ def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) # Final assertion to check the entire block assert block1 == block2, "The entire block objects are not identical" return True + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "condition_and_error...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.714
suggestion
63
51
51
false
CHIA-3731 Cover peak post processing w.r.t. added transactions as a result of retrying potential transactions
20,044
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
assert block1.transactions_info == block2.transactions_info, "Mismatch in transactions_info" assert block1.transactions_generator == block2.transactions_generator, "Mismatch in transactions_generator" assert block1.transactions_generator_ref_list == block2.transactions_generator_ref_list # Final assert...
I think this comment should more directly say what *feature* is being tested and maybe which *cases* are covered. It's the `PendingTXCache`, right?
assert block1.transactions_info == block2.transactions_info, "Mismatch in transactions_info" assert block1.transactions_generator == block2.transactions_generator, "Mismatch in transactions_generator" assert block1.transactions_generator_ref_list == block2.transactions_generator_ref_list # Final assert...
@@ -3294,3 +3294,65 @@ def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) # Final assertion to check the entire block assert block1 == block2, "The entire block objects are not identical" return True + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "condition_and_error...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.571
performance
147
51
51
false
CHIA-3731 Cover peak post processing w.r.t. added transactions as a result of retrying potential transactions
20,044
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
) for block in blocks: await full_node_api.full_node.add_block(block) peak = full_node_api.full_node.blockchain.get_peak() assert peak is not None current_height = peak.height # Create a transaction with a height condition that makes it pending coin = ...
```suggestion # Advance peak to meet the condition ```
) for block in blocks: await full_node_api.full_node.add_block(block) peak = full_node_api.full_node.blockchain.get_peak() assert peak is not None current_height = peak.height # Create a transaction with a height condition that makes it pending coin = ...
@@ -3294,3 +3294,62 @@ def compare_unfinished_blocks(block1: UnfinishedBlock, block2: UnfinishedBlock) # Final assertion to check the entire block assert block1 == block2, "The entire block objects are not identical" return True + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "condition, error", ...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.571
suggestion
64
35
35
false
CHIA-3731 Cover peak post processing w.r.t. added transactions as a result of retrying potential transactions
20,044
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
return False def get_signage_point(self, cc_signage_point: bytes32) -> Optional[SignagePoint]: assert len(self.finished_sub_slots) >= 1 if cc_signage_point == self.constants.GENESIS_CHALLENGE: return SignagePoint(None, None, None, None) for sub_slot, sps, _ in self.fini...
Are there any scenarios, like with unfinished blocks, that this will make the genesis challenge a valid challenge? I'm not familiar with all the scenarios in which sub_slot may be None. It might seem like a small stylistic tweak, but I would be inclined to make the if branch be the "sub_slot is None" because it makes i...
return False def get_signage_point(self, cc_signage_point: bytes32) -> Optional[SignagePoint]: assert len(self.finished_sub_slots) >= 1 if cc_signage_point == self.constants.GENESIS_CHALLENGE: return SignagePoint(None, None, None, None) for sub_slot, sps, _ in self.fini...
@@ -833,10 +833,12 @@ def get_signage_point_by_index_and_cc_output( self, cc_signage_point: bytes32, challenge: bytes32, index: uint8 ) -> Optional[SignagePoint]: assert len(self.finished_sub_slots) >= 1 - if cc_signage_point == self.constants.GENESIS_CHALLENGE: - return Signage...
chia/full_node/full_node_store.py
26
Python
0.5
suggestion
617
51
51
false
fix sp lookup at genesis
20,057
Chia-Network/chia-blockchain
10,822
Python
trgarrett
almogdepaz
self.cancel_tasks() except Exception: error_stack = traceback.format_exc() self.log.warning(f"Exception closing socket: {error_stack}") raise finally: with log_exceptions(self.log, consume=True): if self.close_callback is not No...
I imagine this is supposed to be used but I don't see that anywhere.
self.cancel_tasks() except Exception: error_stack = traceback.format_exc() self.log.warning(f"Exception closing socket: {error_stack}") raise finally: with log_exceptions(self.log, consume=True): if self.close_callback is not No...
@@ -358,6 +358,12 @@ async def ban_peer_bad_protocol(self, log_err_msg: str) -> None: self.log.error(f"Banning peer for {ban_seconds} seconds: {self.peer_info.host} {log_err_msg}") await self.close(ban_seconds, WSCloseCode.PROTOCOL_ERROR, Err.INVALID_PROTOCOL_MESSAGE) + async def ban_peer_consens...
chia/server/ws_connection.py
26
Python
0.286
suggestion
69
51
51
false
[CHIA-3712] simplify add_transaction()
20,063
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
self, spend_bundle: SpendBundle, spend_bundle_id: Optional[bytes32] = None, bls_cache: Optional[BLSCache] = None ) -> SpendBundleConditions: """ Errors are included within the cached_result. This runs in another process so we don't block the main thread """ if spend_...
Is this the only value to warn with here, assuming it's left intentionally?
self, spend_bundle: SpendBundle, spend_bundle_id: Optional[bytes32] = None, bls_cache: Optional[BLSCache] = None ) -> SpendBundleConditions: """ Errors are included within the cached_result. This runs in another process so we don't block the main thread """ if spend_...
@@ -460,6 +460,7 @@ async def pre_validate_spendbundle( ) # validate_clvm_and_signature raises a ValueError with an error code except ValueError as e: + log.warning(f"max CLVM cost: {self.max_tx_clvm_cost}")
chia/full_node/mempool_manager.py
26
Python
0.214
question
75
51
51
false
[CHIA-3712] simplify add_transaction()
20,063
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
full_node_1, _server_1, bt = one_node_one_block blocks = await full_node_1.get_all_full_blocks() start_height = blocks[-1].height if len(blocks) > 0 else -1 blocks = bt.get_consecutive_blocks( 3, block_list_input=blocks, guarantee_transaction_block=Tru...
The `ack.status` value should stay exactly as it was, AFAICS: ```suggestion assert ack.status == MempoolInclusionStatus.FAILED.value assert "chia.util.errors.ValidationError: Error code: BAD_AGGREGATE_SIGNATURE" in caplog.text ```
blocks = bt.get_consecutive_blocks( 3, block_list_input=blocks, guarantee_transaction_block=True, farmer_reward_puzzle_hash=reward_ph, pool_reward_puzzle_hash=reward_ph, ) await add_blocks_in_batches(blocks, full_node_1.full_node) ...
@@ -716,11 +719,12 @@ async def test_invalid_signature( sb: SpendBundle = generate_test_spend_bundle(wallet_a, coin1) assert sb.aggregated_signature != G2Element.generator() sb = sb.replace(aggregated_signature=G2Element.generator()) + caplog.clear() res: Optional[Message] = a...
chia/_tests/core/mempool/test_mempool.py
26
Python
1
bug
250
51
51
false
[CHIA-3712] simplify add_transaction()
20,063
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
"node_id": con.peer_node_id, "creation_time": con.creation_time, "bytes_read": con.bytes_read, "bytes_written": con.bytes_written, "last_message_time": con.last_message_time, "peak_height": peak_height, "peak...
I would differentiate this log entry from the `Exception` one below. Something like: ```suggestion self.log.exception("Validation error in _handle_one_transaction, closing") ```
"node_id": con.peer_node_id, "creation_time": con.creation_time, "bytes_read": con.bytes_read, "bytes_written": con.bytes_written, "last_message_time": con.last_message_time, "peak_height": peak_height, "peak...
@@ -503,11 +503,16 @@ async def _handle_one_transaction(self, entry: TransactionQueueEntry) -> None: except asyncio.CancelledError: error_stack = traceback.format_exc() self.log.debug(f"Cancelling _handle_one_transaction, closing: {error_stack}") + except ValidationError as e: ...
chia/full_node/full_node.py
26
Python
0.857
suggestion
192
51
51
false
[CHIA-3712] simplify add_transaction()
20,063
Chia-Network/chia-blockchain
10,822
Python
AmineKhaldi
arvidn
def test_process_fast_forward_spends_nothing_to_do() -> None: """ This tests the case when we don't have an eligible coin, so there is nothing to fast forward and the item remains unchanged """ sk = AugSchemeMPL.key_gen(b"b" * 32) g1 = sk.get_g1() sig = AugSchemeMPL.sign(sk, b"foobar", g1)...
I would expect this test to still have the same behavior. Removing it looks a bit suspicious, as if we expect different behavior now. Does this test fail with your changes?
def test_process_fast_forward_spends_nothing_to_do() -> None: """ This tests the case when we don't have an eligible coin, so there is nothing to fast forward and the item remains unchanged """ sk = AugSchemeMPL.key_gen(b"b" * 32) g1 = sk.get_g1() sig = AugSchemeMPL.sign(sk, b"foobar", g1)...
@@ -63,28 +63,6 @@ def test_process_fast_forward_spends_nothing_to_do() -> None: assert bundle_coin_spends == original_version.bundle_coin_spends -def test_process_fast_forward_spends_unknown_ff() -> None:
chia/_tests/core/mempool/test_singleton_fast_forward.py
26
Python
0.429
bug
172
51
51
false
CHIA-3737 Simplify BundleCoinSpend's tracking of fast forward spends
20,069
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
test_condition_valid_times, ), ], } test_rpc_clients.wallet_rpc_client.check_log(expected_calls) def test_vcs_approve_r_cats(capsys: object, get_test_cli_clients: tuple[TestRpcClients, Path]) -> None: test_rpc_clients, root_dir = get_test_cli_clients # set RPC Clie...
I wonder why this parameter, which is not part of `request`, is between other parameters which are. Not very important, but a curiosity.
True, test_condition_valid_times, ), ], } test_rpc_clients.wallet_rpc_client.check_log(expected_calls) def test_vcs_approve_r_cats(capsys: object, get_test_cli_clients: tuple[TestRpcClients, Path]) -> None: test_rpc_clients, root_dir = get_test_cli_clien...
@@ -335,25 +336,23 @@ def test_vcs_approve_r_cats(capsys: object, get_test_cli_clients: tuple[TestRpcC class VcsApproveRCATSRpcClient(TestWalletRpcClient): async def crcat_approve_pending( self, - wallet_id: uint32, - min_amount_to_claim: uint64, + request: CR...
chia/_tests/cmds/wallet/test_vcs.py
26
Python
0.5
suggestion
136
51
51
false
[LABS-249] Port `crcat_approve_pending` to `@marshal`
20,116
Chia-Network/chia-blockchain
10,822
Python
richardkiss
Quexington
return None @metadata.request(peer_required=True) async def new_transaction( self, transaction: full_node_protocol.NewTransaction, peer: WSChiaConnection ) -> Optional[Message]: """ A peer notifies us of a new transaction. Requests a full transaction if we haven't s...
you should check the fee here too
return None @metadata.request(peer_required=True) async def new_transaction( self, transaction: full_node_protocol.NewTransaction, peer: WSChiaConnection ) -> Optional[Message]: """ A peer notifies us of a new transaction. Requests a full transaction if we haven't s...
@@ -170,8 +170,15 @@ async def new_transaction( if not (await self.full_node.synced()): return None - # Ignore if already seen - if self.full_node.mempool_manager.seen(transaction.transaction_id): + # If already seen, make sure the cost matches, otherwise ban the peer + ...
chia/full_node/full_node_api.py
26
Python
0.143
suggestion
33
51
51
false
CHIA-3779 Make sure the costs and fees match when a peer notifies us of a new transaction that we saw already
20,140
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
assert f"Added transaction to mempool: {sb_name}\n" in caplog.text # Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pending=False) is not None @pytest.mark.anyio @pytest.mark.parametrize("misma...
where did `bt` come from? Are you sure it will generate valid blocks on top of the chain in `node_to_add_tx_to`?
# Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pending=False) is not None @pytest.mark.anyio @pytest.mark.parametrize("mismatch_cost", [True, False]) @pytest.mark.parametrize("mismatch_fee", [True, F...
@@ -3357,3 +3358,61 @@ async def test_pending_tx_cache_retry_on_new_peak( assert f"Added transaction to mempool: {sb_name}\n" in caplog.text # Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pe...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.5
question
112
51
51
false
CHIA-3779 Make sure the costs and fees match when a peer notifies us of a new transaction that we saw already
20,140
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
@pytest.mark.anyio @pytest.mark.parametrize("mismatch_cost", [True, False]) @pytest.mark.parametrize("mismatch_fee", [True, False]) async def test_ban_for_mismatched_tx_cost_fee( setup_two_nodes_fixture: tuple[list[FullNodeSimulator], list[tuple[WalletNode, ChiaServer]], BlockTools], self_hostname: str, mi...
the name of this function, `generate_and_send_tx()` seems misleading. You also generate blocks and add them to the chain. It's also only called from one place, so there might be a better line to cut along to pull out a function
@pytest.mark.anyio @pytest.mark.parametrize("mismatch_cost", [True, False]) @pytest.mark.parametrize("mismatch_fee", [True, False]) async def test_ban_for_mismatched_tx_cost_fee( setup_two_nodes_fixture: tuple[list[FullNodeSimulator], list[tuple[WalletNode, ChiaServer]], BlockTools], self_hostname: str, mis...
@@ -3357,3 +3358,61 @@ async def test_pending_tx_cache_retry_on_new_peak( assert f"Added transaction to mempool: {sb_name}\n" in caplog.text # Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pe...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.643
suggestion
227
51
51
false
CHIA-3779 Make sure the costs and fees match when a peer notifies us of a new transaction that we saw already
20,140
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
sb_name = sb.name() # Send the transaction res = await full_node_api.send_transaction(SendTransaction(sb)) assert res is not None assert ProtocolMessageTypes(res.type) == ProtocolMessageTypes.transaction_ack transaction_ack = TransactionAck.from_bytes(res.data) as...
I think you only need one node, don't you?
# Send the transaction res = await full_node_api.send_transaction(SendTransaction(sb)) assert res is not None assert ProtocolMessageTypes(res.type) == ProtocolMessageTypes.transaction_ack transaction_ack = TransactionAck.from_bytes(res.data) assert transaction_ack.status ...
@@ -3357,3 +3358,61 @@ async def test_pending_tx_cache_retry_on_new_peak( assert f"Added transaction to mempool: {sb_name}\n" in caplog.text # Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pe...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.071
question
42
51
51
false
CHIA-3779 Make sure the costs and fees match when a peer notifies us of a new transaction that we saw already
20,140
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
coin = blocks[-1].get_included_reward_coins()[0] spend_bundle = wallet.generate_signed_transaction(uint64(42), wallet_ph, coin) sb_name = spend_bundle.name() await node_to_add_tx_to.add_transaction(spend_bundle, sb_name, ws_con) mempool_item = node_to_add_tx_to.mempool_manager.ge...
you need an else block here, to make sure the peer is *not* banned. e.g. if the peer is *always* banned, this test would still pass right now
3, guarantee_transaction_block=True, farmer_reward_puzzle_hash=wallet_ph, pool_reward_puzzle_hash=wallet_ph ) for block in blocks: await full_node_1.full_node.add_block(block) # Create a transaction and add it to the relevant full node's mempool coin = blocks[-1].get_included_reward_coin...
@@ -3357,3 +3358,61 @@ async def test_pending_tx_cache_retry_on_new_peak( assert f"Added transaction to mempool: {sb_name}\n" in caplog.text # Make sure the transaction was retried and got added to the mempool assert full_node_api.full_node.mempool_manager.get_mempool_item(sb_name, include_pe...
chia/_tests/core/full_node/test_full_node.py
26
Python
0.357
suggestion
141
32
30
false
CHIA-3779 Make sure the costs and fees match when a peer notifies us of a new transaction that we saw already
20,140
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
async def tx_request_and_timeout(full_node: FullNode, transaction_id: bytes32, task_id: bytes32) -> None: counter = 0 try: while True: # Limit to asking a few peers, it's possible that this tx got included on chain already ...
I don't think it's safe to assume you will have received and ingested the transaction at this point. I think the only way to do this reliably is to pass along the peer, cost and fee with the transaction request, to be able to tie it back to the sender immediately after having validated it.
@metadata.request(peer_required=True) async def new_transaction( self, transaction: full_node_protocol.NewTransaction, peer: WSChiaConnection ) -> Optional[Message]: """ A peer notifies us of a new transaction. Requests a full transaction if we haven't seen it previously, and...
@@ -226,8 +226,16 @@ async def tx_request_and_timeout(full_node: FullNode, transaction_id: bytes32, t await random_peer.send_message(msg) await asyncio.sleep(5) counter += 1 - if full_node.mempool_manager.seen(transaction_...
chia/full_node/full_node_api.py
26
Python
0.429
suggestion
290
51
51
false
CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
20,166
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
transaction, cost_result, spend_name, self.mempool_manager.peak.height ) status = info.status error = info.error if status == MempoolInclusionStatus.SUCCESS: self.log.debug( f"Added transaction to mempool: {spend_name} mempool size:...
I think `CONSENSUS_ERROR_BAN_SECONDS` is pretty reasonable here. disagreeing on cost or fee is a consensus issue. and I think if you see rate limiter in the log, you won't think of this case
return MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_INITIALIZED info = await self.mempool_manager.add_spend_bundle( transaction, cost_result, spend_name, self.mempool_manager.peak.height ) status = info.status error = info.error i...
@@ -2810,10 +2817,23 @@ async def add_transaction( f"{self.mempool_manager.mempool.total_mempool_cost() / 5000000}" ) - # Only broadcast successful transactions, not pending ones. Otherwise it's a DOS - # vector. mempool_item = self.mempool_manager.get_...
chia/full_node/full_node.py
26
Python
0.643
suggestion
190
51
51
false
CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
20,166
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi
uint8(0), uint32(0) if peak is None else peak.height, tx_peak.height if tx_peak is not None else uint32(0), sp_source_data=SignagePointSourceData( sub_slot_data=SPSubSlotSourceData( end_of...
I take it the tuple of `uint64` is cost and fee. Since you use a tuple instead of a class with named fields, I think it would be good to have a comment indicating which one is which
uint8(0), uint32(0) if peak is None else peak.height, tx_peak.height if tx_peak is not None else uint32(0), sp_source_data=SignagePointSourceData( sub_slot_data=SPSubSlotSourceData( end_of...
@@ -2761,7 +2763,12 @@ async def add_end_of_sub_slot( return None, False async def add_transaction( - self, transaction: SpendBundle, spend_name: bytes32, peer: Optional[WSChiaConnection] = None, test: bool = False + self, + transaction: SpendBundle, + spend_name: bytes32, + ...
chia/full_node/full_node.py
26
Python
0.571
suggestion
181
51
51
false
CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
20,166
Chia-Network/chia-blockchain
10,822
Python
arvidn
AmineKhaldi