before_code stringlengths 30 149k | reviewer_comment stringlengths 16 20.6k | after_code stringlengths 30 163k | diff_context stringlengths 0 22.4k | file_path stringlengths 6 155 | comment_line int64 0 26 | language stringclasses 19
values | quality_score float64 0.07 1 | comment_type stringclasses 9
values | comment_length int64 16 20.6k | before_lines int64 2 4.61k | after_lines int64 2 4.4k | is_negative bool 2
classes | pr_title stringlengths 7 140 | pr_number int64 18 61.2k | repo_name stringclasses 29
values | repo_stars int64 321 56k | repo_language stringclasses 14
values | reviewer_username stringclasses 378
values | author_username stringclasses 739
values | user stringlengths 361 200k | assistant stringlengths 16 20.6k | system stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.SUCCESS, None
if self.mempool_manager.peak is None:
return MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_IN... | Just because the peer has disconnected, we can still ban it, right? To prevent it from reconnecting any time soon |
async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.low):
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.SUCCESS, None
if self.memp... | @@ -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.429 | suggestion | 113 | 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 | Review this pull request change.
Language: Python
File: chia/full_node/full_node.py
PR Title: CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
BEFORE CODE: if self.mempool_manager.get_spendbundle(spend_name) is not None:
s... | Just because the peer has disconnected, we can still ban it, right? To prevent it from reconnecting any time soon | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
Request a transaction from peers that advertised it, until we either
receive it or timeout.
"""
counter = 0
peers_with_tx = copy.copy(full_node.full_node_store.peers_with_tx.get(transaction_id, {}))
try:
while True:
# Limit to asking a few peers, it's possible that this tx go... | I don't think this is right. If I send you an invalid transaction, you validate it and you ban me. You still want to record that you've seen it, so you don't validate it again.
i.e. there's a difference between "seen" and "I have it". I believe "seen" may also mean it's in the queue of transactions about to be validat... | Request a transaction from peers that advertised it, until we either
receive it or timeout.
"""
counter = 0
# Make a copy as we'll pop from it here. We keep the original intact as we
# need it in `respond_transaction` when constructing `TransactionQueueEntry`
# to put into `transaction_queue... | @@ -111,7 +112,7 @@ 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_id): | chia/full_node/full_node_api.py | 26 | Python | 0.429 | suggestion | 323 | 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 | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
BEFORE CODE: Request a transaction from peers that advertised it, until we either
receive it or... | I don't think this is right. If I send you an invalid transaction, you validate it and you ban me. You still want to record that you've seen it, so you don't validate it again.
i.e. there's a difference between "seen" and "I have it". I believe "seen" may also mean it's in the queue of transactions about to be validat... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
"""
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode():
return None
if not (await self.full_node.synced()):
return None
# If already seen, the cost and fee must match, otherwise ban the peer
mempool_item = self.full_node.mempool_mana... | ```suggestion
existing_request = current_map.get(peer.peer_node_id)
if existing_request is not None:
if existing_request.cost != transaction.cost or existing_request.feed != transaction.fees:
# TODO: ban peer
... | """
A peer notifies us of a new transaction.
Requests a full transaction if we haven't seen it previously, and if the fees are enough.
"""
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode():
return None
if not (await self.full_node.synced... | @@ -228,21 +229,22 @@ async def new_transaction(
# If there's current pending request just add this peer to the set of peers that have this tx
if transaction.transaction_id in self.full_node.full_node_store.pending_tx_request:
if transaction.transaction_id in self.full_node.fu... | chia/full_node/full_node_api.py | 26 | Python | 0.786 | suggestion | 340 | 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 | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
BEFORE CODE: """
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode... | ```suggestion
existing_request = current_map.get(peer.peer_node_id)
if existing_request is not None:
if existing_request.cost != transaction.cost or existing_request.feed != transaction.fees:
# TODO: ban peer
... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
"""
A peer notifies us of a new transaction.
Requests a full transaction if we haven't seen it previously, and if the fees are enough.
"""
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode():
return None
if not (await self.full_node.synced... | I'm not sure if it's better, but you could avoid a lookup by using `.get()` instead `in` and check if what you get back is `None` or not. | 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 if the fees are enough.
"""
... | @@ -228,21 +229,22 @@ async def new_transaction(
# If there's current pending request just add this peer to the set of peers that have this tx
if transaction.transaction_id in self.full_node.full_node_store.pending_tx_request:
if transaction.transaction_id in self.full_node.fu... | chia/full_node/full_node_api.py | 26 | Python | 0.571 | suggestion | 137 | 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 | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
BEFORE CODE: """
A peer notifies us of a new transaction.
Requests a full trans... | I'm not sure if it's better, but you could avoid a lookup by using `.get()` instead `in` and check if what you get back is `None` or not. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
from chia.types.generator_types import BlockGenerator, NewBlockGenerator
from chia.types.mempool_inclusion_status import MempoolInclusionStatus
from chia.types.peer_info import PeerInfo
from chia.util.batches import to_batches
from chia.util.db_wrapper import SQLITE_MAX_VARIABLE_NUMBER
from chia.util.errors import Err,... | it's not obvious to me why you need to copy this. Could you add a comment? | from chia.types.generator_types import BlockGenerator, NewBlockGenerator
from chia.types.mempool_inclusion_status import MempoolInclusionStatus
from chia.types.peer_info import PeerInfo
from chia.util.batches import to_batches
from chia.util.db_wrapper import SQLITE_MAX_VARIABLE_NUMBER
from chia.util.errors import Err,... | @@ -89,6 +90,7 @@ async def tx_request_and_timeout(full_node: FullNode, transaction_id: bytes32, t
receive it or timeout.
"""
counter = 0
+ peers_with_tx = copy.copy(full_node.full_node_store.peers_with_tx.get(transaction_id, {})) | chia/full_node/full_node_api.py | 26 | Python | 0.286 | question | 74 | 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 | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3787 Make sure the fee and cost specified in a NewTransaction match the ones from validating its spend bundle
BEFORE CODE: from chia.types.generator_types import BlockGenerator, NewBlockGenerator
from chia.types.m... | it's not obvious to me why you need to copy this. Could you add a comment? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
self.full_node.full_node_store.pending_tx_request[transaction.transaction_id] = peer.peer_node_id
new_set = set()
new_set.add(peer.peer_node_id)
self.full_node.full_node_store.peers_with_tx[transaction.transaction_id] = new_set
task_id: bytes32 = bytes32.secr... | We don't need to capture `transaction.transaction_id` here, we have access to it as a param. | 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 se... | @@ -201,47 +201,9 @@ async def new_transaction(
new_set = set()
new_set.add(peer.peer_node_id)
self.full_node.full_node_store.peers_with_tx[transaction.transaction_id] = new_set
-
- async def tx_request_and_timeout(full_node: FullNode, transaction_id: bytes32, task_id: ... | chia/full_node/full_node_api.py | 26 | Python | 0.357 | suggestion | 92 | 51 | 51 | false | CHIA-3788 Simplify tx_request_and_timeout by converting it from a closure into a FullNode class method | 20,186 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3788 Simplify tx_request_and_timeout by converting it from a closure into a FullNode class method
BEFORE CODE:
self.full_node.full_node_store.pending_tx_request[transaction.transaction_id] = peer.peer... | We don't need to capture `transaction.transaction_id` here, we have access to it as a param. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
f"fee {transaction.fees} vs {mempool_item.fee}."
)
await peer.close(RATE_LIMITER_BAN_SECONDS)
return None
if self.full_node.mempool_manager.is_fee_enough(transaction.fees, transaction.cost):
# If there's current pending request just ad... | I think this function was in this file because it's part of the `_api` functionality. I think it would make more sense to move it out to be a free function, but still in the `full_node_api.py` file. |
await peer.close()
return None
@metadata.request(peer_required=True, execute_task=True)
async def new_peak(self, request: full_node_protocol.NewPeak, peer: WSChiaConnection) -> None:
"""
A peer notifies us that they have added a new peak to their blockchain. If we don't have it... | @@ -201,47 +201,9 @@ async def new_transaction(
new_set = set()
new_set.add(peer.peer_node_id)
self.full_node.full_node_store.peers_with_tx[transaction.transaction_id] = new_set
-
- async def tx_request_and_timeout(full_node: FullNode, transaction_id: bytes32, task_id: ... | chia/full_node/full_node_api.py | 26 | Python | 0.571 | suggestion | 198 | 51 | 51 | false | CHIA-3788 Simplify tx_request_and_timeout by converting it from a closure into a FullNode class method | 20,186 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3788 Simplify tx_request_and_timeout by converting it from a closure into a FullNode class method
BEFORE CODE: f"fee {transaction.fees} vs {mempool_item.fee}."
)
... | I think this function was in this file because it's part of the `_api` functionality. I think it would make more sense to move it out to be a free function, but still in the `full_node_api.py` file. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
@pytest.mark.parametrize(
"wallet_environments",
[{"num_environments": 1, "blocks_needed": [2], "reuse_puzhash": True, "trusted": True}],
indirect=True,
)
@pytest.mark.limit_consensus_modes(reason="irrelevant")
@pytest.mark.anyio
async def test_get_farmed_amount(wallet_environments: WalletTestFramework) ->... | Wonder what happened to this one? (I suspect you've added `| None` to a signature) | await assert_get_balance(wallet_rpc_client, wallet_node, cat_wallet)
@pytest.mark.parametrize(
"wallet_environments",
[{"num_environments": 1, "blocks_needed": [2], "reuse_puzhash": True, "trusted": True}],
indirect=True,
)
@pytest.mark.limit_consensus_modes(reason="irrelevant")
@pytest.mark.anyio
asy... | @@ -468,21 +470,20 @@ async def test_get_farmed_amount(wallet_environments: WalletTestFramework) -> No
env = wallet_environments.environments[0]
wallet_rpc_client = env.rpc_client
- get_farmed_amount_result = await wallet_rpc_client.get_farmed_amount()
+ get_farmed_amount_result = await wallet_rpc_cli... | chia/_tests/wallet/rpc/test_wallet_rpc.py | 26 | Python | 0.357 | suggestion | 82 | 51 | 51 | false | [LABS-291] Port `get_farmed_amount` to `@marshal` | 20,187 | Chia-Network/chia-blockchain | 10,822 | Python | richardkiss | Quexington | Review this pull request change.
Language: Python
File: chia/_tests/wallet/rpc/test_wallet_rpc.py
PR Title: [LABS-291] Port `get_farmed_amount` to `@marshal`
BEFORE CODE:
@pytest.mark.parametrize(
"wallet_environments",
[{"num_environments": 1, "blocks_needed": [2], "reuse_puzhash": True, "trusted": True}]... | Wonder what happened to this one? (I suspect you've added `| None` to a signature) | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
VCSpendResponse,
VerifySignature,
VerifySignatureResponse,
WalletInfoResponse,
)
from chia.wallet.wallet_spend_bundle import WalletSpendBundle
# Timeout for response from wallet/full node for sending a transaction
TIMEOUT = 30
MAX_DERIVATION_INDEX_DELTA = 1000
MAX_NFT_CHUNK_SIZE = 25
log = logging.get... | This is the principal change. This method that this has been added to is a decorator for all RPC endpoints that deal with creating transactions. | VCSpendResponse,
VerifySignature,
VerifySignatureResponse,
WalletInfoResponse,
)
from chia.wallet.wallet_spend_bundle import WalletSpendBundle
# Timeout for response from wallet/full node for sending a transaction
TIMEOUT = 30
MAX_DERIVATION_INDEX_DELTA = 1000
MAX_NFT_CHUNK_SIZE = 25
log = logging.get... | @@ -320,6 +320,9 @@ def _inner(func: RpcEndpoint) -> RpcEndpoint:
async def rpc_endpoint(
self: WalletRpcApi, request: dict[str, Any], *args: object, **kwargs: object
) -> EndpointResult:
+ if await self.service.wallet_state_manager.synced() is False:
+ raise Val... | chia/wallet/wallet_rpc_api.py | 26 | Python | 0.429 | suggestion | 145 | 51 | 51 | false | [LABS-293] Ensure wallet is synced for RPC TX endpoints | 20,190 | Chia-Network/chia-blockchain | 10,822 | Python | Quexington | Quexington | Review this pull request change.
Language: Python
File: chia/wallet/wallet_rpc_api.py
PR Title: [LABS-293] Ensure wallet is synced for RPC TX endpoints
BEFORE CODE: VCSpendResponse,
VerifySignature,
VerifySignatureResponse,
WalletInfoResponse,
)
from chia.wallet.wallet_spend_bundle import WalletSpen... | This is the principal change. This method that this has been added to is a decorator for all RPC endpoints that deal with creating transactions. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None,
time_per_block: Optional[float] = None,
dummy_block_references: bool = False,
include_transactions: bool =... | We have chia.util.lock.LockFile I imagine you could use? | normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None,
time_per_block: Optional[float] = None,
dummy_block_references: bool = False,
include_transactions: bool =... | @@ -59,47 +60,62 @@ def persistent_blocks(
block_list_input = []
block_path_dir = DEFAULT_ROOT_PATH.parent.joinpath("blocks")
file_path = block_path_dir.joinpath(db_name)
+ lock_file_path = block_path_dir / (db_name + ".lockfile")
ci = os.environ.get("CI")
if ci is not None and not fil... | chia/_tests/util/blockchain.py | 26 | Python | 0.286 | question | 56 | 51 | 51 | false | filelock for test- plots and blocks | 20,193 | Chia-Network/chia-blockchain | 10,822 | Python | emlowe | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/util/blockchain.py
PR Title: filelock for test- plots and blocks
BEFORE CODE: normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False,
block_list_input: O... | We have chia.util.lock.LockFile I imagine you could use? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if plot_info.prover.get_strength() < constants.PLOT_STRENGTH_INITIAL:
self.log.warn(
f"Plot strength ({plot_info.prover.get_strength()}) too low, "
f"cannot be used for farming: {plot_info.prover.get_filename()}"
)
... | doesn't calculate_iterations_quality return uint64 ? | if plot_info.prover.get_strength() < constants.PLOT_STRENGTH_INITIAL:
self.log.warn(
f"Plot strength ({plot_info.prover.get_strength()}) too low, "
f"cannot be used for farming: {plot_info.prover.get_filename()}"
)
... | @@ -1570,7 +1572,7 @@ def get_pospaces_for_challenge(
sub_slot_iters,
prev_transaction_b_height,
)
- if required_iters >= calculate_sp_interval_iters(constants, sub_slot_iters):
+ if required_iters is None or required_iters >= calc... | chia/simulator/block_tools.py | 26 | Python | 0.214 | question | 52 | 51 | 51 | false | Minor pos2 updates | 20,200 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: Minor pos2 updates
BEFORE CODE: if plot_info.prover.get_strength() < constants.PLOT_STRENGTH_INITIAL:
self.log.warn(
f"Plot strength ({plot_info.prover.get_stre... | doesn't calculate_iterations_quality return uint64 ? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# f"time: {new_timestamp - last_timestamp:0.2f} "
# f"additions: {len(new_gen.additions) if block_record.is_transaction_block else 0:2} "
# f"removals: {len(new_gen.removals) if block_record.is_transaction_block else 0:2} "
... | This fixes tracking of previous *generators* | assert full_block.foliage_transaction_block is not None
elif guarantee_transaction_block:
continue
# print(f"{full_block.height:4}: difficulty {difficulty} "
# f"time: {new_timestamp - las... | @@ -1009,8 +1013,10 @@ def get_consecutive_blocks(
available_coins.remove(rem)
available_coins.extend(new_gen.additions)
+ if full_block.transactions_generator is not None:
+ generator_block... | chia/simulator/block_tools.py | 26 | Python | 0.071 | suggestion | 44 | 51 | 51 | false | fix BlockTools confusion between tx block and block with generators | 20,212 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | arvidn | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix BlockTools confusion between tx block and block with generators
BEFORE CODE: # f"time: {new_timestamp - last_timestamp:0.2f} "
# f"additions: {len(new_gen.addit... | This fixes tracking of previous *generators* | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# f"removals: {len(new_gen.removals) if block_record.is_transaction_block else 0:2} "
# f"refs: {len(full_block.transactions_generator_ref_list):3} "
# f"tx: {block_record.is_transaction_block}")
last_timestamp =... | This fixes tracking of previous *generators* | assert full_block.foliage_transaction_block is not None
elif guarantee_transaction_block:
continue
# print(f"{full_block.height:4}: difficulty {difficulty} "
# f"time: {new_timestamp - las... | @@ -1303,8 +1309,10 @@ def get_consecutive_blocks(
available_coins.remove(rem)
available_coins.extend(new_gen.additions)
+ if full_block.transactions_generator is not None:
+ generator_block... | chia/simulator/block_tools.py | 26 | Python | 0.071 | suggestion | 44 | 51 | 51 | false | fix BlockTools confusion between tx block and block with generators | 20,212 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | arvidn | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix BlockTools confusion between tx block and block with generators
BEFORE CODE: # f"removals: {len(new_gen.removals) if block_record.is_transaction_block else 0:2} "
#... | This fixes tracking of previous *generators* | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
fields.append(
Field(
name=field.name,
type=hint,
has_default=field.default is not dataclasses.MISSING
or field.default_factory is not dataclasses.MISSING,
stream_function=function_to_stream_one_item(hint),
... | This is a real change. The new `X | Y` syntax results in a different type upon inspection. | hint = hints[field.name]
fields.append(
Field(
name=field.name,
type=hint,
has_default=field.default is not dataclasses.MISSING
or field.default_factory is not dataclasses.MISSING,
stream_function=function_to_str... | @@ -120,7 +121,7 @@ def is_type_SpecificOptional(f_type: object) -> bool:
"""
Returns true for types such as Optional[T], but not Optional, or T.
"""
- return get_origin(f_type) == Union and get_args(f_type)[1]() is None
+ return get_origin(f_type) in {Union, UnionType} and get_args(f_type)[1]() is... | chia/util/streamable.py | 26 | Python | 0.571 | suggestion | 91 | 51 | 51 | false | Manual fixes for upcoming Ruff pyupgrade push | 20,213 | Chia-Network/chia-blockchain | 10,822 | Python | Quexington | Quexington | Review this pull request change.
Language: Python
File: chia/util/streamable.py
PR Title: Manual fixes for upcoming Ruff pyupgrade push
BEFORE CODE: fields.append(
Field(
name=field.name,
type=hint,
has_default=field.default is not dataclasses.MISS... | This is a real change. The new `X | Y` syntax results in a different type upon inspection. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# this counter is counting down to zero
epoch_counter = (1 << phase_out_epoch_bits) - (
prev_transaction_block_height - constants.HARD_FORK2_HEIGHT
) // constants.EPOCH_BLOCKS
# if we're past the phase-out, v1 plots are unconditionally invalid
if epoch_counter <= 0:
return True
... | i would probably add a log for this |
# this counter is counting down to zero
epoch_counter = (1 << phase_out_epoch_bits) - (
prev_transaction_block_height - constants.HARD_FORK2_HEIGHT
) // constants.EPOCH_BLOCKS
# if we're past the phase-out, v1 plots are unconditionally invalid
if epoch_counter <= 0:
return True
... | @@ -75,14 +75,56 @@ def check_plot_size(constants: ConsensusConstants, ps: PlotSize) -> bool:
return True
+def is_v1_phased_out(
+ proof: bytes,
+ prev_transaction_block_height: uint32, # this is the height of the last tx block before the current block SP
+ constants: ConsensusConstants,
+) -> bool:
... | chia/types/blockchain_format/proof_of_space.py | 26 | Python | 0.071 | suggestion | 35 | 51 | 51 | false | [CHIA-3795] change v1 plot phase-out | 20,216 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/types/blockchain_format/proof_of_space.py
PR Title: [CHIA-3795] change v1 plot phase-out
BEFORE CODE:
# this counter is counting down to zero
epoch_counter = (1 << phase_out_epoch_bits) - (
prev_transaction_block_height - constants.HARD_F... | i would probably add a log for this | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if first_in_sub_epoch and segment.sub_epoch_n == 0 and idx == 0:
cc_sub_slot_hash = constants.GENESIS_CHALLENGE
else:
cc_sub_slot_hash = __get_cc_sub_slot(segment.sub_slots, idx, ses).get_hash()
sub_slot_data: SubSlotData = segment.sub_slots[idx]
if sub_slot_data.signage_point_index an... | here we dont have information about where the previous transaction block is, passing 0 currently ignores the phaseout completely i think we can do better just give x blocks bellow height, wouldn't be accurate but i dont see other options | if first_in_sub_epoch and segment.sub_epoch_n == 0 and idx == 0:
cc_sub_slot_hash = constants.GENESIS_CHALLENGE
else:
cc_sub_slot_hash = __get_cc_sub_slot(segment.sub_slots, idx, ses).get_hash()
sub_slot_data: SubSlotData = segment.sub_slots[idx]
if sub_slot_data.signage_point_index an... | chia/full_node/weight_proof.py | 26 | Python | 0.5 | style | 239 | 51 | 51 | false | [CHIA-3795] change v1 plot phase-out | 20,216 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/weight_proof.py
PR Title: [CHIA-3795] change v1 plot phase-out
BEFORE CODE: if first_in_sub_epoch and segment.sub_epoch_n == 0 and idx == 0:
cc_sub_slot_hash = constants.GENESIS_CHALLENGE
else:
cc_sub_slot_hash = __get_cc... | here we dont have information about where the previous transaction block is, passing 0 currently ignores the phaseout completely i think we can do better just give x blocks bellow height, wouldn't be accurate but i dont see other options | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. | |
field.name: getattr(autofilled_cs_config, field.name)
for field in dataclasses.fields(autofilled_cs_config)
}
)
if await self.service.wallet_state_manager.synced() is False:
raise ValueError("Wallet needs to be fully synced before selecting coins"... | This is the motivating change behind the PR. I wanted to centralize this complexity rather than have the logic at the endpoints. | )
tx_config = DEFAULT_TX_CONFIG.override(
**{
field.name: getattr(autofilled_cs_config, field.name)
for field in dataclasses.fields(autofilled_cs_config)
}
)
if await self.service.wallet_state_manager.synced() is False:
... | @@ -1800,16 +1803,9 @@ async def get_spendable_coins(self, request: GetSpendableCoins) -> GetSpendableC
raise ValueError("Wallet needs to be fully synced before getting all coins")
state_mgr = self.service.wallet_state_manager
- wallet = state_mgr.wallets[request.wallet_id]
async... | chia/wallet/wallet_rpc_api.py | 26 | Python | 0.429 | performance | 129 | 51 | 51 | false | [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet` | 20,230 | Chia-Network/chia-blockchain | 10,822 | Python | Quexington | Quexington | Review this pull request change.
Language: Python
File: chia/wallet/wallet_rpc_api.py
PR Title: [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet`
BEFORE CODE: field.name: getattr(autofilled_cs_config, field.name)
for field in dataclasses.fields(autofill... | This is the motivating change behind the PR. I wanted to centralize this complexity rather than have the logic at the endpoints. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
for record in record_list:
lineage = await self.get_lineage_proof_for_coin(record.coin)
if lineage is not None:
amount = uint128(amount + record.coin.amount)
self.log.info(f"Confirmed balance for cat wallet {self.id()} is {amount}")
return uint128(amount)... | Does `in_one_block=True` match with the old behaviour? | for record in record_list:
lineage = await self.get_lineage_proof_for_coin(record.coin)
if lineage is not None:
amount = uint128(amount + record.coin.amount)
self.log.info(f"Confirmed balance for cat wallet {self.id()} is {amount}")
return uint128(amount)... | @@ -338,15 +338,15 @@ def max_send_quantity(self) -> int:
# avoid full block TXs
return int(self.wallet_state_manager.constants.MAX_BLOCK_COST_CLVM / 2 / self.cost_of_single_tx)
- async def get_max_spendable_coins(self, records: Optional[set[WalletCoinRecord]] = None) -> set[WalletCoinRecord]:
- ... | chia/wallet/cat_wallet/cat_wallet.py | 26 | Python | 0.357 | question | 54 | 51 | 51 | false | [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet` | 20,230 | Chia-Network/chia-blockchain | 10,822 | Python | aqk | Quexington | Review this pull request change.
Language: Python
File: chia/wallet/cat_wallet/cat_wallet.py
PR Title: [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet`
BEFORE CODE: for record in record_list:
lineage = await self.get_lineage_proof_for_coin(record.coin)
... | Does `in_one_block=True` match with the old behaviour? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
unconfirmed_tx = await self.wallet_state_manager.tx_store.get_unconfirmed_for_wallet(self.id())
addition_amount = 0
for record in unconfirmed_tx:
if not record.is_in_mempool() and record.spend_bundle is not None:
continue
our_spend = False
for ... | For calls to `is_coin_spendable`, what will happen if the blockchain is not synced, or the wallet is not done processing the current head at the time of the call? | unconfirmed_tx = await self.wallet_state_manager.tx_store.get_unconfirmed_for_wallet(self.id())
addition_amount = 0
for record in unconfirmed_tx:
if not record.is_in_mempool() and record.spend_bundle is not None:
continue
our_spend = False
for ... | @@ -475,19 +475,9 @@ async def get_pending_change_balance(self) -> uint64:
return uint64(addition_amount)
- async def get_cat_spendable_coins(self, records: Optional[set[WalletCoinRecord]] = None) -> list[WalletCoinRecord]:
- result: list[WalletCoinRecord] = []
-
- record_list: set[WalletC... | chia/wallet/cat_wallet/cat_wallet.py | 26 | Python | 0.5 | question | 162 | 51 | 51 | false | [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet` | 20,230 | Chia-Network/chia-blockchain | 10,822 | Python | aqk | Quexington | Review this pull request change.
Language: Python
File: chia/wallet/cat_wallet/cat_wallet.py
PR Title: [LABS-296] Merge `get_cat_spendable_coins` into `get_spendable_coins_for_wallet`
BEFORE CODE: unconfirmed_tx = await self.wallet_state_manager.tx_store.get_unconfirmed_for_wallet(self.id())
additio... | For calls to `is_coin_spendable`, what will happen if the blockchain is not synced, or the wallet is not done processing the current head at the time of the call? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
challenges_to_look_for = 1
reversed_challenge_hashes: list[bytes32] = []
curr: BlockRecord = blocks.block_record(header_block.prev_header_hash)
while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_c... | ```suggestion
*,
prev_b_hash: bytes32,
```
Does this make sense? It forces these parameters to be named. Is it overkill? I think the `bool` should be named at least. | challenges_to_look_for = 1
reversed_challenge_hashes: list[bytes32] = []
curr: BlockRecord = blocks.block_record(header_block.prev_header_hash)
while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_c... | @@ -103,27 +103,20 @@ def get_block_challenge(
def prev_tx_block(
+ constants: ConsensusConstants,
blocks: BlockRecordsProtocol,
- prev_b: Optional[Union[BlockRecord, FullBlock, HeaderBlock]],
+ prev_b_hash: bytes32, | chia/consensus/get_block_challenge.py | 26 | Python | 0.786 | suggestion | 173 | 37 | 41 | false | prev_tx_before_sp | 20,235 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/get_block_challenge.py
PR Title: prev_tx_before_sp
BEFORE CODE: challenges_to_look_for = 1
reversed_challenge_hashes: list[bytes32] = []
curr: BlockRecord = blocks.block_record(header_block.prev_header_hash)
w... | ```suggestion
*,
prev_b_hash: bytes32,
```
Does this make sense? It forces these parameters to be named. Is it overkill? I think the `bool` should be named at least. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_challenge_slot_hashes is not None
reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes... | a doc-string explaining what this function does would be nice | while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_challenge_slot_hashes is not None
reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes... | @@ -103,27 +103,20 @@ def get_block_challenge(
def prev_tx_block(
+ constants: ConsensusConstants,
blocks: BlockRecordsProtocol,
- prev_b: Optional[Union[BlockRecord, FullBlock, HeaderBlock]],
+ prev_b_hash: bytes32,
+ sp_index: uint8,
+ first_in_sub_slot: bool,
) -> uint32: | chia/consensus/get_block_challenge.py | 26 | Python | 0.214 | suggestion | 61 | 34 | 38 | false | prev_tx_before_sp | 20,235 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/get_block_challenge.py
PR Title: prev_tx_before_sp
BEFORE CODE: while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_challenge_slot_hashes is not None
... | a doc-string explaining what this function does would be nice | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes) >= challenges_to_look_for:
break
if curr.height == 0:
assert curr.finished_challenge_slot_hashes is not None
assert... | if `blocks` is an empty cache (`BlockCache`), this would throw, wouldn't it? I think this is a change in behavior in some call sites | reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes) >= challenges_to_look_for:
break
if curr.height == 0:
assert curr.finished_challenge_slot_hashes is not None
assert... | @@ -103,27 +103,20 @@ def get_block_challenge(
def prev_tx_block(
+ constants: ConsensusConstants,
blocks: BlockRecordsProtocol,
- prev_b: Optional[Union[BlockRecord, FullBlock, HeaderBlock]],
+ prev_b_hash: bytes32,
+ sp_index: uint8,
+ first_in_sub_slot: bool,
) -> uint32:
- # todo add ch... | chia/consensus/get_block_challenge.py | 26 | Python | 0.571 | performance | 132 | 31 | 35 | false | prev_tx_before_sp | 20,235 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/get_block_challenge.py
PR Title: prev_tx_before_sp
BEFORE CODE: reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes) >= challenges_to_look_for:
... | if `blocks` is an empty cache (`BlockCache`), this would throw, wouldn't it? I think this is a change in behavior in some call sites | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return []
recent_rc: list[tuple[bytes32, uint128]] = []
curr: Optional[BlockRecord] = peak
while curr is not None and len(recent_rc) < 2 * self.constants.MAX_SUB_SLOT_BLOCKS:
if curr != peak:
recent_rc.append((curr.reward_infusion_new_challenge, curr.total... | the case where `prev_b` is `None` isn't handled in the new version of this. Here it returns `Err.INVALID_PREV_BLOCK_HASH`, in your new version it throws (I think) | return []
recent_rc: list[tuple[bytes32, uint128]] = []
curr: Optional[BlockRecord] = peak
while curr is not None and len(recent_rc) < 2 * self.constants.MAX_SUB_SLOT_BLOCKS:
if curr != peak:
recent_rc.append((curr.reward_infusion_new_challenge, curr.total... | @@ -699,11 +699,13 @@ async def validate_unfinished_block_header(
if len(block.transactions_generator_ref_list) > self.constants.MAX_GENERATOR_REF_LIST_SIZE:
return None, Err.TOO_MANY_GENERATOR_REFS
- prev_b = self.try_block_record(block.prev_header_hash)
- if prev_b is None and bl... | chia/consensus/blockchain.py | 26 | Python | 0.643 | suggestion | 162 | 51 | 51 | false | prev_tx_before_sp | 20,235 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/blockchain.py
PR Title: prev_tx_before_sp
BEFORE CODE: return []
recent_rc: list[tuple[bytes32, uint128]] = []
curr: Optional[BlockRecord] = peak
while curr is not None and len(recent_rc) < 2 * self.constants.... | the case where `prev_b` is `None` isn't handled in the new version of this. Here it returns `Err.INVALID_PREV_BLOCK_HASH`, in your new version it throws (I think) | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
deficit = uint8(0)
adjusted = False
validated_block_count = 0
for idx, block in enumerate(recent_chain.recent_chain_data):
required_iters = uint64(0)
overflow = False
ses = False
height = block.height
for sub_slot in block.finished_sub_slots:
prev_chal... | this change looks unrelated. Could you add a comment to the code explaining why this should be `> 2`? | deficit = uint8(0)
adjusted = False
validated_block_count = 0
for idx, block in enumerate(recent_chain.recent_chain_data):
required_iters = uint64(0)
overflow = False
ses = False
height = block.height
for sub_slot in block.finished_sub_slots:
prev_chal... | @@ -1245,7 +1245,7 @@ def validate_recent_blocks(
if sub_slot.challenge_chain.new_difficulty is not None:
diff = sub_slot.challenge_chain.new_difficulty
- if (challenge is not None) and (prev_challenge is not None) and transaction_blocks > 1:
+ if (challenge is not None) an... | chia/full_node/weight_proof.py | 26 | Python | 0.571 | question | 101 | 51 | 51 | false | prev_tx_before_sp | 20,235 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/full_node/weight_proof.py
PR Title: prev_tx_before_sp
BEFORE CODE: deficit = uint8(0)
adjusted = False
validated_block_count = 0
for idx, block in enumerate(recent_chain.recent_chain_data):
required_iters = uint64(0)
overfl... | this change looks unrelated. Could you add a comment to the code explaining why this should be `> 2`? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# note that we're not technically finding a fork here, we just traverse
# from the current block down to the fork's current peak
chain, peak_hash = await lookup_fork_chain(
self,
(fork_info.peak_height, fork_info.peak_hash),
(block.height - 1, block.prev_heade... | nit but i would move this right before the call to get_flags_for_height_and_constants where it is used | # note that we're not technically finding a fork here, we just traverse
# from the current block down to the fork's current peak
chain, peak_hash = await lookup_fork_chain(
self,
(fork_info.peak_height, fork_info.peak_hash),
(block.height - 1, block.prev_heade... | @@ -270,11 +270,18 @@ async def run_single_block(self, block: FullBlock, fork_info: ForkInfo) -> None:
additions: list[tuple[Coin, Optional[bytes]]] = []
removals: list[tuple[bytes32, Coin]] = []
if block.transactions_generator is not None:
+ prev_tx_height = prev_tx_block( | chia/consensus/blockchain.py | 26 | Python | 0.429 | refactor | 102 | 51 | 51 | false | make sure to pass in the correct previous transaction block height | 20,237 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/consensus/blockchain.py
PR Title: make sure to pass in the correct previous transaction block height
BEFORE CODE: # note that we're not technically finding a fork here, we just traverse
# from the current block down to the fork's current p... | nit but i would move this right before the call to get_flags_for_height_and_constants where it is used | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if event == PlotRefreshEvents.done:
self.plot_sync_sender.sync_done(update_result.removed, update_result.duration)
async def on_disconnect(self, connection: WSChiaConnection) -> None:
self.log.info(f"peer disconnected {connection.get_peer_logging()}")
self.state_changed("close_c... | not related to this pr but why are we not working with Plot here instead of dict[str, Any]? | if event == PlotRefreshEvents.done:
self.plot_sync_sender.sync_done(update_result.removed, update_result.duration)
async def on_disconnect(self, connection: WSChiaConnection) -> None:
self.log.info(f"peer disconnected {connection.get_peer_logging()}")
self.state_changed("close_c... | @@ -196,12 +196,16 @@ def get_plots(self) -> tuple[list[dict[str, Any]], list[str], list[str]]:
param = prover.get_param()
if param.size_v1 is not None:
k = param.size_v1
+ strength = uint8(0)
else:
+ assert pa... | chia/harvester/harvester.py | 26 | Python | 0.286 | question | 91 | 51 | 51 | false | [CHIA-3566] improve v2-plot support in plot-sync | 20,238 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/harvester/harvester.py
PR Title: [CHIA-3566] improve v2-plot support in plot-sync
BEFORE CODE: if event == PlotRefreshEvents.done:
self.plot_sync_sender.sync_done(update_result.removed, update_result.duration)
async def on_disconn... | not related to this pr but why are we not working with Plot here instead of dict[str, Any]? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
self._invalid, self._current_sync.delta.invalid.additions
)
delta_keys_missing: PathListDelta = PathListDelta.from_lists(
self._keys_missing, self._current_sync.delta.keys_missing.additions
)
delta_duplicates: PathListDelta = PathListDelta.from_lists(
... | rename
pi->plot
plot_size->plot_param/param | self._invalid, self._current_sync.delta.invalid.additions
)
delta_keys_missing: PathListDelta = PathListDelta.from_lists(
self._keys_missing, self._current_sync.delta.keys_missing.additions
)
delta_duplicates: PathListDelta = PathListDelta.from_lists(
... | @@ -353,13 +353,15 @@ async def _sync_done(self, data: PlotSyncDone) -> None:
self._duplicates = self._current_sync.delta.duplicates.additions.copy()
self._total_plot_size = sum(plot.file_size for plot in self._plots.values())
+ def expected_plot_size(pi: Plot) -> int: | chia/plot_sync/receiver.py | 26 | Python | 0.143 | suggestion | 44 | 51 | 51 | false | [CHIA-3566] improve v2-plot support in plot-sync | 20,238 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/plot_sync/receiver.py
PR Title: [CHIA-3566] improve v2-plot support in plot-sync
BEFORE CODE: self._invalid, self._current_sync.delta.invalid.additions
)
delta_keys_missing: PathListDelta = PathListDelta.from_lists(
... | rename
pi->plot
plot_size->plot_param/param | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
else:
# Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False,
# Which means no sub slots are omitted
challenges_to_look_for = 2
else:
challenges_to_look_for = 1
reversed_challenge_hashes:... | this comment should probably move to the new function below now | else:
# Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False,
# Which means no sub slots are omitted
challenges_to_look_for = 2
else:
challenges_to_look_for = 1
reversed_challenge_hashes:... | @@ -105,16 +105,16 @@ def get_block_challenge(
# Returns the height of the previous transaction block up to the blocks signage point
# we use this for block validation since when the block is farmed we do not know the latest transaction block
# since a new one might be infused by the time the block is infused | chia/consensus/get_block_challenge.py | 26 | Python | 0.286 | suggestion | 63 | 51 | 51 | false | fix tx block refrences in blocktools | 20,239 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/get_block_challenge.py
PR Title: fix tx block refrences in blocktools
BEFORE CODE: else:
# Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False,
# Which mea... | this comment should probably move to the new function below now | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
def load_block_list(
block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty = uint64(constants.DIFFICULTY_STARTING)
sub_slot_iters = uint64(constants.SUB_SLOT_ITERS_STARTING)
height_to_hash: dict[uint32, bytes32] = {}... | I think you should remove the variable declaration on line 1853 as well. Maybe even rename this variable to `prev_tx_height` |
def load_block_list(
block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty = uint64(constants.DIFFICULTY_STARTING)
sub_slot_iters = uint64(constants.SUB_SLOT_ITERS_STARTING)
height_to_hash: dict[uint32, bytes32] = {}... | @@ -1870,7 +1867,13 @@ def load_block_list(
sp_hash = full_block.reward_chain_block.challenge_chain_sp_vdf.output.get_hash()
cache = BlockCache(blocks)
-
+ prev_transaction_b_height = pre_sp_block_height( | chia/simulator/block_tools.py | 26 | Python | 0.571 | suggestion | 124 | 51 | 51 | false | fix tx block refrences in blocktools | 20,239 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix tx block refrences in blocktools
BEFORE CODE:
def load_block_list(
block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty... | I think you should remove the variable declaration on line 1853 as well. Maybe even rename this variable to `prev_tx_height` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty = uint64(constants.DIFFICULTY_STARTING)
sub_slot_iters = uint64(constants.SUB_SLOT_ITERS_STARTING)
height_to_hash: dict[uint32, bytes32] = {}
blocks: dict[byte... | ```suggestion
blocks=cache,
``` | block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty = uint64(constants.DIFFICULTY_STARTING)
sub_slot_iters = uint64(constants.SUB_SLOT_ITERS_STARTING)
height_to_hash: dict[uint32, bytes32] = {}
blocks: dict[byte... | @@ -1856,7 +1867,13 @@ def load_block_list(
sp_hash = full_block.reward_chain_block.challenge_chain_sp_vdf.output.get_hash()
cache = BlockCache(blocks)
-
+ prev_transaction_b_height = pre_sp_tx_block_height(
+ constants=constants,
+ blocks=BlockCache(blocks), | chia/simulator/block_tools.py | 26 | Python | 0.429 | performance | 43 | 51 | 51 | false | fix tx block refrences in blocktools | 20,239 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix tx block refrences in blocktools
BEFORE CODE: block_list: list[FullBlock], constants: ConsensusConstants
) -> tuple[dict[uint32, bytes32], uint64, dict[bytes32, BlockRecord]]:
difficulty = uint64(constants.DI... | ```suggestion
blocks=cache,
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if signage_point_index <= min_signage_point:
# start farming blocks after min_signage_point
continue
signage_point: SignagePoint = get_signage_point(
constants,
BlockCach... | ```suggestion
sp_index=signage_point_index,
```
I'm pretty sure you need this |
if signage_point_index <= min_signage_point:
# start farming blocks after min_signage_point
continue
signage_point: SignagePoint = get_signage_point(
constants,
BlockCach... | @@ -911,6 +912,14 @@ def get_consecutive_blocks(
assert signage_point.cc_vdf is not None
cc_sp_output_hash = signage_point.cc_vdf.output.get_hash()
+ prev_tx_height = pre_sp_tx_block_height(
+ constants=constants,
+ ... | chia/simulator/block_tools.py | 26 | Python | 0.714 | suggestion | 101 | 51 | 51 | false | fix tx block refrences in blocktools | 20,239 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix tx block refrences in blocktools
BEFORE CODE:
if signage_point_index <= min_signage_point:
# start farming blocks after min_signage_point
... | ```suggestion
sp_index=signage_point_index,
```
I'm pretty sure you need this | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# start farming blocks after min_signage_point
continue
# note that we are passing in the finished slots which include the last slot
signage_point = get_signage_point(
constants,
Block... | ```suggestion
sp_index=signage_point_index,
``` | # start farming blocks after min_signage_point
continue
# note that we are passing in the finished slots which include the last slot
signage_point = get_signage_point(
constants,
Block... | @@ -1216,6 +1222,14 @@ def get_consecutive_blocks(
cc_sp_output_hash = signage_point.cc_vdf.output.get_hash()
# If did not reach the target slots to skip, don't make any proofs for this sub-slot
+ prev_tx_height = pre_sp_tx_block_height(
+ ... | chia/simulator/block_tools.py | 26 | Python | 0.571 | suggestion | 71 | 51 | 51 | false | fix tx block refrences in blocktools | 20,239 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/simulator/block_tools.py
PR Title: fix tx block refrences in blocktools
BEFORE CODE: # start farming blocks after min_signage_point
continue
# note that we are passing in the finished slo... | ```suggestion
sp_index=signage_point_index,
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
],
)
def test_calculate_prefix_bits_v1(height: uint32, expected: int) -> None:
assert calculate_prefix_bits(DEFAULT_CONSTANTS, height, PlotParam.make_v1(32)) == expected
@pytest.mark.parametrize(
argnames=["height", "expected"],
argvalues=[
(0, 5),
(0xFFFFFFFA, 5),
(0xFFFFFFFB,... | we should have one place in the codebase to get this calculation from, probably just a function the receives the Bits | (20643000, 5),
],
)
def test_calculate_prefix_bits_v1(height: uint32, expected: int) -> None:
assert calculate_prefix_bits(DEFAULT_CONSTANTS, height, PlotParam.make_v1(32)) == expected
@pytest.mark.parametrize(
argnames=["height", "expected"],
argvalues=[
(0, 5),
(0xFFFFFFFA, 5... | @@ -286,7 +286,7 @@ def test_v1_phase_out() -> None:
constants = DEFAULT_CONSTANTS.replace(HARD_FORK2_HEIGHT=uint32(500000))
rng = random.Random()
- phase_out_epochs = 1 << constants.PLOT_V1_PHASE_OUT_EPOCH_BITS
+ phase_out_epochs = (1 << constants.PLOT_V1_PHASE_OUT_EPOCH_BITS) - 1 | chia/_tests/core/custom_types/test_proof_of_space.py | 26 | Python | 0.429 | suggestion | 117 | 47 | 48 | false | Tweak phase out | 20,258 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/core/custom_types/test_proof_of_space.py
PR Title: Tweak phase out
BEFORE CODE: ],
)
def test_calculate_prefix_bits_v1(height: uint32, expected: int) -> None:
assert calculate_prefix_bits(DEFAULT_CONSTANTS, height, PlotParam.make_v1(32)) ==... | we should have one place in the codebase to get this calculation from, probably just a function the receives the Bits | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return True
assert size_v1 is not None
if size_v1 < constants.MIN_PLOT_SIZE_V1:
log.error(f"Plot size ({size_v1}) is lower than the minimum ({constants.MIN_PLOT_SIZE_V1})")
return False
if size_v1 > constants.MAX_PLOT_SIZE_V1:
log.error(f"Plot size ({size_v1}) is higher than... | I see. You mean this special case. I can remove it. It was just meant to save a few arithmetic operations. | return True
assert size_v1 is not None
if size_v1 < constants.MIN_PLOT_SIZE_V1:
log.error(f"Plot size ({size_v1}) is lower than the minimum ({constants.MIN_PLOT_SIZE_V1})")
return False
if size_v1 > constants.MAX_PLOT_SIZE_V1:
log.error(f"Plot size ({size_v1}) is higher than... | @@ -84,22 +84,25 @@ def is_v1_phased_out(
# The probability of having been phased out is proportional on the
# number of epochs since hard fork activation
phase_out_epoch_bits = constants.PLOT_V1_PHASE_OUT_EPOCH_BITS
+ if phase_out_epoch_bits == 0:
+ return True | chia/types/blockchain_format/proof_of_space.py | 26 | Python | 0.429 | suggestion | 106 | 51 | 51 | false | Tweak phase out | 20,258 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | arvidn | Review this pull request change.
Language: Python
File: chia/types/blockchain_format/proof_of_space.py
PR Title: Tweak phase out
BEFORE CODE: return True
assert size_v1 is not None
if size_v1 < constants.MIN_PLOT_SIZE_V1:
log.error(f"Plot size ({size_v1}) is lower than the minimum ({constan... | I see. You mean this special case. I can remove it. It was just meant to save a few arithmetic operations. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
total = 0
with self.harvester.plot_manager:
self.harvester.log.debug("new_signage_point_harvester lock acquired")
for try_plot_filename, try_plot_info in self.harvester.plot_manager.plots.items():
# Passes the plot filter (does not check sp filter yet though, sinc... | this is similar to what we do inside is_v1_phased_out right ?
i think we should consolidate | total = 0
with self.harvester.plot_manager:
self.harvester.log.debug("new_signage_point_harvester lock acquired")
for try_plot_filename, try_plot_info in self.harvester.plot_manager.plots.items():
# Passes the plot filter (does not check sp filter yet though, sinc... | @@ -408,10 +409,10 @@ async def lookup_challenge(
else:
constants = self.harvester.constants
# after the phase-out, ignore v1 plots
+ phase_out_epochs = num_phase_out_epochs(constants)
if (
new_ch... | chia/harvester/harvester_api.py | 26 | Python | 0.286 | suggestion | 92 | 51 | 51 | false | Tweak phase out | 20,258 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/harvester/harvester_api.py
PR Title: Tweak phase out
BEFORE CODE: total = 0
with self.harvester.plot_manager:
self.harvester.log.debug("new_signage_point_harvester lock acquired")
for try_plot_filename, try_plot_inf... | this is similar to what we do inside is_v1_phased_out right ?
i think we should consolidate | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return (1 << constants.PLOT_V1_PHASE_OUT_EPOCH_BITS) - 1
def is_v1_phased_out(
proof: bytes,
prev_transaction_block_height: uint32, # this is the height of the last tx block before the current block SP
constants: ConsensusConstants,
) -> bool:
if prev_transaction_block_height < constants.HARD_FOR... | this is not right. it should be `< 0` | return (1 << constants.PLOT_V1_PHASE_OUT_EPOCH_BITS) - 1
def v1_cut_off_height(constants: ConsensusConstants) -> int:
"""
returns the height where v1 proofs-of-space are no longer valid. Blocks
whose previous transaction block is equal to or higher than this may not have a
v1 proof.
"""
re... | @@ -83,23 +93,22 @@ def is_v1_phased_out(
# This is a v1 plot and the phase-out period has started
# The probability of having been phased out is proportional on the
# number of epochs since hard fork activation
- phase_out_epoch_bits = constants.PLOT_V1_PHASE_OUT_EPOCH_BITS
- phase_out_epoch_mask ... | chia/types/blockchain_format/proof_of_space.py | 26 | Python | 0.286 | suggestion | 37 | 51 | 51 | false | Tweak phase out | 20,258 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | arvidn | Review this pull request change.
Language: Python
File: chia/types/blockchain_format/proof_of_space.py
PR Title: Tweak phase out
BEFORE CODE: return (1 << constants.PLOT_V1_PHASE_OUT_EPOCH_BITS) - 1
def is_v1_phased_out(
proof: bytes,
prev_transaction_block_height: uint32, # this is the height of the... | this is not right. it should be `< 0` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
def __init__(self, peer_size_limit: int, log: logging.Logger) -> None:
self._list_cursor = 0
self._queue_length = asyncio.Semaphore(0) # default is 1
self._index_to_peer_map = []
... | we want to service high fee per cost first, right? If the priority queue sort low values first, I think it would be easier to just use cost per fee as the key. Either way, I think it warrants a comment. Intuitively, high priority comes first. | _high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
def __init__(self, peer_size_limit: int, log: logging.Logger) -> None:
self._list_cursor = 0
self._queue_length = asyncio.Semaphore(0) # default is 1
self._index_to_peer_map = []
... | @@ -104,10 +104,22 @@ async def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_pri
self._high_priority_queue.put(tx)
else:
if peer_id not in self._queue_dict:
- self._queue_dict[peer_id] = SimpleQueue()
+ self._queue_dict[peer_id] = as... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.5 | style | 242 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: _high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
de... | we want to service high fee per cost first, right? If the priority queue sort low values first, I think it would be easier to just use cost per fee as the key. Either way, I think it warrants a comment. Intuitively, high priority comes first. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
transaction_bytes: bytes | None = field(compare=False)
spend_name: bytes32
peer: WSChiaConnection | None = field(compare=False)
test: bool = field(compare=False)
# IDs of peers that advertised this transaction via new_transaction, along
# with their hostname, fee and cost.
peers_with_tx: dic... | I don't think we want an async queue | transaction_bytes: bytes | None = field(compare=False)
spend_name: bytes32
peer: WSChiaConnection | None = field(compare=False)
test: bool = field(compare=False)
# IDs of peers that advertised this transaction via new_transaction, along
# with their hostname, fee and cost.
peers_with_tx: dic... | @@ -85,7 +85,7 @@ class TransactionQueue:
_list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
- _queue_dict: dict[bytes32, SimpleQueue[TransactionQueueEntry]]
+ _queue_dict: dict[bytes32, asyncio.PriorityQueue[tuple[float, TransactionQueueEntr... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.071 | suggestion | 36 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: transaction_bytes: bytes | None = field(compare=False)
spend_name: bytes32
peer: WSChiaConnection | None ... | I don't think we want an async queue | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
_queue_dict: dict[bytes32, asyncio.PriorityQueue[tuple[float, TransactionQueueEntry]]]
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
def __init__(self, peer_size_limit: int... | why would `tx_info` ever be `None` here? In what scenario would that happen? | _queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
_queue_dict: dict[bytes32, PriorityQueue[tuple[float, TransactionQueueEntry]]]
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
def __init__(self, peer_size_limit: int, log: l... | @@ -104,10 +104,22 @@ async def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_pri
self._high_priority_queue.put(tx)
else:
if peer_id not in self._queue_dict:
- self._queue_dict[peer_id] = SimpleQueue()
+ self._queue_dict[peer_id] = as... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | question | 76 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: _queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
_queue_dict: dict[bytes32, asyncio.Pri... | why would `tx_info` ever be `None` here? In what scenario would that happen? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
self._queue_dict = {}
self._high_priority_queue = SimpleQueue() # we don't limit the number of high priority transactions
self.peer_size_limit = peer_size_limit
self.log = log
async def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority: bool = False) -> No... | This else-block seems suspicious. Don't we always know the cost and fee of a transaction? At least we should know what the peer advertized it as, even if it's wrong. | self._queue_dict = {}
self._high_priority_queue = SimpleQueue() # we don't limit the number of high priority transactions
self.peer_size_limit = peer_size_limit
self.log = log
def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority: bool = False) -> None:
... | @@ -104,10 +104,22 @@ async def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_pri
self._high_priority_queue.put(tx)
else:
if peer_id not in self._queue_dict:
- self._queue_dict[peer_id] = SimpleQueue()
+ self._queue_dict[peer_id] = as... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.429 | bug | 165 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: self._queue_dict = {}
self._high_priority_queue = SimpleQueue() # we don't limit the number of high ... | This else-block seems suspicious. Don't we always know the cost and fee of a transaction? At least we should know what the peer advertized it as, even if it's wrong. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
This class replaces one queue by using a high priority queue for local transactions and separate queues for peers.
Local transactions are processed first.
Then the next transaction is taken from the next non-empty queue after the last processed queue. (round-robin)
This decreases the effects of one peer... | is the high-priority case when we receive a transaction via the RPC? `pushtx`? | This class replaces one queue by using a high priority queue for local transactions and separate queues for peers.
Local transactions are processed first.
Then the next transaction is taken from the next non-empty queue after the last processed queue. (round-robin)
This decreases the effects of one peer... | @@ -104,10 +104,22 @@ async def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_pri
self._high_priority_queue.put(tx) | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | question | 78 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: This class replaces one queue by using a high priority queue for local transactions and separate queues for peers... | is the high-priority case when we receive a transaction via the RPC? `pushtx`? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if tx_info is not None and tx_info.advertised_cost > 0:
fpc = tx_info.advertised_fee / tx_info.advertised_cost
priority = -fpc
else:
# Compute the fee per cost using values from the peer with
# the highest ad... | I don't think we want this queue to be `async` | if tx_info is not None and tx_info.advertised_cost > 0:
fpc = tx_info.advertised_fee / tx_info.advertised_cost
# PriorityQueue returns lowest first so we invert
priority = -fpc
else:
# This peer didn't advert... | @@ -121,7 +133,7 @@ async def pop(self) -> TransactionQueueEntry:
while True:
peer_queue = self._queue_dict[self._index_to_peer_map[self._list_cursor]]
if not peer_queue.empty():
- result = peer_queue.get()
+ _, result = await peer_queue.get() | chia/full_node/tx_processing_queue.py | 26 | Python | 0.214 | suggestion | 46 | 40 | 38 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: if tx_info is not None and tx_info.advertised_cost > 0:
fpc = tx_info.advertised_... | I don't think we want this queue to be `async` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
higher_tx_cost = uint64(20)
lower_tx_cost = uint64(10)
higher_tx_fee = uint64(5)
lower_tx_fee = uint64(1)
# 2 for a, 1 for b, 2 for c
peer_tx_a = [
get_transaction_queue_entry(peer_a, 0, {peer_a: PeerWithTx(str(peer_a), lower_tx_fee, higher_tx_cost)}),
get_transaction_queue_entry... | what's the type error we're ignoring here? |
higher_tx_cost = uint64(20)
lower_tx_cost = uint64(10)
higher_tx_fee = uint64(5)
lower_tx_fee = uint64(1)
# 2 for a, 1 for b, 2 for c
peer_tx_a = [
get_transaction_queue_entry(peer_a, 0, {peer_a: PeerWithTx(str(peer_a), lower_tx_fee, higher_tx_cost)}),
get_transaction_queue_entr... | @@ -135,20 +142,99 @@ async def test_queue_cleanup_and_fairness(seeded_random: random.Random) -> None:
peer_b = bytes32.random(seeded_random)
peer_c = bytes32.random(seeded_random)
+ higher_tx_cost = uint64(20)
+ lower_tx_cost = uint64(10)
+ higher_tx_fee = uint64(5)
+ lower_tx_fee = uint64(1)
... | chia/_tests/core/full_node/test_tx_processing_queue.py | 26 | Python | 0.214 | question | 42 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: higher_tx_cost = uint64(20)
lower_tx_cost = uint64(10)
higher_tx_fee = uint64(5)
low... | what's the type error we're ignoring here? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
entries.append((entry.peer_id, entry.index)) # type: ignore[attr-defined]
assert [(peer_a, 1), (peer_b, 0), (peer_c, 0)] == entries # all peers have been properly included in the queue.
second_entries = []
for _ in range(2): # we validate that we properly queue the last 2 transactions
ent... | this is only testing that two items with the same spend name are *equal*, not that < or > comparisons work as we expect | entry = await transaction_queue.pop()
entries.append((entry.peer_id, entry.index)) # type: ignore[attr-defined]
assert [(peer_a, 1), (peer_b, 0), (peer_c, 0)] == entries # all peers have been properly included in the queue.
second_entries = []
for _ in range(2): # we validate that we prop... | @@ -135,20 +142,99 @@ async def test_queue_cleanup_and_fairness(seeded_random: random.Random) -> None:
peer_b = bytes32.random(seeded_random)
peer_c = bytes32.random(seeded_random)
+ higher_tx_cost = uint64(20)
+ lower_tx_cost = uint64(10)
+ higher_tx_fee = uint64(5)
+ lower_tx_fee = uint64(1)
... | chia/_tests/core/full_node/test_tx_processing_queue.py | 26 | Python | 0.357 | suggestion | 119 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: entries.append((entry.peer_id, entry.index)) # type: ignore[attr-defined]
assert [(peer... | this is only testing that two items with the same spend name are *equal*, not that < or > comparisons work as we expect | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# peers with transactions maps.
peer3 = bytes32.random()
peers_with_tx1 = {
# This has FPC of 5.0
peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_... | what type error is ignore here? It would probably be a good idea to add a comment here, justifying the ignore-statement. Same in the other places where you ignore mypy errors | peer3 = bytes32.random()
peers_with_tx1 = {
# This has FPC of 5.0
peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_transaction_queue_entry(peer3, 0, pe... | @@ -135,20 +142,99 @@ async def test_queue_cleanup_and_fairness(seeded_random: random.Random) -> None:
peer_b = bytes32.random(seeded_random)
peer_c = bytes32.random(seeded_random)
+ higher_tx_cost = uint64(20)
+ lower_tx_cost = uint64(10)
+ higher_tx_fee = uint64(5)
+ lower_tx_fee = uint64(1)
... | chia/_tests/core/full_node/test_tx_processing_queue.py | 26 | Python | 0.5 | question | 174 | 33 | 31 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: # peers with transactions maps.
peer3 = bytes32.random()
peers_with_tx1 = {
# Th... | what type error is ignore here? It would probably be a good idea to add a comment here, justifying the ignore-statement. Same in the other places where you ignore mypy errors | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# peers with transactions maps.
peer3 = bytes32.random()
peers_with_tx1 = {
# This has FPC of 5.0
peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_... | you can't really compare floating points with `==` | peer3 = bytes32.random()
peers_with_tx1 = {
# This has FPC of 5.0
peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_transaction_queue_entry(peer3, 0, pe... | @@ -135,20 +142,99 @@ async def test_queue_cleanup_and_fairness(seeded_random: random.Random) -> None:
peer_b = bytes32.random(seeded_random)
peer_c = bytes32.random(seeded_random)
+ higher_tx_cost = uint64(20)
+ lower_tx_cost = uint64(10)
+ higher_tx_fee = uint64(5)
+ lower_tx_fee = uint64(1)
... | chia/_tests/core/full_node/test_tx_processing_queue.py | 26 | Python | 0.357 | suggestion | 50 | 33 | 31 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: # peers with transactions maps.
peer3 = bytes32.random()
peers_with_tx1 = {
# Th... | you can't really compare floating points with `==` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_transaction_queue_entry(peer3, 0, peers_with_tx1)
queue.put(tx1, peer3)
peers_with_tx2 = {
# This has ... | this looks even more suspicious. Is it really safe to perform `==` comparison against `inf`? | # This has FPC of 2.0 but higher advertised cost
peer2: PeerWithTx(str(peer2), uint64(20), uint64(10)),
}
tx1 = get_transaction_queue_entry(peer3, 0, peers_with_tx1)
queue.put(tx1, peer3)
peers_with_tx2 = {
# This has FPC of 3.0
peer1: PeerWithTx(str(peer1), uint64(30), u... | @@ -135,20 +142,99 @@ async def test_queue_cleanup_and_fairness(seeded_random: random.Random) -> None:
peer_b = bytes32.random(seeded_random)
peer_c = bytes32.random(seeded_random)
+ higher_tx_cost = uint64(20)
+ lower_tx_cost = uint64(10)
+ higher_tx_fee = uint64(5)
+ lower_tx_fee = uint64(1)
... | chia/_tests/core/full_node/test_tx_processing_queue.py | 26 | Python | 0.357 | question | 92 | 29 | 27 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: peer1: PeerWithTx(str(peer1), uint64(10), uint64(2)),
# This has FPC of 2.0 but high... | this looks even more suspicious. Is it really safe to perform `==` comparison against `inf`? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
self._high_priority_queue = SimpleQueue() # we don't limit the number of high priority transactions
self.peer_size_limit = peer_size_limit
self.log = log
def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority: bool = False) -> None:
if peer_id is None or hi... | here too. It seems more appropriate to set:
```
priority = tx_info.advertised_cost / tx_info.advertised_fee
``` | self._high_priority_queue = SimpleQueue() # we don't limit the number of high priority transactions
self.peer_size_limit = peer_size_limit
self.log = log
def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority: bool = False) -> None:
if peer_id is None or hi... | @@ -104,10 +104,24 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
self._high_priority_queue.put(tx)
else:
if peer_id not in self._queue_dict:
- self._queue_dict[peer_id] = SimpleQueue()
+ self._queue_dict[peer_id] = Pr... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.714 | suggestion | 111 | 51 | 51 | false | CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost | 20,282 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3810 In TransactionQueue, prioritize peer queue transactions by fee per cost
BEFORE CODE: self._high_priority_queue = SimpleQueue() # we don't limit the number of high priority transactions
... | here too. It seems more appropriate to set:
```
priority = tx_info.advertised_cost / tx_info.advertised_fee
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if sub_slot_data.signage_point_index and is_overflow_block(constants, sub_slot_data.signage_point_index):
curr_slot = segment.sub_slots[idx - 1]
assert curr_slot.cc_slot_end_info
challenge = curr_slot.cc_slot_end_info.challenge
else:
challenge = cc_sub_slot_hash
if sub_slot_... | why not just pass 0 instead of the transaction height ?
i think that would be much simpler
| if sub_slot_data.signage_point_index and is_overflow_block(constants, sub_slot_data.signage_point_index):
curr_slot = segment.sub_slots[idx - 1]
assert curr_slot.cc_slot_end_info
challenge = curr_slot.cc_slot_end_info.challenge
else:
challenge = cc_sub_slot_hash
if sub_slot_... | @@ -1386,6 +1386,7 @@ def __validate_pospace(
height,
curr_diff,
uint32(max(0, height - constants.MAX_SUB_SLOT_BLOCKS)), | chia/full_node/weight_proof.py | 26 | Python | 0.286 | question | 92 | 51 | 51 | false | relax PoS validation in weight proofs | 20,298 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/weight_proof.py
PR Title: relax PoS validation in weight proofs
BEFORE CODE: if sub_slot_data.signage_point_index and is_overflow_block(constants, sub_slot_data.signage_point_index):
curr_slot = segment.sub_slots[idx - 1]
ass... | why not just pass 0 instead of the transaction height ?
i think that would be much simpler
| You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
@asynccontextmanager
async def setup_full_system_inner(
b_tools: BlockTools | None,
b_tools_1: BlockTools | None,
connect_to_daemon: bool,
consensus_constants: ConsensusConstants,
db_version: int,
keychain1: Keychain,
keychain2: Keychain,
shared_b_tools: BlockTools,
) -> AsyncIterator[Fu... | it's not obvious that it's safe to start these block tools *after* we try to find available local listen ports. They may try to open listen sockets themselves. I think it would be safer to move these up to create them in the original order | b_tools: BlockTools | None,
b_tools_1: BlockTools | None,
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_sync_w... | @@ -370,21 +383,26 @@ async def setup_full_system_inner(
shared_b_tools: BlockTools,
) -> AsyncIterator[FullSystem]:
config_overrides = {"full_node.max_sync_wait": 0, "full_node.log_coins": True}
- if b_tools is None:
- b_tools = await create_block_tools_async(
- constants=consensus_cons... | chia/_tests/util/setup_nodes.py | 26 | Python | 0.5 | suggestion | 239 | 51 | 51 | false | context manager for BlockTools | 20,326 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | emlowe | Review this pull request change.
Language: Python
File: chia/_tests/util/setup_nodes.py
PR Title: context manager for BlockTools
BEFORE CODE: @asynccontextmanager
async def setup_full_system_inner(
b_tools: BlockTools | None,
b_tools_1: BlockTools | None,
connect_to_daemon: bool,
consensus_constants... | it's not obvious that it's safe to start these block tools *after* we try to find available local listen ports. They may try to open listen sockets themselves. I think it would be safer to move these up to create them in the original order | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
@pytest.fixture(scope="session")
def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
ret: ConsensusConstants = test_constants
if consensus_mode >= ConsensusMode.HARD_FORK_2_0:
ret = ret.replace(
HARD_FORK_HEIGHT=uint32(2),
PLOT_FILTER_128_HEIGHT=uint32... | ideally we would keep the type annotation for the return value |
@pytest.fixture(scope="session")
def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
ret: ConsensusConstants = test_constants
if consensus_mode >= ConsensusMode.HARD_FORK_2_0:
ret = ret.replace(
HARD_FORK_HEIGHT=uint32(2),
PLOT_FILTER_128_HEIGHT=uint32... | @@ -231,12 +231,12 @@ def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
@pytest.fixture(scope="session", name="bt")
-async def block_tools_fixture(get_keychain, blockchain_constants, anyio_backend, testrun_uid: str) -> BlockTools:
+async def block_tools_fixture(get_keychain, blockchain... | chia/_tests/conftest.py | 26 | Python | 0.357 | suggestion | 62 | 51 | 51 | false | context manager for BlockTools | 20,326 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | emlowe | Review this pull request change.
Language: Python
File: chia/_tests/conftest.py
PR Title: context manager for BlockTools
BEFORE CODE:
@pytest.fixture(scope="session")
def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
ret: ConsensusConstants = test_constants
if consensus_mode >=... | ideally we would keep the type annotation for the return value | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
await add_blocks_in_batches(default_400_blocks, trusted_full_node_api.full_node)
await add_blocks_in_batches(default_1000_blocks[:400], untrusted_full_node_api.full_node)
with (
patch_request_handler(api=untrusted_full_node_api, handler=register_for_ph_updates),
caplog.at_level(logging.INF... | From what I see I think they just had a thinko about asserting `only_trusted_peer`'s return (which happens by default in `time_out_assert`) and asserting `time_out_assert` instead. | await add_blocks_in_batches(default_1500_blocks[:600], trusted_full_node_api.full_node)
await add_blocks_in_batches(default_1000_blocks[:600], untrusted_full_node_api.full_node)
with (
patch_request_handler(api=untrusted_full_node_api, handler=register_for_ph_updates),
caplog.at_level(loggi... | @@ -1683,22 +1672,29 @@ def only_trusted_peer() -> bool:
await add_blocks_in_batches(default_1000_blocks[:400], untrusted_full_node_api.full_node)
- with patch_request_handler(api=untrusted_full_node_api, handler=register_for_ph_updates):
+ with (
+ patch_request_handler(api=untrusted_full_node_ap... | chia/_tests/wallet/sync/test_wallet_sync.py | 26 | Python | 0.571 | suggestion | 180 | 51 | 51 | false | Fixes to test_long_sync_untrusted_break | 20,327 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | emlowe | Review this pull request change.
Language: Python
File: chia/_tests/wallet/sync/test_wallet_sync.py
PR Title: Fixes to test_long_sync_untrusted_break
BEFORE CODE: await add_blocks_in_batches(default_400_blocks, trusted_full_node_api.full_node)
await add_blocks_in_batches(default_1000_blocks[:400], untruste... | From what I see I think they just had a thinko about asserting `only_trusted_peer`'s return (which happens by default in `time_out_assert`) and asserting `time_out_assert` instead. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
from __future__ import annotations
import asyncio
import contextlib
import dataclasses
import logging
import random
import time
from collections.abc import Awaitable, Coroutine
from typing import Any
import pytest
from chia_rs import (
AugSchemeMPL,
Coin,
CoinRecord,
ConsensusConstants,
Foliage,
... | ```suggestion
assert False # pragma: no cover
``` |
@pytest.mark.anyio
@pytest.mark.limit_consensus_modes(allowed=[ConsensusMode.HARD_FORK_2_0], reason="save time")
async def test_corrupt_blockchain(bt: BlockTools, default_400_blocks: list[FullBlock]) -> None:
full_node = await FullNode.create(
bt.config["full_node"],
root_path=bt.root_path,
... | @@ -3492,3 +3495,29 @@ async def test_new_tx_zero_cost(
await ws_con_2.send_message(msg)
# Make sure the first full node has banned the second.
await time_out_assert(3, lambda: full_node_2_ip in server_1.banned_peers)
+
+
+@pytest.mark.anyio
+@pytest.mark.limit_consensus_modes(allowed=[ConsensusMode.HARD... | chia/_tests/core/full_node/test_full_node.py | 26 | Python | 0.571 | suggestion | 62 | 3,495 | 27 | false | Add test for code in FullNode that checks DB | 20,346 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | emlowe | Review this pull request change.
Language: Python
File: chia/_tests/core/full_node/test_full_node.py
PR Title: Add test for code in FullNode that checks DB
BEFORE CODE: from __future__ import annotations
import asyncio
import contextlib
import dataclasses
import logging
import random
import time
from collections.a... | ```suggestion
assert False # pragma: no cover
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
peers_with_tx: dict[bytes32, PeerWithTx] = field(default_factory=dict, compare=False)
done: ValuedEvent[tuple[MempoolInclusionStatus, Err | None]] = field(
default_factory=ValuedEvent,
compare=False,
)
@dataclass
class TransactionQueue:
"""
This class replaces one queue by using a ... | isn't `_queue_dict` also a map of the same peer IDs?
It would seem cheaper and simpler to stick this `int` in that dict instead. Am I missing something? | peers_with_tx: dict[bytes32, PeerWithTx] = field(default_factory=dict, compare=False)
done: ValuedEvent[tuple[MempoolInclusionStatus, Err | None]] = field(
default_factory=ValuedEvent,
compare=False,
)
@dataclass
class PeerTransactionsQueue:
# Peer's priority queue of the form (negativ... | @@ -89,15 +89,23 @@ class TransactionQueue:
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
+ _max_tx_clvm_cost: uint64
+ # Map of peer ID to deficit counter in the context of deficit round robin
+ _deficit_counters: dict[bytes32, int] | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | question | 152 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: peers_with_tx: dict[bytes32, PeerWithTx] = field(default_factory=dict, compare=False)
done: ValuedE... | isn't `_queue_dict` also a map of the same peer IDs?
It would seem cheaper and simpler to stick this `int` in that dict instead. Am I missing something? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
self._queue_length.release() # increment semaphore to indicate that we have a new item in the queue
def _cleanup_peer_queues(self) -> None:
"""
Removes empty peer queues and updates the cursor accordin... | I think this deserves a comment explaining the idea behind this behavior. that we want to service transactions fairly between peers, based on cost. | if tx_info is not None and tx_info.advertised_cost > 0:
fpc = tx_info.advertised_fee / tx_info.advertised_cost
# PriorityQueue returns lowest first so we invert
priority = -fpc
else:
# This peer didn't advertise cost and fee information for
# t... | @@ -123,25 +132,69 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
self._queue_length.release() # increment semaphore to indicate that we have a new item in the queue
+ def _clean... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | suggestion | 147 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
self._queu... | I think this deserves a comment explaining the idea behind this behavior. that we want to service transactions fairly between peers, based on cost. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if len(self._index_to_peer_map) > 0:
self._list_cursor %= len(self._index_to_peer_map)
else:
self._list_cursor = 0
async def pop(self) -> TransactionQueueEntry:
await self._queue_length.acquire()
if not self._high_priority_queue.empty():
return se... | I don't think you need the `_list_cursor` anymore, now that you look at every peer every time you pop. There's a risk it might not be very efficient though.
It might be OK for a first version. A heap might be a more efficient choice | """
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._peers_transactions_queues[peer_id].priority_queue.empty():
self._peers_transactions_queues.pop(peer_id, None)
if idx < self._list_cursor:
self._l... | @@ -123,25 +132,69 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
self._queue_length.release() # increment semaphore to indicate that we have a new item in the queue
+ def _clean... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | performance | 232 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: if len(self._index_to_peer_map) > 0:
self._list_cursor %= len(self._index_to_peer_map)
... | I don't think you need the `_list_cursor` anymore, now that you look at every peer every time you pop. There's a risk it might not be very efficient though.
It might be OK for a first version. A heap might be a more efficient choice | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
compare=False,
)
@dataclass
class TransactionQueue:
"""
This class replaces one queue by using a high priority queue for local transactions and separate queues for peers.
Local transactions are processed first.
Then the next transaction is taken from the next non-empty queue after the last... | I don't think you need `_index_to_peer_map` anymore, just like you don''t need `_list_cursor` anymore. You visit every peer every time you `pop()`, so there's no need to keep any cursor position in between calls to `pop()`. | compare=False,
)
@dataclass
class PeerTransactionsQueue:
# Peer's priority queue of the form (negative fee per cost, entry).
# We sort like this because PriorityQueue returns lowest first.
priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]] = field(default_factory=PriorityQueue)... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | suggestion | 223 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: compare=False,
)
@dataclass
class TransactionQueue:
"""
This class replaces one queue... | I don't think you need `_index_to_peer_map` anymore, just like you don''t need `_list_cursor` anymore. You visit every peer every time you `pop()`, so there's no need to keep any cursor position in between calls to `pop()`. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. | |
await self._queue_length.acquire()
if not self._high_priority_queue.empty():
return self._high_priority_queue.get()
while True:
# Map of peer ID to its top transaction's advertised cost
top_txs_advertised_costs: dict[bytes32, uint64] = {}
# Let's s... | I think this case warrants a comment. This is where we don't know the cost (or fee) for a transaction, so we want to assume a very high cost. I don't think we should search `peer_with_tx`, we should just assume it has a really high cost. This is just for backwards compatibility, right?
```suggestion
t... | self._list_cursor -= 1
else:
new_peer_map.append(peer_id)
self._index_to_peer_map = new_peer_map
if self._list_cursor >= len(self._index_to_peer_map):
self._list_cursor = 0
async def pop(self) -> TransactionQueueEntry:
await self._... | @@ -123,25 +132,69 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
self._queue_length.release() # increment semaphore to indicate that we have a new item in the queue
+ def _clean... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.857 | suggestion | 418 | 49 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: await self._queue_length.acquire()
if not self._high_priority_queue.empty():
re... | I think this case warrants a comment. This is where we don't know the cost (or fee) for a transaction, so we want to assume a very high cost. I don't think we should search `peer_with_tx`, we should just assume it has a really high cost. This is just for backwards compatibility, right?
```suggestion
t... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None = field(compare=False)
spend_name: bytes32
peer:... | I think `deficit` warrants a comment. the unit is `CLVM cost` for instance |
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None = field(compare=False)
spend_name: bytes32
peer:... | @@ -73,6 +73,12 @@ class TransactionQueueEntry:
)
+@dataclass
+class NormalPriorityQueue:
+ priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]]
+ deficit: int | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | nitpick | 74 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE:
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from ... | I think `deficit` warrants a comment. the unit is `CLVM cost` for instance | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
advertised_cost: uint64
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None = field(compare=False)
s... | I think this member also warrants a comment. I imagine that `float` is fee per cost, or is it cost per fee? Or maybe negative fee-per-cost. | advertised_cost: uint64
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None = field(compare=False)
s... | @@ -73,6 +73,12 @@ class TransactionQueueEntry:
)
+@dataclass
+class NormalPriorityQueue:
+ priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]] | chia/full_node/tx_processing_queue.py | 26 | Python | 0.5 | suggestion | 139 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: advertised_cost: uint64
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
... | I think this member also warrants a comment. I imagine that `float` is fee per cost, or is it cost per fee? Or maybe negative fee-per-cost. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
@dataclass
class TransactionQueue:
"""
This class replaces one queue by using a high priority queue for local transactions and separate queues for peers.
Local transactions are processed first.
Then the next transaction is taken from the next non-empty queue after the last processed queue. (round-robi... | why did you need to add deferred cleanup? | priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]] = field(default_factory=PriorityQueue)
# Peer's deficit in the context of deficit round robin algorithm. The unit
# here is in CLVM cost.
deficit: int = field(default=0, init=False)
@dataclass
class TransactionQueue:
"""
This c... | @@ -85,28 +91,33 @@ class TransactionQueue:
_list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
- _queue_dict: dict[bytes32, PriorityQueue[tuple[float, TransactionQueueEntry]]]
+ _normal_priority_queues: dict[bytes32, NormalPriorityQueue]
... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.071 | question | 41 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE:
@dataclass
class TransactionQueue:
"""
This class replaces one queue by using a high priority que... | why did you need to add deferred cleanup? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
_max_tx_clvm_cost: uint64
# Each 100 pops we do a cleanup of empty peer queues
_cleanup_counter: int
def __init__(self, peer_size_limit: int, log: logging.Logger, max_tx_clvm_cost: uint64) -> N... | If you add:
```
self._queue_length.release()
return
```
here, you can de-indent the else-block | _list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
_peers_transactions_queues: dict[bytes32, PeerTransactionsQueue]
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
# Fallback cost f... | @@ -85,28 +91,33 @@ class TransactionQueue:
_list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
- _queue_dict: dict[bytes32, PriorityQueue[tuple[float, TransactionQueueEntry]]]
+ _normal_priority_queues: dict[bytes32, NormalPriorityQueue]
... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | suggestion | 94 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: _high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logg... | If you add:
```
self._queue_length.release()
return
```
here, you can de-indent the else-block | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
_max_tx_clvm_cost: uint64
# Each 100 pops we do a cleanup of empty peer queues
_cleanup_counter: int
def __init__(self, peer_size_limit: int, log: logging.Logger, max_tx_clvm_cost: uint64) -> N... | if you invert this check and throw, the rest of the code can be de-indented | _list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
_peers_transactions_queues: dict[bytes32, PeerTransactionsQueue]
_high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logger
# Fallback cost f... | @@ -85,28 +91,33 @@ class TransactionQueue:
_list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
- _queue_dict: dict[bytes32, PriorityQueue[tuple[float, TransactionQueueEntry]]]
+ _normal_priority_queues: dict[bytes32, NormalPriorityQueue]
... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.214 | style | 75 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: _high_priority_queue: SimpleQueue[TransactionQueueEntry]
peer_size_limit: int
log: logging.Logg... | if you invert this check and throw, the rest of the code can be de-indented | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
self._index_to_peer_map.append(peer_id)
if self._normal_priority_queues[peer_id].priority_queue.qsize() < self.peer_size_limit:
tx_info = tx.peers_with_tx.get(peer_id)
if tx_info is not None and tx_info.advertised_cost > 0:
fpc = tx_info.ad... | was there no cleanup earlier? Was this a memory leak? | if peer_id is None or high_priority: # when it's local there is no peer_id.
self._high_priority_queue.put(tx)
self._queue_length.release()
return
peer_queue = self._peers_transactions_queues.get(peer_id)
if peer_queue is None:
peer_queue = PeerTra... | @@ -117,31 +128,73 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- self._queue_dict... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | performance | 53 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: self._index_to_peer_map.append(peer_id)
if self._normal_priority_queues[peer_id... | was there no cleanup earlier? Was this a memory leak? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# Peer's priority queue of the form (negative fee per cost, entry).
# We sort like this because PriorityQueue returns lowest first.
priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]]
# Peer's deficit in the context of deficit round robin algorithm. The unit
# here is in CLVM cost.
... | this new field is not obvious to me. Why do you need it?
I think it should be documented in the code. Can you require this to be initialized by a named parameter in the constructor? | # Peer's priority queue of the form (negative fee per cost, entry).
# We sort like this because PriorityQueue returns lowest first.
priority_queue: PriorityQueue[tuple[float, TransactionQueueEntry]] = field(default_factory=PriorityQueue)
# Peer's deficit in the context of deficit round robin algorithm. ... | @@ -85,19 +95,24 @@ class TransactionQueue:
_list_cursor: int # this is which index
_queue_length: asyncio.Semaphore
_index_to_peer_map: list[bytes32]
- _normal_priority_queues: dict[bytes32, PriorityQueue[tuple[float, TransactionQueueEntry]]]
+ _normal_priority_queues: dict[bytes32, NormalPriorit... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.429 | question | 182 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: # Peer's priority queue of the form (negative fee per cost, entry).
# We sort like this because Pri... | this new field is not obvious to me. Why do you need it?
I think it should be documented in the code. Can you require this to be initialized by a named parameter in the constructor? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
advertised_fee: uint64
advertised_cost: uint64
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None =... | this name seems a bit questionable to me. It's a `TransactionPriorityQueue` perhaps?
"normal" doesn't really help explain what it does. | advertised_fee: uint64
advertised_cost: uint64
@dataclass(frozen=True, order=True)
class TransactionQueueEntry:
"""
A transaction received from peer. This is put into a queue, and not yet in the mempool.
"""
transaction: SpendBundle = field(compare=False)
transaction_bytes: bytes | None =... | @@ -73,6 +73,16 @@ class TransactionQueueEntry:
)
+@dataclass
+class NormalPriorityQueue: | chia/full_node/tx_processing_queue.py | 26 | Python | 0.5 | suggestion | 136 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: advertised_fee: uint64
advertised_cost: uint64
@dataclass(frozen=True, order=True)
class Transact... | this name seems a bit questionable to me. It's a `TransactionPriorityQueue` perhaps?
"normal" doesn't really help explain what it does. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if self._normal_priority_queues[peer_id].priority_queue.qsize() >= self.peer_size_limit:
self.log.warning(f"Transaction queue full for peer {peer_id}")
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
tx_info = tx.peers_with_tx.get(peer_id)
if tx_i... | ```suggestion
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._normal_priority_queues[peer_id].priority_queue.empty():
self._normal_priority_queues.pop(peer_id, None)
if idx <= self._list_cursor:
self._list_cursor -= 1
... | self._index_to_peer_map.append(peer_id)
if self._peers_transactions_queues[peer_id].priority_queue.qsize() >= self.peer_size_limit:
self.log.warning(f"Transaction queue full for peer {peer_id}")
raise TransactionQueueFull(f"Transaction queue full for peer {peer_id}")
... | @@ -122,28 +137,70 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- peer_queue.put((priority, tx))
+ peer_que... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.786 | suggestion | 381 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: if self._normal_priority_queues[peer_id].priority_queue.qsize() >= self.peer_size_limit:
... | ```suggestion
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._normal_priority_queues[peer_id].priority_queue.empty():
self._normal_priority_queues.pop(peer_id, None)
if idx <= self._list_cursor:
self._list_cursor -= 1
... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
"""
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._peers_transactions_queues[peer_id].priority_queue.empty():
self._peers_transactions_queues.pop(peer_id, None)
if idx < self._list_cursor:
self._l... | you must have meant `break` or `return` here, no?
This will make it an infinite loop | """
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._peers_transactions_queues[peer_id].priority_queue.empty():
self._peers_transactions_queues.pop(peer_id, None)
if idx < self._list_cursor:
self._l... | @@ -122,28 +138,75 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- peer_queue.put((priority, tx))
+ peer_que... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.357 | bug | 84 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: """
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
... | you must have meant `break` or `return` here, no?
This will make it an infinite loop | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# we fallback to the highest cost.
if tx_info is not None:
# At this point we have no transactions with zero cost
assert tx_info.advertised_cost > 0
top_tx_advertised_cost = tx_info.advertised_cost
else:
... | this also seems risky, are you sure you can't get stuck spinning infinitely here? | if tx_info is not None:
# At this point we have no transactions with zero cost
assert tx_info.advertised_cost > 0
top_tx_advertised_cost = tx_info.advertised_cost
else:
top_tx_advertised_cost = self._max_tx_c... | @@ -122,28 +138,75 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- peer_queue.put((priority, tx))
+ peer_que... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.214 | question | 81 | 30 | 28 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: # we fallback to the highest cost.
if tx_info is not None:
... | this also seems risky, are you sure you can't get stuck spinning infinitely here? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
"""
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._peers_transactions_queues[peer_id].priority_queue.empty():
self._peers_transactions_queues.pop(peer_id, None)
if idx < self._list_cursor:
self._l... | ```suggestion
assert num_peers != 0
``` | """
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
if self._peers_transactions_queues[peer_id].priority_queue.empty():
self._peers_transactions_queues.pop(peer_id, None)
if idx < self._list_cursor:
self._l... | @@ -122,28 +138,75 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- peer_queue.put((priority, tx))
+ peer_que... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | suggestion | 51 | 51 | 51 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: """
new_peer_map = []
for idx, peer_id in enumerate(self._index_to_peer_map):
... | ```suggestion
assert num_peers != 0
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# we fallback to the highest cost.
if tx_info is not None:
# At this point we have no transactions with zero cost
assert tx_info.advertised_cost > 0
top_tx_advertised_cost = tx_info.advertised_cost
else:
... | ```suggestion
assert len(top_txs_advertised_costs) != 0
``` | if tx_info is not None:
# At this point we have no transactions with zero cost
assert tx_info.advertised_cost > 0
top_tx_advertised_cost = tx_info.advertised_cost
else:
top_tx_advertised_cost = self._max_tx_c... | @@ -122,28 +138,75 @@ def put(self, tx: TransactionQueueEntry, peer_id: bytes32 | None, high_priority:
# this transaction (it sent a `RespondTransaction` message
# instead of a `NewTransaction` one).
priority = float("inf")
- peer_queue.put((priority, tx))
+ peer_que... | chia/full_node/tx_processing_queue.py | 26 | Python | 0.571 | suggestion | 71 | 30 | 28 | false | CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop | 20,351 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/tx_processing_queue.py
PR Title: CHIA-3856 Use an adapted version of deficit round robin algorithm in TransactionQueue's pop
BEFORE CODE: # we fallback to the highest cost.
if tx_info is not None:
... | ```suggestion
assert len(top_txs_advertised_costs) != 0
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
"""
if TYPE_CHECKING:
_protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, tuple[FullBlock, BlockRecord]]
_height_to_hash: dict[uint32, bytes32]
def __init__(self, underlying: BlocksProtocol) -> None:
... | my model of errors is that an `assert` failing indicates a bug, but any other exception being raised is not necessarily a bug. Which makes me ask this question: I would expect this violation of precondition to be a bug, is it still? | """
if TYPE_CHECKING:
_protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, tuple[FullBlock, BlockRecord]]
_height_to_hash: dict[uint32, bytes32]
def __init__(self, underlying: BlocksProtocol) -> None:
... | @@ -41,7 +45,28 @@ def _get_block_record(self, header_hash: bytes32) -> BlockRecord | None:
return eb[1]
def add_extra_block(self, block: FullBlock, block_record: BlockRecord) -> None:
- assert block.header_hash == block_record.header_hash
+ if block.header_hash != block_record.header_hash... | chia/consensus/augmented_chain.py | 26 | Python | 0.714 | bug | 232 | 51 | 51 | false | Augmented usage fix | 20,361 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/augmented_chain.py
PR Title: Augmented usage fix
BEFORE CODE: """
if TYPE_CHECKING:
_protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, ... | my model of errors is that an `assert` failing indicates a bug, but any other exception being raised is not necessarily a bug. Which makes me ask this question: I would expect this violation of precondition to be a bug, is it still? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
_protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, tuple[FullBlock, BlockRecord]]
_height_to_hash: dict[uint32, bytes32]
def __init__(self, underlying: BlocksProtocol) -> None:
self._underlying = underl... | I don't think this is quite right. `_height_to_hash` will be empty if the underlying blockchain hasn't been augmented, right?
You may have to ask `self._blockchain` for the peak hash in that case.
I suspect if you fix this, you may not need to make the other changes to the test. | _protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, tuple[FullBlock, BlockRecord]]
_height_to_hash: dict[uint32, bytes32]
def __init__(self, underlying: BlocksProtocol) -> None:
self._underlying = underl... | @@ -41,7 +45,28 @@ def _get_block_record(self, header_hash: bytes32) -> BlockRecord | None:
return eb[1]
def add_extra_block(self, block: FullBlock, block_record: BlockRecord) -> None:
- assert block.header_hash == block_record.header_hash
+ if block.header_hash != block_record.header_hash... | chia/consensus/augmented_chain.py | 26 | Python | 0.643 | suggestion | 281 | 51 | 51 | false | Augmented usage fix | 20,361 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/augmented_chain.py
PR Title: Augmented usage fix
BEFORE CODE: _protocol_check: ClassVar[BlocksProtocol] = cast("AugmentedBlockchain", None)
_underlying: BlocksProtocol
_extra_blocks: dict[bytes32, tuple[FullBlock, BlockRecord]]
... | I don't think this is quite right. `_height_to_hash` will be empty if the underlying blockchain hasn't been augmented, right?
You may have to ask `self._blockchain` for the peak hash in that case.
I suspect if you fix this, you may not need to make the other changes to the test. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, cast
from chia_rs import BlockRecord, FullBlock
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32
from chia.consensus.blockchain_interface import BlocksProtocol
from chia.util.errors import Err
class Augmente... | my understanding is that this is raised when we encounter a bug. Do you think it would make sense to derive from `AssertionError` to make that clear? | from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, cast
from chia_rs import BlockRecord, FullBlock
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32
from chia.consensus.blockchain_interface import BlocksProtocol
from chia.util.errors import Err
class Augmente... | @@ -10,6 +10,10 @@
from chia.util.errors import Err
+class AugmentedBlockchainValidationError(Exception): | chia/consensus/augmented_chain.py | 13 | Python | 0.643 | bug | 149 | 38 | 38 | false | Augmented usage fix | 20,361 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/consensus/augmented_chain.py
PR Title: Augmented usage fix
BEFORE CODE: from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, cast
from chia_rs import BlockRecord, FullBlock
from chia_rs.sized_bytes import bytes32
from chia_rs.s... | my understanding is that this is raised when we encounter a bug. Do you think it would make sense to derive from `AssertionError` to make that clear? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return max(0, prefix_bits)
def calculate_plot_filter_input(plot_id: bytes32, challenge_hash: bytes32, signage_point: bytes32) -> bytes32:
return std_hash(plot_id + challenge_hash + signage_point)
def calculate_pos_challenge(plot_id: bytes32, challenge_hash: bytes32, signage_point: bytes32) -> bytes32:
r... | I think it would be good to comment here that this is must be set for v2 and must not be set for v1. In both places | if height >= constants.PLOT_FILTER_32_HEIGHT:
prefix_bits -= 4
elif height >= constants.PLOT_FILTER_64_HEIGHT:
prefix_bits -= 3
elif height >= constants.PLOT_FILTER_128_HEIGHT:
prefix_bits -= 2
elif height >= constants.HARD_FORK_HEIGHT:
prefix_bits -= 1
return max(0,... | @@ -243,26 +235,26 @@ def calculate_pos_challenge(plot_id: bytes32, challenge_hash: bytes32, signage_p
return std_hash(calculate_plot_filter_input(plot_id, challenge_hash, signage_point))
-def calculate_plot_id_v2(
- pool_contract_puzzle_hash: bytes32,
- plot_public_key: G1Element,
- strength: uint8,
... | chia/types/blockchain_format/proof_of_space.py | 26 | Python | 0.357 | suggestion | 115 | 46 | 51 | false | Explore bringing back v2 plot pool keys support | 20,388 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/types/blockchain_format/proof_of_space.py
PR Title: Explore bringing back v2 plot pool keys support
BEFORE CODE: return max(0, prefix_bits)
def calculate_plot_filter_input(plot_id: bytes32, challenge_hash: bytes32, signage_point: bytes32) -> bytes32... | I think it would be good to comment here that this is must be set for v2 and must not be set for v1. In both places | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
ProofOfSpaceCase(
id="Not passing the plot filter v2",
pos_challenge=b32("5706ae15c4a437399f464c64ef4f33c362d860ccd2945b76b3ebdb0505783817"),
plot_size=PlotParam.make_v2(32),
pool_contract_puzzle_hash=bytes32(b"1" * 32),
plot_public_key=g1(
"879526b4e7b616cfd64984... | Don't we already have a test that covers "did not pass the plot filter"?
The condition this test covers doesn't exist anymore, it's not obvious that we need to keep it | ProofOfSpaceCase(
id="Not passing the plot filter v2",
pos_challenge=b32("4cfaacbd2782db64d07cf490ca938534adb07dfbd2f92b0e479e2e5b196178db"),
plot_size=PlotParam.make_v2(32),
pool_contract_puzzle_hash=bytes32(b"1" * 32),
plot_public_key=g1(
"879526b4e7b616cfd64984... | @@ -147,11 +147,11 @@ def b32(key: str) -> bytes32:
),
ProofOfSpaceCase(
id="v2 plot with pool pk",
- pos_challenge=bytes32(b"1" * 32),
+ pos_challenge=b32("84252a4d185dd053495537ef2442ed059035ace6b6873945dd7b5e9f0b3cf645"),
plot_size=PlotParam.make_v2(2),
plot_public_... | chia/_tests/core/custom_types/test_proof_of_space.py | 26 | Python | 0.357 | suggestion | 167 | 51 | 51 | false | Explore bringing back v2 plot pool keys support | 20,388 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/_tests/core/custom_types/test_proof_of_space.py
PR Title: Explore bringing back v2 plot pool keys support
BEFORE CODE: ProofOfSpaceCase(
id="Not passing the plot filter v2",
pos_challenge=b32("5706ae15c4a437399f464c64ef4f33c362d860ccd2... | Don't we already have a test that covers "did not pass the plot filter"?
The condition this test covers doesn't exist anymore, it's not obvious that we need to keep it | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return ProofOfSpace(
challenge,
pool_public_key,
pool_contract_puzzle_hash,
plot_public_key,
uint8(k),
proof,
)
def get_plot_id(pos: ProofOfSpace) -> bytes32:
plot_param = pos.param()
if plot_param.strength_v2 is not None:
assert pos.pool_contrac... | I think it would be simpler to not rely on `isinstance`. something like this:
```
assert pos.pool_public_key is None or pos.pool_contract_puzzle_hash is None
# v2
if plot_param.strength_v2 is not None:
if pos.pool_public_key is None:
return calculate_plot_v2(pos.pool_contract_puzzle_hash, pos.plot_p... | return ProofOfSpace(
challenge,
pool_public_key,
pool_contract_puzzle_hash,
plot_public_key,
uint8(k),
proof,
)
def get_plot_id(pos: ProofOfSpace) -> bytes32:
plot_param = pos.param()
if pos.pool_public_key is None:
assert pos.pool_contract_puzzl... | @@ -44,15 +44,20 @@ def make_pos(
def get_plot_id(pos: ProofOfSpace) -> bytes32:
plot_param = pos.param()
- if plot_param.strength_v2 is not None:
- assert pos.pool_contract_puzzle_hash is not None
- return calculate_plot_id_v2(pos.pool_contract_puzzle_hash, pos.plot_public_key, uint8(plot_para... | chia/types/blockchain_format/proof_of_space.py | 26 | Python | 0.786 | suggestion | 667 | 51 | 51 | false | Explore bringing back v2 plot pool keys support | 20,388 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/types/blockchain_format/proof_of_space.py
PR Title: Explore bringing back v2 plot pool keys support
BEFORE CODE: return ProofOfSpace(
challenge,
pool_public_key,
pool_contract_puzzle_hash,
plot_public_key,
uint8... | I think it would be simpler to not rely on `isinstance`. something like this:
```
assert pos.pool_public_key is None or pos.pool_contract_puzzle_hash is None
# v2
if plot_param.strength_v2 is not None:
if pos.pool_public_key is None:
return calculate_plot_v2(pos.pool_contract_puzzle_hash, pos.plot_p... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# Returns the previous transaction block up to the blocks signage point
# we use this for block validation since when the block is farmed we do not know the latest transaction block
# since a new one might be infused by the time the block is infused
from __future__ import annotations
from chia_rs import ConsensusConst... | this seems very risky. We're about to introduce a soft fork that happens before `HARD_FORK2_HEIGHT`. Currently `get_flags_for_height_and_constants()` is the single place where forks are defined. Returning 0 here is a ticking time bomb.
I think it might be reasonable to assume that it's hard fork 2 that starts caring ab... | # Returns the previous transaction block up to the blocks signage point
# we use this for block validation since when the block is farmed we do not know the latest transaction block
# since a new one might be infused by the time the block is infused
from __future__ import annotations
from chia_rs import ConsensusConst... | @@ -0,0 +1,44 @@
+# Returns the previous transaction block up to the blocks signage point
+# we use this for block validation since when the block is farmed we do not know the latest transaction block
+# since a new one might be infused by the time the block is infused
+from __future__ import annotations
+
+from chia_r... | chia/full_node/hard_fork_utils.py | 18 | Python | 0.643 | suggestion | 478 | 43 | 43 | false | get_flags, fix pre_sp_tx_block, test CHIA-3861 | 20,400 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/full_node/hard_fork_utils.py
PR Title: get_flags, fix pre_sp_tx_block, test CHIA-3861
BEFORE CODE: # Returns the previous transaction block up to the blocks signage point
# we use this for block validation since when the block is farmed we do not know th... | this seems very risky. We're about to introduce a soft fork that happens before `HARD_FORK2_HEIGHT`. Currently `get_flags_for_height_and_constants()` is the single place where forks are defined. Returning 0 here is a ticking time bomb.
I think it might be reasonable to assume that it's hard fork 2 that starts caring ab... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
first_peak = b.get_peak()
fork_info2 = None
# Create one AugmentedBlockchain instance and reuse it across fork chain validations
aug_chain: AugmentedBlockchain | None = AugmentedBlockchain(b)
for reorg_block in reorg_blocks:
if (reorg_block.height % 100) == 0:
... | it makes me a bit nervous to have this be conditional. If something is changed with the chains, this test may not trigger a reorg anymore, but it will still pass. At least that's what it looks like.
I'm thinking that maybe it would be possible to fix this by adjusting `chain_1_weight` instead, to depend on which chain... | b.clean_block_records()
first_peak = b.get_peak()
fork_info2 = None
# Create one AugmentedBlockchain instance and reuse it across fork chain validations
aug_chain: AugmentedBlockchain | None = AugmentedBlockchain(b)
for reorg_block in reorg_blocks:
if (reorg... | @@ -3480,22 +3472,23 @@ async def test_long_reorg(
await _validate_and_add_block(
b, reorg_block, expected_result=AddBlockResult.ALREADY_HAVE_BLOCK, augmented_blockchain=aug_chain
)
- elif reorg_block.weight <= chain_1_weight:
+ else:
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.643 | suggestion | 333 | 51 | 51 | false | fix tests | 20,457 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/_tests/blockchain/test_blockchain.py
PR Title: fix tests
BEFORE CODE:
first_peak = b.get_peak()
fork_info2 = None
# Create one AugmentedBlockchain instance and reuse it across fork chain validations
aug_chain: AugmentedBlo... | it makes me a bit nervous to have this be conditional. If something is changed with the chains, this test may not trigger a reorg anymore, but it will still pass. At least that's what it looks like.
I'm thinking that maybe it would be possible to fix this by adjusting `chain_1_weight` instead, to depend on which chain... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
blocks_reorg_chain = bt.get_consecutive_blocks(
4, blocks_reorg_chain, seed=b"2", block_refs=[uint32(5), uint32(11)], transaction_data=spend_bundle2
)
blocks_reorg_chain = bt.get_consecutive_blocks(4, blocks_reorg_chain, seed=b"2")
fork_info = ForkInfo(-1, -1, b.constants.GENESIS_CHALLENGE)
... | the reason this check is here is to make sure the test actually triggers a reorg. As far as I can tell, with this change, we wouldn't ensure that happens.
Would it not be possible to make the check against `19` above instead depend on which chain we're using, but still with a hard coded height. | blocks_reorg_chain,
seed=b"2",
farmer_reward_puzzle_hash=coinbase_puzzlehash,
pool_reward_puzzle_hash=receiver_puzzlehash,
transaction_data=spend_bundle,
guarantee_transaction_block=True,
)
spend_bundle2 = wallet_a.generate_signed_transaction(uint64(1_000), recei... | @@ -3847,9 +3833,11 @@ async def test_reorg_new_ref(empty_blockchain: Blockchain, bt: BlockTools) -> No
# same height as peak decide by iterations
peak = b.get_peak()
assert peak is not None
- # same height as peak should be ADDED_AS_ORPHAN if block.total_iters >= peak... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.643 | suggestion | 296 | 51 | 51 | false | fix tests | 20,457 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz | Review this pull request change.
Language: Python
File: chia/_tests/blockchain/test_blockchain.py
PR Title: fix tests
BEFORE CODE: blocks_reorg_chain = bt.get_consecutive_blocks(
4, blocks_reorg_chain, seed=b"2", block_refs=[uint32(5), uint32(11)], transaction_data=spend_bundle2
)
blocks_reorg_c... | the reason this check is here is to make sure the test actually triggers a reorg. As far as I can tell, with this change, we wouldn't ensure that happens.
Would it not be possible to make the check against `19` above instead depend on which chain we're using, but still with a hard coded height. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
buf = skip_optional(buf, skip_g1_element) # pool_public_key
buf = skip_optional(buf, skip_bytes32) # pool_contract_puzzle_hash
buf = skip_g1_element(buf) # plot_public_key
buf = skip_uint8(buf) # size
return skip_bytes(buf) # proof
def skip_reward_chain_block(buf: memoryview) -> memoryview:
... | i think we should wrap this in a util call that outputs has_vdf_info and has_mmr_root, and have some unit testing for it | buf = skip_optional(buf, skip_g1_element) # pool_public_key
buf = skip_optional(buf, skip_bytes32) # pool_contract_puzzle_hash
buf = skip_g1_element(buf) # plot_public_key
buf = skip_uint8(buf) # size
return skip_bytes(buf) # proof
def skip_reward_chain_block(buf: memoryview) -> memoryview:
... | @@ -139,7 +139,15 @@ def skip_reward_chain_block(buf: memoryview) -> memoryview:
buf = skip_optional(buf, skip_vdf_info) # reward_chain_sp_vdf
buf = skip_g2_element(buf) # reward_chain_sp_signature
buf = skip_vdf_info(buf) # reward_chain_ip_vdf
- buf = skip_optional(buf, skip_vdf_info) # infused_c... | chia/full_node/full_block_utils.py | 26 | Python | 0.429 | nitpick | 120 | 51 | 51 | false | update the fast FullBlock parser | 20,458 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/full_block_utils.py
PR Title: update the fast FullBlock parser
BEFORE CODE: buf = skip_optional(buf, skip_g1_element) # pool_public_key
buf = skip_optional(buf, skip_bytes32) # pool_contract_puzzle_hash
buf = skip_g1_element(buf) ... | i think we should wrap this in a util call that outputs has_vdf_info and has_mmr_root, and have some unit testing for it | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
return MempoolInclusionStatus.SUCCESS, None
if self.mempool_manager.peak is None:
return MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_INITIALIZED
info = await self.mempool_manager.add_spend_bundle(
transaction, cost_result, spend_name, self.mempo... | It seems uneccessarily complex to compute the diff and check it against a set.
I'm not sure which way the older clients report, do they include the cost of the quote or do the new ones? We know it's always one or the other, so we just need to check two cases.
```suggestion
if entry.advertised_fee == mem... | return MempoolInclusionStatus.SUCCESS, None
if self.mempool_manager.peak is None:
return MempoolInclusionStatus.FAILED, Err.MEMPOOL_NOT_INITIALIZED
info = await self.mempool_manager.add_spend_bundle(
transaction, cost_result, spend_name, self.mempo... | @@ -2818,7 +2819,12 @@ async def add_transaction(
# Now that we validated this transaction, check what fees and
# costs the peers have advertised for it.
for peer_id, entry in peers_with_tx.items():
- if entry.advertised_fee == mempool_item.fee and entry.advertised_... | chia/full_node/full_node.py | 26 | Python | 0.786 | suggestion | 495 | 51 | 51 | false | CHIA-3883 Tolerate quote related cost mismatch for older nodes | 20,460 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node.py
PR Title: CHIA-3883 Tolerate quote related cost mismatch for older nodes
BEFORE CODE: return MempoolInclusionStatus.SUCCESS, None
if self.mempool_manager.peak is None:
return MempoolInclus... | It seems uneccessarily complex to compute the diff and check it against a set.
I'm not sure which way the older clients report, do they include the cost of the quote or do the new ones? We know it's always one or the other, so we just need to check two cases.
```suggestion
if entry.advertised_fee == mem... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.low):
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.SUCCESS, None
if self.memp... | I think we should be specific.
```suggestion
# The 2.4.3 full node, and earlier, computed the cost slightly differently.
# They did not include byte-cost or execution cost of the quote for the puzzle.
``` |
async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.low):
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.SUCCESS, None
if self.memp... | @@ -2818,7 +2819,12 @@ async def add_transaction(
# Now that we validated this transaction, check what fees and
# costs the peers have advertised for it.
for peer_id, entry in peers_with_tx.items():
- if entry.advertised_fee == mempool_item.fee and entry.advertised_... | chia/full_node/full_node.py | 26 | Python | 0.857 | suggestion | 236 | 51 | 51 | false | CHIA-3883 Tolerate quote related cost mismatch for older nodes | 20,460 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node.py
PR Title: CHIA-3883 Tolerate quote related cost mismatch for older nodes
BEFORE CODE:
async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.low):
if self.mempool_manager.get_spendbun... | I think we should be specific.
```suggestion
# The 2.4.3 full node, and earlier, computed the cost slightly differently.
# They did not include byte-cost or execution cost of the quote for the puzzle.
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
A peer notifies us of a new transaction.
Requests a full transaction if we haven't seen it previously, and if the fees are enough.
"""
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode():
return None
if not (await self.full_node.synced()):
... | I think the same treatment should be made here. Just check the exact matches with the two cost values we accept, and be precise in the comment of why we need to do it (including version number). | A peer notifies us of a new transaction.
Requests a full transaction if we haven't seen it previously, and if the fees are enough.
"""
# Ignore if syncing
if self.full_node.sync_store.get_sync_mode():
return None
if not (await self.full_node.synced()):
... | @@ -220,11 +221,16 @@ async def new_transaction(
# If already seen, the cost and fee must match, otherwise ban the peer
mempool_item = self.full_node.mempool_manager.get_mempool_item(transaction.transaction_id, include_pending=True)
if mempool_item is not None:
- if mempool_item.co... | chia/full_node/full_node_api.py | 26 | Python | 0.429 | suggestion | 194 | 51 | 51 | false | CHIA-3883 Tolerate quote related cost mismatch for older nodes | 20,460 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3883 Tolerate quote related cost mismatch for older nodes
BEFORE CODE: A peer notifies us of a new transaction.
Requests a full transaction if we haven't seen it previously, and if the fees are eno... | I think the same treatment should be made here. Just check the exact matches with the two cost values we accept, and be precise in the comment of why we need to do it (including version number). | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
current_map = self.full_node.full_node_store.peers_with_tx.get(transaction.transaction_id)
if current_map is None:
self.full_node.full_node_store.peers_with_tx[transaction.transaction_id] = {
peer.peer_node_id: PeerWithTx(
... | this `abs()` looks suspicious. We know that we never include the quote cost, so `prev` should either be an exact match or exactly the quote cost higher, no? | )
await peer.close(CONSENSUS_ERROR_BAN_SECONDS)
return None
if self.full_node.mempool_manager.is_fee_enough(transaction.fees, transaction.cost):
# If there's current pending request just add this peer to the set of peers that have this tx
if t... | @@ -244,11 +251,19 @@ async def new_transaction(
return None
prev = current_map.get(peer.peer_node_id)
if prev is not None:
- if prev.advertised_fee != transaction.fees or prev.advertised_cost != transaction.cost:
+ # Older nod... | chia/full_node/full_node_api.py | 26 | Python | 0.571 | question | 156 | 51 | 51 | false | CHIA-3883 Tolerate quote related cost mismatch for older nodes | 20,460 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3883 Tolerate quote related cost mismatch for older nodes
BEFORE CODE: current_map = self.full_node.full_node_store.peers_with_tx.get(transaction.transaction_id)
if current_map is N... | this `abs()` looks suspicious. We know that we never include the quote cost, so `prev` should either be an exact match or exactly the quote cost higher, no? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
):
return None
height_to_hash = self.full_node.blockchain.height_to_hash
header_hashes: list[bytes32] = []
for i in range(request.start_height, request.end_height + 1):
header_hash: bytes32 | None = height_to_hash(uint32(i))
if header_hash is None:
... | this would trigger the assert for non transaction blocks, wouldn't it? | ):
return None
height_to_hash = self.full_node.blockchain.height_to_hash
header_hashes: list[bytes32] = []
for i in range(request.start_height, request.end_height + 1):
header_hash: bytes32 | None = height_to_hash(uint32(i))
if header_hash is None:
... | chia/full_node/full_node_api.py | 26 | Python | 0.214 | question | 70 | 51 | 51 | false | CHIA-3887 Skip fetching additions and removals for non transaction blocks in FullNodeAPI's request_header_blocks | 20,470 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: CHIA-3887 Skip fetching additions and removals for non transaction blocks in FullNodeAPI's request_header_blocks
BEFORE CODE: ):
return None
height_to_hash = self.full_node.blockchain.height... | this would trigger the assert for non transaction blocks, wouldn't it? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. | |
name = self._next_savepoint()
# The SAVEPOINT creation is inside the try block to prevent orphan
# SAVEPOINTs. An orphan SAVEPOINT (created but never released) causes
# all subsequent SAVEPOINTs to nest inside it, making every RELEASE a
# merge instead of a commit — trapping data... | should be catching `aiosqlite.DatabaseError`, to not suppress other failures that should be reported to callers? | name = self._next_savepoint()
# The SAVEPOINT creation is inside the try block to prevent orphan
# SAVEPOINTs. An orphan SAVEPOINT (created but never released) causes
# all subsequent SAVEPOINTs to nest inside it, making every RELEASE a
# merge instead of a commit — trapping data... | @@ -275,16 +317,44 @@ def _next_savepoint(self) -> str:
@contextlib.asynccontextmanager
async def _savepoint_ctx(self) -> AsyncIterator[None]:
name = self._next_savepoint()
- await self._write_connection.execute(f"SAVEPOINT {name}")
+ # The SAVEPOINT creation is inside the try block to ... | chia/util/db_wrapper.py | 26 | Python | 0.714 | bug | 112 | 51 | 51 | false | [CHIA-3897] Prevent dangling SAVEPOINTs by shielding against cancellation | 20,503 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | cmmarslender | Review this pull request change.
Language: Python
File: chia/util/db_wrapper.py
PR Title: [CHIA-3897] Prevent dangling SAVEPOINTs by shielding against cancellation
BEFORE CODE: name = self._next_savepoint()
# The SAVEPOINT creation is inside the try block to prevent orphan
# SAVEPOINTs. An o... | should be catching `aiosqlite.DatabaseError`, to not suppress other failures that should be reported to callers? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
# SAVEPOINTs. An orphan SAVEPOINT (created but never released) causes
# all subsequent SAVEPOINTs to nest inside it, making every RELEASE a
# merge instead of a commit — trapping data in an uncommitted
# transaction invisible to reader connections.
#
# aiosqlite queues SQ... | it might be worth pointing out that there is still a failure case we can't handle, when the call to `ROLLBACK TO` is itself cancelled. The only thing we can do is to run it multiple times and hope for the best. Same thing with `RELEASE` | # SAVEPOINTs. An orphan SAVEPOINT (created but never released) causes
# all subsequent SAVEPOINTs to nest inside it, making every RELEASE a
# merge instead of a commit — trapping data in an uncommitted
# transaction invisible to reader connections.
#
# aiosqlite queues SQ... | @@ -275,16 +317,44 @@ def _next_savepoint(self) -> str:
@contextlib.asynccontextmanager
async def _savepoint_ctx(self) -> AsyncIterator[None]:
name = self._next_savepoint()
- await self._write_connection.execute(f"SAVEPOINT {name}")
+ # The SAVEPOINT creation is inside the try block to ... | chia/util/db_wrapper.py | 26 | Python | 0.714 | bug | 236 | 51 | 51 | false | [CHIA-3897] Prevent dangling SAVEPOINTs by shielding against cancellation | 20,503 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | cmmarslender | Review this pull request change.
Language: Python
File: chia/util/db_wrapper.py
PR Title: [CHIA-3897] Prevent dangling SAVEPOINTs by shielding against cancellation
BEFORE CODE: # SAVEPOINTs. An orphan SAVEPOINT (created but never released) causes
# all subsequent SAVEPOINTs to nest inside it, making... | it might be worth pointing out that there is still a failure case we can't handle, when the call to `ROLLBACK TO` is itself cancelled. The only thing we can do is to run it multiple times and hope for the best. Same thing with `RELEASE` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
monkeypatch: pytest.MonkeyPatch,
) -> None:
nodes, _, _ = setup_two_nodes_fixture
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
# Use the server_2 ssl information to connect to server_1, and send a huge message
timeout = ClientTimeout(tota... | AFAICS you no longer make sure these peers get banned. Is that intentional? | nodes, _, _ = setup_two_nodes_fixture
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
# Use the server_2 ssl information to connect to server_1, and send a huge message
timeout = ClientTimeout(total=10)
session = ClientSession(timeout=timeout)
... | @@ -104,33 +135,13 @@ async def test_bad_handshake_and_ban(
self,
setup_two_nodes_fixture: tuple[list[FullNodeSimulator], list[tuple[WalletNode, ChiaServer]], BlockTools],
self_hostname: str,
- monkeypatch: pytest.MonkeyPatch,
) -> None:
nodes, _, _ = setup_two_nodes_fixt... | chia/_tests/core/server/test_dos.py | 26 | Python | 0.214 | question | 75 | 51 | 51 | false | refactor connection handshake | 20,512 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/core/server/test_dos.py
PR Title: refactor connection handshake
BEFORE CODE: monkeypatch: pytest.MonkeyPatch,
) -> None:
nodes, _, _ = setup_two_nodes_fixture
server_1 = nodes[0].full_node.server
server_2 = nodes... | AFAICS you no longer make sure these peers get banned. Is that intentional? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
),
)
await self._send_message(outbound_handshake)
try:
message = await self._read_one_message()
except Exception:
raise ProtocolError(Err.INVALID_HANDSHAKE)
if message is None:
raise ProtocolError(Err.INVALID_HANDSHAKE... | We can now combine these conditions:
```suggestion
if (
self.is_outbound
and local_type in {NodeType.FARMER, NodeType.HARVESTER}
and inbound_handshake.protocol_version != protocol_version[local_type]
):
``` | ),
)
await self._send_message(outbound_handshake)
try:
message = await self._read_one_message()
except Exception:
raise ProtocolError(Err.INVALID_HANDSHAKE)
if message is None:
raise ProtocolError(Err.INVALID_HANDSHAKE... | @@ -217,23 +220,29 @@ async def perform_handshake(
),
)
await self._send_message(outbound_handshake)
- inbound_handshake_msg = await self._read_one_message()
- if inbound_handshake_msg is None:
- raise ProtocolError(Err.INVALID_HANDSHAKE)
-... | chia/server/ws_connection.py | 26 | Python | 0.929 | suggestion | 259 | 51 | 51 | false | refactor connection handshake | 20,512 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/server/ws_connection.py
PR Title: refactor connection handshake
BEFORE CODE: ),
)
await self._send_message(outbound_handshake)
try:
message = await self._read_one_message()
except Except... | We can now combine these conditions:
```suggestion
if (
self.is_outbound
and local_type in {NodeType.FARMER, NodeType.HARVESTER}
and inbound_handshake.protocol_version != protocol_version[local_type]
):
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
await self.full_node.new_compact_vdf(request, peer)
finally:
self.full_node.compact_vdf_requests.remove(name)
except LimitedSemaphoreFullError:
self.log.debug("Ignoring NewCompactVDF, limited semaphore full: %s %s", peer.get_peer_logging(), req... | While we wont actually ban localhost or an exempt peer IP (based on the exemption list in the config), it would still potentially be useful to let exempt peers or localhost to send these unsolicited (its useful to me, at least right now to do so). I suppose I can always edit the full node if I need to do it again, but ... | await self.full_node.new_compact_vdf(request, peer)
finally:
self.full_node.compact_vdf_requests.remove(name)
except LimitedSemaphoreFullError:
self.log.debug("Ignoring NewCompactVDF, limited semaphore full: %s %s", peer.get_peer_logging(), req... | @@ -1655,6 +1655,15 @@ async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVD
@metadata.request(peer_required=True)
async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: WSChiaConnection) -> None:
+ request_key = bytes(
+ full_no... | chia/full_node/full_node_api.py | 26 | Python | 0.5 | question | 392 | 51 | 51 | false | reject unsolicited RespondCompactVDF messages | 20,531 | Chia-Network/chia-blockchain | 10,822 | Python | cmmarslender | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: reject unsolicited RespondCompactVDF messages
BEFORE CODE: await self.full_node.new_compact_vdf(request, peer)
finally:
self.full_node.compact_vdf_requests.remove... | While we wont actually ban localhost or an exempt peer IP (based on the exemption list in the config), it would still potentially be useful to let exempt peers or localhost to send these unsolicited (its useful to me, at least right now to do so). I suppose I can always edit the full node if I need to do it again, but ... | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: WSChiaConnection) -> None:
peak = self.blockchain.get_peak()
if peak is None or peak.height - request.height < 5:
self.log.info(f"Ignoring new_compact_vdf, height {request.height} too recent.")
... | We're computing the hash of peer_request a second time here (first time is in line 3153 above). |
async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: WSChiaConnection) -> None:
peak = self.blockchain.get_peak()
if peak is None or peak.height - request.height < 5:
self.log.info(f"Ignoring new_compact_vdf, height {request.height} too recent.")
... | @@ -3150,8 +3150,13 @@ async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer:
peer_request = full_node_protocol.RequestCompactVDF(
request.height, request.header_hash, request.field_vdf, request.vdf_info
)
+ peer.pending_compact_vdfs.put(pe... | chia/full_node/full_node.py | 26 | Python | 0.214 | suggestion | 95 | 51 | 51 | false | reject unsolicited RespondCompactVDF messages | 20,531 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/full_node.py
PR Title: reject unsolicited RespondCompactVDF messages
BEFORE CODE:
async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: WSChiaConnection) -> None:
peak = self.blockchain.get_peak()
... | We're computing the hash of peer_request a second time here (first time is in line 3153 above). | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
try:
async with self.full_node.compact_vdf_sem.acquire():
try:
await self.full_node.new_compact_vdf(request, peer)
finally:
self.full_node.compact_vdf_requests.remove(name)
except LimitedSemaphoreFullError:
s... | `is_trusted` checks for `is_localhost` already IIRC. | async with self.full_node.compact_vdf_sem.acquire():
try:
await self.full_node.new_compact_vdf(request, peer)
finally:
self.full_node.compact_vdf_requests.remove(name)
except LimitedSemaphoreFullError:
self.log.debug... | @@ -1655,6 +1656,16 @@ async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVD
@metadata.request(peer_required=True)
async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: WSChiaConnection) -> None:
+ request_key = full_node_protocol.RequestC... | chia/full_node/full_node_api.py | 26 | Python | 0.357 | suggestion | 52 | 51 | 51 | false | reject unsolicited RespondCompactVDF messages | 20,531 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/full_node/full_node_api.py
PR Title: reject unsolicited RespondCompactVDF messages
BEFORE CODE: try:
async with self.full_node.compact_vdf_sem.acquire():
try:
await self.full_node.new_compact_vdf(req... | `is_trusted` checks for `is_localhost` already IIRC. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
if key not in self.cache:
return None
else:
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: K, value: V) -> None:
if self.capacity > 0:
self.cache[key] = value
self.cache.move_to_end(key)
if len(se... | We may want to signal these as "private" (well, python..) fields by having them start with underscore? | if key not in self.cache:
return None
else:
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: K, value: V) -> None:
if self.capacity > 0:
self.cache[key] = value
self.cache.move_to_end(key)
if len(se... | @@ -33,3 +33,30 @@ def remove(self, key: K) -> None:
def get_capacity(self) -> int:
return self.capacity
+
+
+class LRUSet(Generic[K]):
+ """A bounded set that preserves insertion order and evicts the oldest entry when full."""
+
+ def __init__(self, capacity: int) -> None:
+ self.capacity ... | chia/util/lru_cache.py | 26 | Python | 0.357 | question | 102 | 46 | 46 | false | reject unsolicited RespondCompactVDF messages | 20,531 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/util/lru_cache.py
PR Title: reject unsolicited RespondCompactVDF messages
BEFORE CODE: if key not in self.cache:
return None
else:
self.cache.move_to_end(key)
return self.cache[key]
def put(self, ke... | We may want to signal these as "private" (well, python..) fields by having them start with underscore? | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
last_block: BlockRecord | None = full_node_api.full_node.blockchain.get_peak()
assert last_block is not None
# Invalid height (with header_hash specified)
res = await full_node_api.request_additions(RequestAdditions(uint32(100), last_block.header_hash, [ph]))
assert res is not None
reject = Rej... | ```suggestion
too_many = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST + 1)]
``` | last_block: BlockRecord | None = full_node_api.full_node.blockchain.get_peak()
assert last_block is not None
# Invalid height (with header_hash specified)
res = await full_node_api.request_additions(RequestAdditions(uint32(100), last_block.header_hash, [ph]))
assert res is not None
reject = Rej... | @@ -635,13 +638,41 @@ async def test_request_additions_errors(simulator_and_wallet: OldSimulatorsAndWa
last_block: BlockRecord | None = full_node_api.full_node.blockchain.get_peak()
assert last_block is not None
- # Invalid height
- with pytest.raises(ValueError):
- await full_node_api.request_... | chia/_tests/wallet/sync/test_wallet_sync.py | 26 | Python | 0.571 | suggestion | 99 | 51 | 51 | false | [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception | 20,555 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/wallet/sync/test_wallet_sync.py
PR Title: [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception
BEFORE CODE: last_block: BlockRecord | None = full_node_api.full_node.blockchain.get_peak()
assert last_block is ... | ```suggestion
too_many = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST + 1)]
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
assert reject.header_hash == last_block.header_hash
# Invalid height (no header_hash, returns zeros)
res = await full_node_api.request_additions(RequestAdditions(uint32(100), None, [ph]))
assert res is not None
reject = RejectAdditionsRequest.from_bytes(res.data)
assert reject.height == 100
... | ```suggestion
at_limit = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST)]
``` | assert reject.header_hash == last_block.header_hash
# Invalid height (no header_hash, returns zeros)
res = await full_node_api.request_additions(RequestAdditions(uint32(100), None, [ph]))
assert res is not None
reject = RejectAdditionsRequest.from_bytes(res.data)
assert reject.height == 100
... | @@ -635,13 +638,41 @@ async def test_request_additions_errors(simulator_and_wallet: OldSimulatorsAndWa
last_block: BlockRecord | None = full_node_api.full_node.blockchain.get_peak()
assert last_block is not None
- # Invalid height
- with pytest.raises(ValueError):
- await full_node_api.request_... | chia/_tests/wallet/sync/test_wallet_sync.py | 26 | Python | 0.571 | suggestion | 95 | 51 | 51 | false | [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception | 20,555 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/wallet/sync/test_wallet_sync.py
PR Title: [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception
BEFORE CODE: assert reject.header_hash == last_block.header_hash
# Invalid height (no header_hash, returns zeros... | ```suggestion
at_limit = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST)]
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
for coin in coin_list:
assert coin.puzzle_hash == p
# The other ones are included
assert len(coin_list) == 2
# None for puzzle hashes returns all coins and no proofs
res3 = await full_node_api.request_additions(RequestAdditions(last_block.height, last_block.h... | We can write `test_request_additions_errors` and `test_request_removals_too_many_coin_names` to become significantly simpler/faster using something like `one_node_one_block`. | for coin in coin_list:
assert coin.puzzle_hash == p
# The other ones are included
assert len(coin_list) == 2
# None for puzzle hashes returns all coins and no proofs
res3 = await full_node_api.request_additions(RequestAdditions(last_block.height, last_block.h... | @@ -763,6 +794,35 @@ async def test_request_additions_success(simulator_and_wallet: OldSimulatorsAndW
assert len(response.coins) == 0
+@pytest.mark.anyio
+async def test_request_removals_too_many_coin_names( | chia/_tests/wallet/sync/test_wallet_sync.py | 26 | Python | 0.643 | suggestion | 174 | 51 | 51 | false | [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception | 20,555 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/wallet/sync/test_wallet_sync.py
PR Title: [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception
BEFORE CODE: for coin in coin_list:
assert coin.puzzle_hash == p
# The other ones... | We can write `test_request_additions_errors` and `test_request_removals_too_many_coin_names` to become significantly simpler/faster using something like `one_node_one_block`. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
assert response.proofs == []
assert len(response.coins) == 0
@pytest.mark.anyio
async def test_request_removals_too_many_coin_names(
simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str
) -> None:
full_nodes, wallets, _ = simulator_and_wallet
wallet_node, wallet_server = wallets[0]
... | ```suggestion
too_many = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST + 1)]
``` | assert response.proofs == []
assert len(response.coins) == 0
@pytest.mark.anyio
async def test_request_removals_too_many_coin_names(
simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str
) -> None:
full_nodes, wallets, _ = simulator_and_wallet
wallet_node, wallet_server = wallets[0]
... | @@ -763,6 +794,35 @@ async def test_request_additions_success(simulator_and_wallet: OldSimulatorsAndW
assert len(response.coins) == 0
+@pytest.mark.anyio
+async def test_request_removals_too_many_coin_names(
+ simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str
+) -> None:
+ full_nodes, wal... | chia/_tests/wallet/sync/test_wallet_sync.py | 26 | Python | 0.571 | suggestion | 99 | 51 | 51 | false | [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception | 20,555 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn | Review this pull request change.
Language: Python
File: chia/_tests/wallet/sync/test_wallet_sync.py
PR Title: [CHIA-3935] return RejectAdditionsRequest to wallets instead of raising an exception
BEFORE CODE: assert response.proofs == []
assert len(response.coins) == 0
@pytest.mark.anyio
async def test_req... | ```suggestion
too_many = [bytes32.random() for _ in range(MAX_COIN_HASHES_PER_REQUEST + 1)]
``` | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
from __future__ import annotations
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ProtocolMessageTypes
ProtocolMessageTypeToNodeType: dict[ProtocolMessageTypes, set[NodeType]] = {
# Shared protocol (all services)
ProtocolMessageTypes.handshake: set(NodeT... | I think this needs a comment describing what it's for | from __future__ import annotations
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ProtocolMessageTypes
# Map of protocol message type to the node types that send it. We use this to
# validate which nodes are allowed to send which messages so that all api calls
#... | @@ -0,0 +1,126 @@
+from __future__ import annotations
+
+from chia.protocols.outbound_message import NodeType
+from chia.protocols.protocol_message_types import ProtocolMessageTypes
+
+ProtocolMessageTypeToNodeType: dict[ProtocolMessageTypes, set[NodeType]] = { | chia/protocols/protocol_message_type_to_node_type.py | 9 | Python | 0.214 | suggestion | 53 | 34 | 34 | false | CHIA-3905 Improve nodes message typechecking | 20,556 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/protocols/protocol_message_type_to_node_type.py
PR Title: CHIA-3905 Improve nodes message typechecking
BEFORE CODE: from __future__ import annotations
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ... | I think this needs a comment describing what it's for | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ProtocolMessageTypes
ProtocolMessageTypeToNodeType: dict[ProtocolMessageTypes, set[NodeType]] = {
# Shared protocol (all services)
ProtocolMessageTypes.handshake: set(NodeType),
# Harvester protocol (har... | I don't think a farmer ever sends this to the full node. So, should `FARMER` really be in this set?
Isn't this indicating which node type is allowed to send a specific message? It looks like most entries here have the *receiving* node type as well. it doesn't look right. |
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ProtocolMessageTypes
# Map of protocol message type to the node types that send it. We use this to
# validate which nodes are allowed to send which messages so that all api calls
# are type checked.
ProtocolMessageT... | @@ -0,0 +1,126 @@
+from __future__ import annotations
+
+from chia.protocols.outbound_message import NodeType
+from chia.protocols.protocol_message_types import ProtocolMessageTypes
+
+ProtocolMessageTypeToNodeType: dict[ProtocolMessageTypes, set[NodeType]] = {
+ # Shared protocol (all services)
+ ProtocolMessage... | chia/protocols/protocol_message_type_to_node_type.py | 26 | Python | 0.786 | suggestion | 272 | 51 | 51 | false | CHIA-3905 Improve nodes message typechecking | 20,556 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi | Review this pull request change.
Language: Python
File: chia/protocols/protocol_message_type_to_node_type.py
PR Title: CHIA-3905 Improve nodes message typechecking
BEFORE CODE:
from chia.protocols.outbound_message import NodeType
from chia.protocols.protocol_message_types import ProtocolMessageTypes
ProtocolMessa... | I don't think a farmer ever sends this to the full node. So, should `FARMER` really be in this set?
Isn't this indicating which node type is allowed to send a specific message? It looks like most entries here have the *receiving* node type as well. it doesn't look right. | You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.