before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
log.info(
"Not skipping peak, don't have. Maybe we are not the fastest timelord "
f"height: {new_peak.reward_chain_block.height} weight:"
f"{new_peak.reward_chain_block.weight} "
)
self.timelord.new_peak = new_p... | it's not obvious to me why we should stick to our own unfinished block if the iteration count is equal. | self.timelord.state_changed("skipping_peak", {"height": new_peak.reward_chain_block.height})
return
log.info(
"Not skipping peak, don't have. Maybe we are not the fastest timelord "
f"height: {new_peak.reward_chain_block.he... | @@ -99,13 +101,22 @@ async def new_peak_timelord(self, new_peak: timelord_protocol.NewPeakTimelord) -
self.timelord.state_changed("skipping_peak", {"height": new_peak.reward_chain_block.height})
def check_orphaned_unfinished_block(self, new_peak: NewPeakTimelord):
+ new_peak_unf_rh = new_peak... | chia/timelord/timelord_api.py | 26 | Python | 0.429 | suggestion | 103 | 51 | 51 | false | dont skip same peak if in unfinished cache | 19,626 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz |
async with reader.execute(query, (store_id, *chunk)) as cursor:
rows = await cursor.fetchall()
result.update({row["kv_id"]: row["blob"] for row in rows})
if len(result) != len(kv_ids):
raise Exception("Cannot retrieve all the requested kv_ids... | i think this is loading the blob from disk twice? i would have to look back, but i think i figured out how to pass a pyo3 object back into rust without overhead which would allow these to be re-ordered with the already loaded merkle blob being passed to the delta file cache. this would still avoid asking the blob to ... | await self.get_nodes_for_file(root, left_hash, store_id, deltas_only, delta_file_cache, tree_nodes)
await self.get_nodes_for_file(root, right_hash, store_id, deltas_only, delta_file_cache, tree_nodes)
tree_nodes.append(SerializedNode(False, bytes(left_hash), bytes(right_hash)))
... | @@ -1667,20 +1667,21 @@ async def write_tree_to_file(
if node_hash == bytes32.zeros:
return
+ delta_file_cache = DeltaFileCache()
+ with log_exceptions(log=log, message="Error while getting merkle blob"):
+ root_path = self.get_merkle_path(store_id=store_id, root_hash=ro... | chia/data_layer/data_store.py | 26 | Python | 0.5 | performance | 411 | 51 | 51 | false | Optimize add missing files | 19,630 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | fchirica |
if root.generation > 0:
previous_root = await self.get_tree_root(store_id=store_id, generation=root.generation - 1)
with log_exceptions(log=log, message="Error while getting previous merkle blob"):
previous_root_path = self.get_merkle_path(store_id=store_id, root_hash=pre... | does this otherwise not result in a traceback in the log? it feels a bit special given all that's being done is choosing a path.
similar applies below. | FROM ids
WHERE store_id = ? AND kv_id IN ({placeholders})
LIMIT {len(chunk)}
"""
async with reader.execute(query, (store_id, *chunk)) as cursor:
rows = await cursor.fetchall()
result.upda... | @@ -1667,20 +1667,21 @@ async def write_tree_to_file(
if node_hash == bytes32.zeros:
return
+ delta_file_cache = DeltaFileCache()
+ with log_exceptions(log=log, message="Error while getting merkle blob"): | chia/data_layer/data_store.py | 26 | Python | 0.357 | question | 155 | 51 | 51 | false | Optimize add missing files | 19,630 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | fchirica |
coin_hints: dict[bytes32, bytes32] = {
coin_id: bytes32(hint) for coin_id, hint in ppp_result.hints if len(hint) == 32
}
peak = Peak(
state_change_summary.peak.header_hash, state_change_summary.peak.height, state_change_summary.peak.weight
)
# Looks up c... | I would have thought we'd want this early in this function, to minimize the reordering of these things | await self.server.send_to_all([msg], NodeType.FULL_NODE)
coin_hints: dict[bytes32, bytes32] = {
coin_id: bytes32(hint) for coin_id, hint in ppp_result.hints if len(hint) == 32
}
peak = Peak(
state_change_summary.peak.header_hash, state_change_summary.pea... | @@ -2013,6 +2019,10 @@ async def peak_post_processing_2(
self._state_changed("new_peak")
+ if ppp_result.signage_points is not None:
+ for signage_point in ppp_result.signage_points:
+ await self.signage_point_post_processing(*signage_point)
+ | chia/full_node/full_node.py | 26 | Python | 0.357 | suggestion | 102 | 51 | 51 | false | CHIA-2823 move sp broadcast | 19,654 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | almogdepaz |
async def new_block(
self,
height: uint32,
timestamp: uint64,
included_reward_coins: Collection[Coin],
tx_additions: Collection[Coin],
tx_removals: list[bytes32],
) -> None:
"""
Only called for blocks which are blocks (and thus have rewards and tra... | I think it would be very helpful to have comments here, with the names of these fields | async def new_block(
self,
height: uint32,
timestamp: uint64,
included_reward_coins: Collection[Coin],
tx_additions: Collection[Coin],
tx_removals: list[bytes32],
) -> None:
"""
Only called for blocks which are blocks (and thus have rewards and tra... | @@ -91,34 +91,43 @@ async def new_block(
start = time.monotonic()
- additions = []
+ db_values_to_insert = []
for coin in tx_additions:
- record: CoinRecord = CoinRecord(
- coin,
- height,
- uint32(0),
- False,
... | chia/full_node/coin_store.py | 26 | Python | 0.214 | suggestion | 86 | 51 | 51 | false | CHIA-2989 Insert DB values in CoinStore's new_block without creating coin records for them | 19,662 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
for coin in tx_additions:
db_values_to_insert.append(
(
coin.name(),
height,
0,
0,
coin.puzzle_hash,
coin.parent_coin_info,
coin.amount.stream_t... | can you remove `_add_coin_records()` now? If it's only used by tests, it should be pulled out of the class | for coin in tx_additions:
db_values_to_insert.append(
(
coin.name(),
# confirmed_index
height,
# spent_index
0,
# coinbase
0,
... | @@ -91,34 +91,43 @@ async def new_block(
start = time.monotonic()
- additions = []
+ db_values_to_insert = []
for coin in tx_additions:
- record: CoinRecord = CoinRecord(
- coin,
- height,
- uint32(0),
- False,
... | chia/full_node/coin_store.py | 26 | Python | 0.571 | suggestion | 106 | 51 | 51 | false | CHIA-2989 Insert DB values in CoinStore's new_block without creating coin records for them | 19,662 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
from __future__ import annotations
import dataclasses
import logging
import sqlite3
import time
from collections.abc import Collection
from typing import Any, ClassVar, Optional
import typing_extensions
from aiosqlite import Cursor
from chia_rs import CoinState
from chia_rs.sized_bytes import bytes32
from chia_rs.siz... | I think most of the value of this change is gained by moving this function into a file that lives under `chia/_tests/` to remove it from production code and turn it into test code | from __future__ import annotations
import dataclasses
import logging
import sqlite3
import time
from collections.abc import Collection
from typing import Any, ClassVar, Optional
import typing_extensions
from aiosqlite import Cursor
from chia_rs import CoinState
from chia_rs.sized_bytes import bytes32
from chia_rs.siz... | @@ -22,6 +22,28 @@
log = logging.getLogger(__name__)
+async def add_coin_records_to_db(db_wrapper: DBWrapper2, records: list[CoinRecord]) -> None: | chia/full_node/coin_store.py | 25 | Python | 0.571 | suggestion | 179 | 50 | 50 | false | CHIA-3050 Extract _add_coin_records out of CoinStore and simplify it | 19,686 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
"INSERT INTO coin_record VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
(
(
record.coin.name(),
record.confirmed_block_index,
record.spent_block_index,
int(record.coinbase),
record.coin.puzzle_h... | ```suggestion
coin = Coin(bytes32([i*2] * 32), bytes32([i*2+1] * 32), uint64(i))
``` | from __future__ import annotations
from chia.types.coin_record import CoinRecord
from chia.util.db_wrapper import DBWrapper2
async def add_coin_records_to_db(db_wrapper: DBWrapper2, records: list[CoinRecord]) -> None:
if len(records) == 0:
return
async with db_wrapper.writer_maybe_transaction() as co... | @@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import pytest
+from chia_rs import Coin
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia._tests.util.db_connection import DBConnection
+from chia.full_node.coin_store import CoinStore
+from chia.types.coin_record... | chia/_tests/util/coin_store.py | 26 | Python | 0.571 | suggestion | 98 | 41 | 27 | false | CHIA-3050 Extract _add_coin_records out of CoinStore and simplify it | 19,686 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
# reserve fee cannot be greater than UINT64_MAX per consensus rule.
# run_generator() would fail
assert_fee_sum = uint64(0 if conds is None else conds.reserve_fee)
# 17. Check that the assert fee sum <= fees, and that each reserved fee is non-negative
if fees < assert_fee_sum:
return Err.R... | was adding this hinting needed? |
# reserve fee cannot be greater than UINT64_MAX per consensus rule.
# run_generator() would fail
assert_fee_sum = uint64(0 if conds is None else conds.reserve_fee)
# 17. Check that the assert fee sum <= fees, and that each reserved fee is non-negative
if fees < assert_fee_sum:
return Err.R... | @@ -549,7 +549,7 @@ async def validate_block_body(
# 21. Verify conditions
# verify absolute/relative height/time conditions
if conds is not None:
- error = mempool_check_time_locks(
+ error: Optional[Err] = check_time_locks( | chia/consensus/block_body_validation.py | 26 | Python | 0.071 | question | 31 | 40 | 40 | false | Extract time lock validation and move to `chia.consensus`. | 19,707 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
def get_future_reward_coins(block: FullBlock) -> tuple[Coin, Coin]:
pool_amount = calculate_pool_reward(block.height)
farmer_amount = calculate_base_farmer_reward(block.height)
if block.is_transaction_block():
assert block.transactions_info is not None
farmer_amount = uint64(farmer_amount +... | is this just a formatting change? |
def get_future_reward_coins(block: FullBlock) -> tuple[Coin, Coin]:
pool_amount = calculate_pool_reward(block.height)
farmer_amount = calculate_base_farmer_reward(block.height)
if block.is_transaction_block():
assert block.transactions_info is not None
farmer_amount = uint64(farmer_amount ... | @@ -61,22 +58,15 @@ def get_future_reward_coins(block: FullBlock) -> tuple[Coin, Coin]:
async def test_basic_coin_store(db_version: int, softfork_height: uint32, bt: BlockTools) -> None:
wallet_a = WALLET_A
reward_ph = wallet_a.get_new_puzzlehash()
-
# Generate some coins
- blocks = bt.get_consecutiv... | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.143 | question | 33 | 51 | 51 | false | CHIA-3107 Simplify test_basic_coin_store | 19,709 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
pool_coin: Coin = create_pool_coin(
block.height, block.foliage.foliage_block_data.pool_target.puzzle_hash, pool_amount, constants.GENESIS_CHALLENGE
)
farmer_coin: Coin = create_farmer_coin(
block.height,
block.foliage.foliage_block_data.farmer_reward_puzzle_hash,
farmer_amou... | I think it's hard to argue that this (nested list comprehensions) is a simplification to the left hand side. You also end up with one more line of code | farmer_amount = uint64(farmer_amount + block.transactions_info.fees)
pool_coin: Coin = create_pool_coin(
block.height, block.foliage.foliage_block_data.pool_target.puzzle_hash, pool_amount, constants.GENESIS_CHALLENGE
)
farmer_coin: Coin = create_farmer_coin(
block.height,
bl... | @@ -61,22 +58,15 @@ def get_future_reward_coins(block: FullBlock) -> tuple[Coin, Coin]:
async def test_basic_coin_store(db_version: int, softfork_height: uint32, bt: BlockTools) -> None:
wallet_a = WALLET_A
reward_ph = wallet_a.get_new_puzzlehash()
-
# Generate some coins
- blocks = bt.get_consecutiv... | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.357 | suggestion | 151 | 51 | 51 | false | CHIA-3107 Simplify test_basic_coin_store | 19,709 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
bytes(block.transactions_generator), [], flags, bt.constants
)
tx_removals = [removal.name() for removal in removals]
tx_additions = [addition for addition, _ in additions]
else:
tx_removals, tx_additions = [], []
... | This is just a formatting change, right?
I think the existing formatting is preferred. I don't think this is a simplification. Is it? | should_be_included.add(farmer_coin)
should_be_included.add(pool_coin)
if not block.is_transaction_block():
continue
if block.transactions_generator is not None:
assert block.transactions_info is not None
flags = get_flags_fo... | @@ -97,75 +87,65 @@ async def test_basic_coin_store(db_version: int, softfork_height: uint32, bt: Bl
farmer_coin, pool_coin = get_future_reward_coins(block)
should_be_included.add(farmer_coin)
should_be_included.add(pool_coin)
- if block.is_transaction_block():
- ... | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.429 | question | 134 | 51 | 51 | false | CHIA-3107 Simplify test_basic_coin_store | 19,709 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
if not block.is_transaction_block():
continue
if block.transactions_generator is not None:
assert block.transactions_info is not None
flags = get_flags_for_height_and_constants(block.height, bt.constants)
additions, removals = addit... | This is just a formatting change, right?I think the existing formatting is preferred. |
# Adding blocks to the coin store
should_be_included_prev: set[Coin] = set()
should_be_included: set[Coin] = set()
for block in blocks:
farmer_coin, pool_coin = get_future_reward_coins(block)
should_be_included.add(farmer_coin)
should_be_included.add(... | @@ -97,75 +87,65 @@ async def test_basic_coin_store(db_version: int, softfork_height: uint32, bt: Bl
farmer_coin, pool_coin = get_future_reward_coins(block)
should_be_included.add(farmer_coin)
should_be_included.add(pool_coin)
- if block.is_transaction_block():
- ... | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.286 | suggestion | 85 | 51 | 51 | false | CHIA-3107 Simplify test_basic_coin_store | 19,709 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
"coin_parent, amount, timestamp, coin_name FROM coin_record WHERE confirmed_index>?",
(block_index,),
)
for row in rows:
coin = self.row_to_coin(row)
spent_index = uint32(0) if row[1] <= 0 else row[1]
record = CoinRe... | did you see sqlite selecting a different index? | # Add coins that are confirmed in the reverted blocks to the list of changed coins.
rows = await conn.execute_fetchall(
"SELECT confirmed_index, spent_index, coinbase, puzzle_hash, "
"coin_parent, amount, timestamp, coin_name FROM coin_record WHERE spent_index>?",... | @@ -571,8 +592,33 @@ async def rollback_to_block(self, block_index: int) -> list[CoinRecord]:
if coin_name not in coin_changes:
coin_changes[coin_name] = record
- await conn.execute("UPDATE coin_record SET spent_index=0 WHERE spent_index>?", (block_index,))
- re... | chia/full_node/coin_store.py | 26 | Python | 0.071 | question | 47 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
assert len(self.block_hashes) == self.peak_height - self.fork_height
assert block.height == self.fork_height + 1 + len(self.block_hashes)
self.block_hashes.append(header_hash)
self.peak_height = int(block.height)
self.peak_hash = header_hash
if conds is not None:
... | any changes to this logic are very hard to spot since you refactored this code at the same time. If you think we should remove this function, doing so (without any logic changes) should be a separate PR. | assert len(self.block_hashes) == self.peak_height - self.fork_height
assert block.height == self.fork_height + 1 + len(self.block_hashes)
self.block_hashes.append(header_hash)
self.peak_height = int(block.height)
self.peak_hash = header_hash
def include_reward_coins(self, bl... | @@ -102,40 +104,24 @@ def include_spends(self, conds: Optional[SpendBundleConditions], block: FullBloc
assert block.foliage_transaction_block is not None
timestamp = block.foliage_transaction_block.timestamp
for spend in conds.spends:
- self.removals_since_fork[byte... | chia/consensus/block_body_validation.py | 26 | Python | 0.5 | refactor | 203 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
self,
(fork_info.peak_height, fork_info.peak_hash),
(block.height - 1, block.prev_header_hash),
self.constants,
)
# the ForkInfo object is expected to be valid, just having its peak
# behind the current block
assert peak_hash == fork_info.p... | is there a good reason to change this? `run_block_generator2()` is slower, since it accepts *untrusted* blocks, whereas `additions_and_removals()` only run *trusted* blocks. i.e. we have already validated them | (block.height - 1, block.prev_header_hash),
self.constants,
)
# the ForkInfo object is expected to be valid, just having its peak
# behind the current block
assert peak_hash == fork_info.peak_hash
assert len(chain) == block.height - fork_info.peak_height -... | @@ -268,22 +268,26 @@ async def run_single_block(self, block: FullBlock, fork_info: ForkInfo) -> None:
assert fork_info.peak_height == block.height - 1
assert block.height == 0 or fork_info.peak_hash == block.prev_header_hash
- additions: list[tuple[Coin, Optional[bytes]]] = []
- remov... | chia/consensus/blockchain.py | 26 | Python | 0.643 | security | 209 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
records = [await coin_store.get_coin_record(coin.name()) for coin in coins]
for record in records:
assert record is not None
assert record.spent
assert record.spent_block_index == block.height
@pytest.mark.limit_consensus_modes(reason="save time"... | this refactoring, of turning this into an early-continue is already made in a separate PR, isn't it? Are there *other* changes mixed in with this refactoring too? If so, the refactoring should probably be turned into a separate commit so the logic change becomes visible by itself |
records = [await coin_store.get_coin_record(coin.name()) for coin in coins]
for record in records:
assert record is not None
assert record.spent
assert record.spent_block_index == block.height
@pytest.mark.limit_consensus_modes(reason="save time... | @@ -220,22 +217,12 @@ async def test_num_unspent(bt: BlockTools, db_version: int) -> None:
for block in blocks:
if not block.is_transaction_block():
continue
-
- if block.is_transaction_block(): | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.5 | refactor | 280 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
for coin in block.get_included_reward_coins():
if coin.puzzle_hash == reward_ph:
coins_to_spend.append(coin)
spend_bundle = wallet_a.generate_signed_transaction(uint64(1000), wallet_a.get_new_puzzlehash(), coins_to_spend[0])
async with DBConnection(db_version) a... | this refactoring is also in a separate PR. Are there logic changes mixed into this refactor? If so, the refactor should be a separate commit so the logic changes are visible alone | if block.is_transaction_block():
for coin in block.get_included_reward_coins():
if coin.puzzle_hash == reward_ph:
coins_to_spend.append(coin)
spend_bundle = wallet_a.generate_signed_transaction(uint64(1000), wallet_a.get_new_puzzlehash(), coins_to_spend[0])
... | @@ -98,75 +97,73 @@ async def test_basic_coin_store(db_version: int, softfork_height: uint32, bt: Bl
farmer_coin, pool_coin = get_future_reward_coins(block)
should_be_included.add(farmer_coin)
should_be_included.add(pool_coin)
- if block.is_transaction_block(): | chia/_tests/core/full_node/stores/test_coin_store.py | 26 | Python | 0.429 | refactor | 179 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
return fork_info
@pytest.mark.anyio
async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchain: Blockchain, bt: BlockTools) -> None:
"""
Covers the case of calling `get_header_blocks_in_range`, requesting
transactions filter, on a non transaction block.
"""
b = empty_blo... | I think we should use a different name than "potential_ff_singleton". Partly because it's very long but also that it might be misunderstood to mean the same thing as "eligible for ff". Maybe something concise that describes more closely what it represents | b.clean_block_records()
with pytest.raises(AssertionError):
await b.lookup_block_generators(blocks_1[600].prev_header_hash, {uint32(3)})
async def get_fork_info(blockchain: Blockchain, block: FullBlock, peak: BlockRecord) -> ForkInfo:
fork_chain, fork_hash = await lookup_fork_chain(
bl... | @@ -4199,3 +4203,104 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.5 | suggestion | 255 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
# spend flags, we'll consider coins with odd amount
# that share the same puzzle hash and amount as their
# spent parents to be potential ff singletons.
maybe_ff_singleton = (
addition.amount % 2 ... | the fact that `spend_sim` reaches into private functions of `CoinStore` has been a problem for a while, and this is making it worse. Is there now way for spend sim to use the same interface as the main blockchain to manipulate the coin store? | await self.coin_store.new_block(
height=uint32(self.block_height + 1),
timestamp=self.timestamp,
included_reward_coins=included_reward_coins,
tx_additions=tx_additions,
tx_removals=spent_coins_ids if spent_coins_ids is not None else [],
)
... | @@ -281,11 +281,38 @@ async def farm_block(self, puzzle_hash: bytes32 = bytes32(b"0" * 32)) -> tuple[l
await self.hint_store.add_hints(hints)
return_additions = additions
return_removals = bundle.removals()
- spent_coins_ids = [r.name... | chia/_tests/util/spend_sim.py | 26 | Python | 0.643 | question | 242 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
log.info("DB: Creating index coin_spent_index")
await conn.execute("CREATE INDEX IF NOT EXISTS coin_spent_index on coin_record(spent_index)")
log.info("DB: Creating index coin_puzzle_hash")
await conn.execute("CREATE INDEX IF NOT EXISTS coin_puzzle_hash on coin_record(p... | this will make the database larger. Can you add a comment to the source code explaining why we need this index? it would be good to document why we only add it to new databases too
|
log.info("DB: Creating index coin_spent_index")
await conn.execute("CREATE INDEX IF NOT EXISTS coin_spent_index on coin_record(spent_index)")
log.info("DB: Creating index coin_puzzle_hash")
await conn.execute("CREATE INDEX IF NOT EXISTS coin_puzzle_hash on coin_record(p... | @@ -66,11 +66,23 @@ async def create(cls, db_wrapper: DBWrapper2) -> CoinStore:
log.info("DB: Creating index coin_parent_index")
await conn.execute("CREATE INDEX IF NOT EXISTS coin_parent_index on coin_record(coin_parent)")
+ async with conn.execute("SELECT 1 FROM coin_record LIMI... | chia/full_node/coin_store.py | 26 | Python | 0.357 | suggestion | 182 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
self.peak_height = fork_height
self.peak_hash = header_hash
self.additions_since_fork = {}
self.removals_since_fork = {}
self.block_hashes = []
def include_spends(self, conds: Optional[SpendBundleConditions], block: FullBlock, header_hash: bytes32) -> None:
height = ... | I don't think we want the database to reflect the `ELIGIBLE_FOR_FF` flag. I would like the invariant for this field to be simple and easy to verify. i.e. *just* parent puzzle hash matches our puzzle hash, parent amount matches our amount, (and maybe amount is odd).
iiuc, this additional field to `ForkAdd()` is represe... | self.fork_height = fork_height
self.peak_height = fork_height
self.peak_hash = header_hash
self.additions_since_fork = {}
self.removals_since_fork = {}
self.block_hashes = []
def update_fork_peak(self, block: FullBlock, header_hash: bytes32) -> None:
"""Updat... | @@ -102,40 +104,24 @@ def include_spends(self, conds: Optional[SpendBundleConditions], block: FullBloc
assert block.foliage_transaction_block is not None
timestamp = block.foliage_transaction_block.timestamp
for spend in conds.spends:
- self.removals_since_fork[byte... | chia/consensus/block_body_validation.py | 26 | Python | 0.571 | question | 352 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
coin=coin,
child_coin=child_coin,
)
def check_additions(self, expected_same_parent_additions: set[bytes32]) -> None:
assert all(
a in self.fork_info.additions_since_fork and self.fork_info.additions_since_fork[a].same_as_parent
for a in expected_same_... | if you're really considering whether the amount is odd, this test should be parameterized on that as well, right? | puzzle_hash = bytes32([2] * 32)
amount = uint64(1337)
coin = Coin(bytes32([3] * 32), puzzle_hash, amount)
child_coin_ph = puzzle_hash if same_ph_as_parent else bytes32([4] * 32)
child_coin_amount = amount if same_amount_as_parent else uint64(0)
child_coin = Coin(coin.name... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.429 | question | 113 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
[],
[],
[],
[],
flags,
)
],
0,
0,
0,
None,
None,
[],
0,
0,
0,
True,
0,
0,
)
# Now let's run the test
test_setup.... | I was expecting `odd_amount` here as well | None,
None,
None,
create_coin,
[],
[],
[],
[],
[],
[],
[],
0,
)
],
0,
0,
0,
... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.214 | suggestion | 41 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
test_setup.check_additions(expected_same_parent_additions)
if rollback:
# Now we rollback before the spend that belongs to the test conditions
test_setup.fork_info.rollback(test_setup.test_block.prev_header_hash, test_setup.test_block.height - 1)
# That should leave only the initial addi... | It sounds a bit odd to refer to a coin being created as "its parent is spent". unless I'm missing something. A coin can never have an unspent parent.
```suggestion
A coin is tracked as a potential fast forward singleton when it's created,
if its puzzle hash and amount match the parent, and the amount is odd.... | test_setup.fork_info.include_spends(conds, test_setup.test_block, test_setup.test_block.header_hash)
# Let's make sure the results are as expected
expected_same_parent_additions = (
{test_setup.child_coin.name()} if same_ph_as_parent and same_amount_as_parent else set()
)
test_setup.check_ad... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.786 | suggestion | 331 | 50 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
if rollback:
# Now we rollback before the spend that belongs to the test conditions
test_setup.fork_info.rollback(test_setup.test_block.prev_header_hash, test_setup.test_block.height - 1)
# That should leave only the initial additions we started with
assert test_setup.fork_info.addit... | was it deliberate to say "coins` in plural? I might be a bit confused as well, this test name says "same_as_parent", but whether the parent is the same or not depends on which configuration of this test is run, doesn't it? The same goes for `test_include_spends_same_as_parent()` | # Let's make sure the results are as expected
expected_same_parent_additions = (
{test_setup.child_coin.name()} if same_ph_as_parent and same_amount_as_parent else set()
)
test_setup.check_additions(expected_same_parent_additions)
if rollback:
# Now we rollback before the spend that ... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.643 | suggestion | 279 | 49 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
blocks = bt.get_consecutive_blocks(2)
for block in blocks:
await _validate_and_add_block(b, block)
non_tx_block = next(block for block in blocks if not block.is_transaction_block())
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
a... | `None, False, False`, it's not so easy to know what this means. I think this crosses the line for number of unnamed `bool` parameters | for block in blocks:
await _validate_and_add_block(b, block)
non_tx_block = next(block for block in blocks if not block.is_transaction_block())
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.head... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.5 | suggestion | 133 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
from chia.types.coin_record import CoinRecord
from chia.util.errors import Err
from chia.util.hash import std_hash
log = logging.getLogger(__name__)
# peak-> o
# main |
# chain o o <- peak_height \ additions and removals
# | | peak_hash | from these blocks are
# o o ... | isn't there some `dataclass` property to require these to be named when initialized? I think it would be best to do that for `hint`, `is_coinbase` and `same_as_parent`. Then we could give them default values too.
Also, as far as I can tell, different parts of your patch seem to define what this field refers to sligh... | from chia.util.errors import Err
from chia.util.hash import std_hash
log = logging.getLogger(__name__)
# peak-> o
# main |
# chain o o <- peak_height \ additions and removals
# | | peak_hash | from these blocks are
# o o / recorded
# \ /
# o <- f... | @@ -49,6 +50,7 @@ class ForkAdd:
timestamp: uint64
hint: Optional[bytes]
is_coinbase: bool
+ same_as_parent: bool | chia/consensus/block_body_validation.py | 26 | Python | 0.643 | question | 801 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
True,
0,
0,
)
# Now let's run the test
test_setup.fork_info.include_spends(conds, test_setup.test_block, test_setup.test_block.header_hash)
# Let's make sure the results are as expected
expected_same_parent_additions = (
{test_setup.child_coin.name()}
if eligi... | isn't there supposed to be a check that `same_as_parent` is set correctly here? | 0,
None,
None,
[],
0,
0,
0,
True,
0,
0,
)
# Now let's run the test
test_setup.fork_info.include_spends(conds, test_setup.test_block, test_setup.test_block.header_hash)
# Let's make sure the results are as expected
expect... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.357 | question | 79 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
A coin is tracked as a potential fast forward singleton when its parent is
spent, its puzzle hash and amount match, and the amount is odd. We're
covering here `include_block`, `rollback` and `reset` in
the context of potential fast forward singletons.
"""
test_setup = ForkInfoTestSetup.create(sa... | isn't there supposed to be a check that `same_as_parent` is set correctly here? | @pytest.mark.parametrize("reset", [True, False])
@pytest.mark.anyio
async def test_include_block_same_as_parent_coins(
same_ph_as_parent: bool, same_amount_as_parent: bool, rollback: bool, reset: bool
) -> None:
"""
Tests that `ForkInfo` properly tracks same-as-parent created coins.
A created coin is tr... | @@ -4235,3 +4239,163 @@ async def test_get_header_blocks_in_range_tx_filter_non_tx_block(empty_blockchai
blocks_with_filter = await b.get_header_blocks_in_range(0, 42, tx_filter=True)
empty_tx_filter = b"\x00"
assert blocks_with_filter[non_tx_block.header_hash].transactions_filter == empty_tx_filter
+
+
... | chia/_tests/blockchain/test_blockchain.py | 26 | Python | 0.357 | question | 79 | 26 | 32 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
spend_id = spend.coin.name()
spent_coins[spend_id] = spend.coin
spent_coins_ids.append(spend_id)
tx_removals.append(spend.coin)
for addition in additions:
same_as_parent = (
... | it seems that you don't need `spent_coins_ids` anymore, now that you have `spent_coins`. I would think this could just be:
```suggestion
await self.new_peak(spent_coins.keys())
``` | spend_id = spend.coin.name()
spent_coins[spend_id] = spend.coin
spent_coins_ids.append(spend_id)
tx_removals.append(spend.coin)
for child in additions:
parent = spent_coins.get(chi... | @@ -299,7 +309,7 @@ async def farm_block(self, puzzle_hash: bytes32 = bytes32(b"0" * 32)) -> tuple[l
await self.new_peak(spent_coins_ids) | chia/_tests/util/spend_sim.py | 26 | Python | 0.786 | suggestion | 191 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
"""Updates `self` with `block`'s height and `header_hash`."""
assert self.peak_height == block.height - 1
assert len(self.block_hashes) == self.peak_height - self.fork_height
assert block.height == self.fork_height + 1 + len(self.block_hashes)
self.block_hashes.append(header_hash... | I don't think you need to give this a name. This change is unrelated to the essence of this PR and, I think, makes it harder to read. I would say the same thing about `spend_ph`. It adds changes to the diff, even though it's not a material change. I don't believe these compute any hashes. | """Updates `self` with `block`'s height and `header_hash`."""
assert self.peak_height == block.height - 1
assert len(self.block_hashes) == self.peak_height - self.fork_height
assert block.height == self.fork_height + 1 + len(self.block_hashes)
self.block_hashes.append(header_hash... | @@ -103,18 +105,34 @@ def include_reward_coins(self, block: FullBlock) -> None:
timestamp = block.foliage_transaction_block.timestamp
coin_id = coin.name()
assert coin_id not in self.additions_since_fork
- self.additions_since_fork[coin_id] = ForkAdd(coin, block.height,... | chia/consensus/block_body_validation.py | 26 | Python | 0.643 | suggestion | 289 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
self.block_hashes.append(header_hash)
self.peak_height = int(block.height)
self.peak_hash = header_hash
def include_reward_coins(self, block: FullBlock) -> None:
"""Updates `self` with `block`'s reward coins."""
for coin in block.get_included_reward_coins():
asse... | This flag means more things than just same puzzle hash, same amount and odd amount.
I don't understand why this should be considered at all. This is setting the `spent_index` differently than it's set during a reorg, isn't it?
Imagine coming here and `ELIGIBLE_FOR_FF` is not set, but puzzle hash and amount do match. ... | self.block_hashes.append(header_hash)
self.peak_height = int(block.height)
self.peak_hash = header_hash
def include_reward_coins(self, block: FullBlock) -> None:
"""Updates `self` with `block`'s reward coins."""
for coin in block.get_included_reward_coins():
asse... | @@ -103,18 +105,34 @@ def include_reward_coins(self, block: FullBlock) -> None:
timestamp = block.foliage_transaction_block.timestamp
coin_id = coin.name()
assert coin_id not in self.additions_since_fork
- self.additions_since_fork[coin_id] = ForkAdd(coin, block.height,... | chia/consensus/block_body_validation.py | 26 | Python | 0.643 | performance | 674 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
child_coin, block.height, timestamp, hint, False, same_as_parent
)
self.include_reward_coins(block)
def include_block(
self,
additions: list[tuple[Coin, Optional[bytes]]],
removals: list[Coin],
block: FullBlock,
header_hash... | this logic also needs to be the same as all other places where this flag is set. Here you check whether amount is odd, you don't above. | ) -> None:
self.update_fork_peak(block, header_hash)
if block.foliage_transaction_block is not None:
timestamp = block.foliage_transaction_block.timestamp
spent_coins: dict[bytes32, Coin] = {}
for spend in removals:
spend_id = bytes32(spend.name())... | @@ -127,10 +145,21 @@ def include_block(
self.update_fork_peak(block, header_hash)
if block.foliage_transaction_block is not None:
timestamp = block.foliage_transaction_block.timestamp
+ spent_coins: dict[bytes32, Coin] = {}
for spend in removals:
- ... | chia/consensus/block_body_validation.py | 26 | Python | 0.357 | suggestion | 135 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
and amount == spend.coin_amount
)
self.additions_since_fork[child_coin_id] = ForkAdd(
child_coin, block.height, timestamp, hint, False, same_as_parent
)
self.include_reward_coins(block)
def include_b... | this looks suspicious. Is there ever a case where `coin.parent_coin_info` is *not* in `spent_coins`?
In case `coin.parent_coin_info` isn't, I can't imagine this expression being correct.
If it's always expected to be in there, it should be an `assert`. | removals: list[Coin],
block: FullBlock,
header_hash: bytes32,
) -> None:
self.update_fork_peak(block, header_hash)
if block.foliage_transaction_block is not None:
timestamp = block.foliage_transaction_block.timestamp
spent_coins: dict[bytes32, Coin] = ... | @@ -127,10 +145,21 @@ def include_block(
self.update_fork_peak(block, header_hash)
if block.foliage_transaction_block is not None:
timestamp = block.foliage_transaction_block.timestamp
+ spent_coins: dict[bytes32, Coin] = {}
for spend in removals:
- ... | chia/consensus/block_body_validation.py | 26 | Python | 0.643 | suggestion | 254 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
height = uint32(max(last_coin_state.created_height or 0, last_coin_state.spent_height or 0))
if height != next_height:
break
coin_states.pop()
return coin_states, next_height
async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecor... | this is not obvious to me. why do you need to "launder" the same-puzzle and same amount bit here? | height = uint32(max(last_coin_state.created_height or 0, last_coin_state.spent_height or 0))
if height != next_height:
break
coin_states.pop()
return coin_states, next_height
async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecor... | @@ -534,7 +558,8 @@ async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecord]
)
for row in rows:
coin = self.row_to_coin(row)
- record = CoinRecord(coin, uint32(0), row[1], row[2], uint64(0))
+ spent_index = uint32(0) if row... | chia/full_node/coin_store.py | 26 | Python | 0.214 | question | 97 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
last_coin_state = coin_states[-1]
height = uint32(max(last_coin_state.created_height or 0, last_coin_state.spent_height or 0))
if height != next_height:
break
coin_states.pop()
return coin_states, next_height
async def rollback_to_block(self... | ```suggestion
spent_index = uint32(0) if row[1] <= 0 else uint32(row[1])
``` | last_coin_state = coin_states[-1]
height = uint32(max(last_coin_state.created_height or 0, last_coin_state.spent_height or 0))
if height != next_height:
break
coin_states.pop()
return coin_states, next_height
async def rollback_to_block(self... | @@ -534,7 +558,8 @@ async def rollback_to_block(self, block_index: int) -> dict[bytes32, CoinRecord]
)
for row in rows:
coin = self.row_to_coin(row)
- record = CoinRecord(coin, uint32(0), row[1], row[2], uint64(0))
+ spent_index = uint32(0) if row... | chia/full_node/coin_store.py | 26 | Python | 0.571 | suggestion | 94 | 51 | 51 | false | CHIA-2900 Fast forward mempool optimization | 19,713 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
v1 = v[:3] + ("0" * (len(v) - 3))
s.append(int(v1))
NUM *= A
DEN *= B
assert NUM < 1 << 64
assert DEN < 1 << 64
if NUM > MAX:
NUM >>= 5
DEN >>= 5
return s
CONDITION_COSTS = compute_cost_table()
def conditions_cost(conds: Program) ->... | this should be a constant somewhere | def compute_cost_table() -> list[int]:
A = 17
B = 16
s = []
NUM = 100
DEN = 1
MAX = 1 << 59
for i in range(256):
v = str(NUM // DEN)
v1 = v[:3] + ("0" * (len(v) - 3))
s.append(int(v1))
NUM *= A
DEN *= B
assert NUM < 1 << 64
assert DEN <... | @@ -1958,10 +1967,19 @@ def compute_cost_table() -> list[int]:
CONDITION_COSTS = compute_cost_table()
-def conditions_cost(conds: Program) -> uint64:
+def conditions_cost(conds: Program, *, charge_for_conditions: bool) -> uint64:
+ free_conditions = 100 | chia/simulator/block_tools.py | 26 | Python | 0.143 | suggestion | 35 | 51 | 51 | false | [CHIA-2859] add ConsensusMode in tests to cover the new hard fork | 19,716 | Chia-Network/chia-blockchain | 10,822 | Python | matt-o-how | arvidn |
def stream_bytes(item: Any, f: BinaryIO) -> None:
write_uint32(f, uint32(len(item)))
f.write(item)
def stream_list(stream_inner_type_func: StreamFunctionType, item: Any, f: BinaryIO) -> None:
write_uint32(f, uint32(len(item)))
for element in item:
stream_inner_type_func(element, f)
def strea... | I would think we might want the order of keys to be deterministic, no? |
def stream_bytes(item: Any, f: BinaryIO) -> None:
write_uint32(f, uint32(len(item)))
f.write(item)
def stream_list(stream_inner_type_func: StreamFunctionType, item: Any, f: BinaryIO) -> None:
write_uint32(f, uint32(len(item)))
for element in item:
stream_inner_type_func(element, f)
def stre... | @@ -429,6 +466,21 @@ def stream_tuple(stream_inner_type_funcs: list[StreamFunctionType], item: Any, f
stream_inner_type_funcs[i](item[i], f)
+def stream_dict(
+ key_stream_inner_type_func: StreamFunctionType,
+ value_stream_inner_type_func: StreamFunctionType,
+ item: Any,
+ f: BinaryIO,
+) -> ... | chia/util/streamable.py | 26 | Python | 0.214 | question | 70 | 51 | 51 | false | [CHIA-3158] Add dicts to streamable | 19,719 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | Quexington |
],
)
def test_round_trip(value: int) -> None:
t1 = Program.to(value)
t2 = int_to_bytes(value)
assert t1 == Program.to(t2)
assert int_from_bytes(t2) == value
assert t1.as_int() == value
def test_zero_serialization() -> None:
assert int_to_bytes(0) == b""
assert int_from_bytes(b"") == 0
... | it's preferable to have unit tests be deterministic, so this would be better using fixed seed | ],
)
def test_round_trip(value: int) -> None:
t1 = Program.to(value)
t2 = int_to_bytes(value)
assert t1 == Program.to(t2)
assert int_from_bytes(t2) == value
assert t1.as_int() == value
def test_zero_serialization() -> None:
assert int_to_bytes(0) == b""
assert int_from_bytes(b"") == 0
... | @@ -0,0 +1,87 @@
+from __future__ import annotations
+
+import random
+
+import pytest
+
+from chia.types.blockchain_format.program import Program
+from chia.util.casts import int_from_bytes, int_to_bytes
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ 0,
+ 1,
+ -1,
+ 127,
+ -12... | chia/_tests/wallet/test_clvm_casts.py | 26 | Python | 0.286 | suggestion | 93 | 51 | 51 | false | Migrate away from `clvm` imports | 19,730 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | matt-o-how |
blocks.reverse()
return blocks
async def autofarm_transaction(self, spend_name: bytes32) -> None:
if self.auto_farm:
self.log.info(f"Autofarm triggered by tx-id: {spend_name.hex()}")
new_block = FarmNewBlockProtocol(self.bt.farmer_ph)
await self.farm_new_... | Having this method in `CoinStoreProtocol` is a bad idea. We use an equivalent algorithm, also a bad idea, but at least contained to the simulator, limiting its potential damage. | blocks.reverse()
return blocks
async def autofarm_transaction(self, spend_name: bytes32) -> None:
if self.auto_farm:
self.log.info(f"Autofarm triggered by tx-id: {spend_name.hex()}")
new_block = FarmNewBlockProtocol(self.bt.farmer_ph)
await self.farm_new_... | @@ -123,7 +123,34 @@ async def update_autofarm_config(self, enable_autofarm: bool) -> bool:
return self.auto_farm
async def get_all_coins(self, request: GetAllCoinsProtocol) -> list[CoinRecord]:
- return await self.full_node.coin_store.get_all_coins(request.include_spent_coins) | chia/simulator/full_node_simulator.py | 26 | Python | 0.571 | suggestion | 177 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | richardkiss | richardkiss |
)
async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.high):
pending_tx = await self.mempool_manager.new_peak(self.blockchain.get_tx_peak(), None)
assert len(pending_tx.items) == 0 # no pending transactions when star... | The local `mypy` caught this subtle problem (`exit_stack` is already typed in an incompatible way in this scope). | state_change_summary = StateChangeSummary(peak, uint32(max(peak.height - 1, 0)), [], [], [], [])
# Must be called under priority_mutex
ppp_result: PeakPostProcessingResult = await self.peak_post_processing(
full_peak, state_change_summa... | @@ -350,9 +357,9 @@ async def manage(self) -> AsyncIterator[None]:
self.initialized = True
try:
- async with contextlib.AsyncExitStack() as exit_stack:
+ async with contextlib.AsyncExitStack() as aexit_stack: | chia/full_node/full_node.py | 26 | Python | 0.643 | suggestion | 113 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | richardkiss | richardkiss |
log_coins=log_coins,
)
self._mempool_manager = MempoolManager(
get_coin_records=self.coin_store.get_coin_records,
get_unspent_lineage_info_for_puzzle_hash=self.coin_store.get_unspent_lineage_info_for_puzzle_hash,
consensus_constant... | The `.num_unspent` API is badly named and ill-conceived since a count could take a very long time depending on the specifics of the storage mechanism, and is not actually needed for any genuine purpose, so requiring it in the protocol applies an unnecessary constraint. We use a local function that more or less provides... | single_threaded=single_threaded,
)
# Transactions go into this queue from the server, and get sent to respond_transaction
self._transaction_queue = TransactionQueue(1000, self.log)
self._transaction_queue_task: asyncio.Task[None] = create_referenced_task(... | @@ -306,10 +314,9 @@ async def manage(self) -> AsyncIterator[None]:
peak: Optional[BlockRecord] = self.blockchain.get_peak()
if peak is None:
self.log.info(f"Initialized with empty blockchain time taken: {int(time_taken)}s")
- num_unspent = await self.coin_store... | chia/full_node/full_node.py | 26 | Python | 0.643 | bug | 446 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | richardkiss | richardkiss |
async def get_coin_record(self, coin_id: bytes32) -> Optional[CoinRecord]:
"""
Returns the coin record for the specified coin id
"""
async def get_coin_records(self, coin_ids: Collection[bytes32]) -> list[CoinRecord]:
"""
Returns the coin records for the specified coin i... | Nothing is done with these values so it is a bit misleading to specify them here. I believe the `Ellipses` object is the common filler to say that a default must be provided by implementations.
```suggestion
start_height: uint32 = ...,
end_height: uint32 = ...,
``` | async def get_coin_record(self, coin_id: bytes32) -> Optional[CoinRecord]:
"""
Returns the coin record for the specified coin id
"""
async def get_coin_records(self, coin_ids: Collection[bytes32]) -> list[CoinRecord]:
"""
Returns the coin records for the specified coin i... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.786 | suggestion | 288 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
"""
Returns the coins added at a specific height
"""
async def get_coins_removed_at_height(self, height: uint32) -> list[CoinRecord]:
"""
Returns the coins removed at a specific height
"""
async def get_coin_records_by_puzzle_hash(
self,
include_... | ```suggestion
start_height: uint32 = ...,
end_height: uint32 = ...,
``` | """
Returns the coins added at a specific height
"""
async def get_coins_removed_at_height(self, height: uint32) -> list[CoinRecord]:
"""
Returns the coins removed at a specific height
"""
async def get_coin_records_by_puzzle_hash(
self,
include_... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.571 | suggestion | 90 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
include_spent_coins: bool,
puzzle_hash: bytes32,
start_height: uint32 = uint32(0),
end_height: uint32 = uint32((2**32) - 1),
) -> list[CoinRecord]:
"""
Returns the coin records for a specific puzzle hash
"""
async def get_coin_records_by_puzzle_hashes(
... | ```suggestion
start_height: uint32 = ...,
end_height: uint32 = ...,
``` | include_spent_coins: bool,
puzzle_hash: bytes32,
start_height: uint32 = ...,
end_height: uint32 = ...,
) -> list[CoinRecord]:
"""
Returns the coin records for a specific puzzle hash
"""
async def get_coin_records_by_puzzle_hashes(
self,
co... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.571 | suggestion | 90 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
puzzle_hashes: list[bytes32],
start_height: uint32 = uint32(0),
end_height: uint32 = uint32((2**32) - 1),
) -> list[CoinRecord]:
"""
Returns the coin records for a list of puzzle hashes
"""
async def get_coin_records_by_names(
self,
include_spent_... | ```suggestion
max_items: int = ...,
``` | puzzle_hashes: list[bytes32],
start_height: uint32 = ...,
end_height: uint32 = ...,
) -> list[CoinRecord]:
"""
Returns the coin records for a list of puzzle hashes
"""
async def get_coin_records_by_names(
self,
include_spent_coins: bool,
n... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.429 | suggestion | 49 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
names: list[bytes32],
start_height: uint32 = uint32(0),
end_height: uint32 = uint32((2**32) - 1),
) -> list[CoinRecord]:
"""
Returns the coin records for a list of coin names
"""
async def get_coin_states_by_puzzle_hashes(
self,
include_spent_coin... | ```suggestion
start_height: uint32 = ...,
end_height: uint32 = ...,
``` | names: list[bytes32],
start_height: uint32 = ...,
end_height: uint32 = ...,
) -> list[CoinRecord]:
"""
Returns the coin records for a list of coin names
"""
async def get_coin_states_by_puzzle_hashes(
self,
include_spent_coins: bool,
puzzl... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.571 | suggestion | 90 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
*,
max_items: int = 50000,
) -> set[CoinState]:
"""
Returns the coin states for a set of puzzle hashes
"""
async def get_coin_records_by_parent_ids(
self,
include_spent_coins: bool,
parent_ids: list[bytes32],
start_height: uint32 = uint32(... | ```suggestion
max_height: uint32 = ...,
max_items: int = ...,
``` | *,
max_items: int = ...,
) -> set[CoinState]:
"""
Returns the coin states for a set of puzzle hashes
"""
async def get_coin_records_by_parent_ids(
self,
include_spent_coins: bool,
parent_ids: list[bytes32],
start_height: uint32 = ...,
... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.571 | suggestion | 84 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
Returns the coin records for a list of parent ids
"""
async def get_coin_states_by_ids(
self,
include_spent_coins: bool,
coin_ids: Collection[bytes32],
min_height: uint32 = uint32(0),
*,
max_height: uint32 = uint32.MAXIMUM,
max_items: int = 50... | ```suggestion
min_height: uint32 = ...,
include_spent: bool = ...,
include_unspent: bool = ...,
include_hinted: bool = ...,
min_amount: uint64 = ...,
max_items: int = ...,
``` | Returns the coin records for a list of parent ids
"""
async def get_coin_states_by_ids(
self,
include_spent_coins: bool,
coin_ids: Collection[bytes32],
min_height: uint32 = uint32(0),
*,
max_height: uint32 = ...,
max_items: int = ...,
) ->... | @@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import Collection
+from typing import Optional, Protocol
+
+from chia_rs import CoinState
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia.types.blockchain_format.coin import Coin
+from chia... | chia/consensus/coin_store_protocol.py | 26 | Python | 0.786 | suggestion | 230 | 41 | 47 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
signage_point_times=[time.time() for _ in range(consensus_constants.NUM_SPS_SUB_SLOT)],
full_node_store=FullNodeStore(consensus_constants),
log=logging.getLogger(name),
db_path=db_path,
wallet_sync_queue=asyncio.Queue(),
)
@contextlib.asynccontext... | What about adding a `.empty()` or such method to the coin store and protocol itself? | signage_point_times=[time.time() for _ in range(consensus_constants.NUM_SPS_SUB_SLOT)],
full_node_store=FullNodeStore(consensus_constants),
log=logging.getLogger(name),
db_path=db_path,
wallet_sync_queue=asyncio.Queue(),
)
@contextlib.asynccontext... | @@ -212,6 +213,13 @@ async def manage(self) -> AsyncIterator[None]:
# These many respond_transaction tasks can be active at any point in time
self._add_transaction_semaphore = asyncio.Semaphore(200)
+ async def coin_store_seems_nonempty() -> bool:
+ for h in range(50):
+ ... | chia/full_node/full_node.py | 26 | Python | 0.357 | question | 84 | 51 | 51 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
@pyt... | if you would move this line to after line 22, you could remove this test and save some verbosity | from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | @@ -0,0 +1,36 @@
+from __future__ import annotations
+
+import pytest
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia._tests.util.db_connection import DBConnection
+from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
+from chia.full_node.coin_sto... | chia/_tests/core/consensus/stores/test_coin_store_protocol.py | 19 | Python | 0.286 | refactor | 96 | 37 | 41 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | richardkiss |
from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
@pyt... | `db_version` is a fixture, right? what does it mean to have a default value? | from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | @@ -0,0 +1,36 @@
+from __future__ import annotations
+
+import pytest
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia._tests.util.db_connection import DBConnection
+from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
+from chia.full_node.coin_sto... | chia/_tests/core/consensus/stores/test_coin_store_protocol.py | 20 | Python | 0.357 | question | 76 | 37 | 41 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | richardkiss |
from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
@pyt... | there is another test file to test `CoinStore`, why is this one (new) method tested in this file?
The name suggests that it's testing the *protocol*, but it's not. It's testing the concrete type, `CoinStore`. | from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | chia/_tests/core/consensus/stores/test_coin_store_protocol.py | 1 | Python | 0.714 | suggestion | 209 | 26 | 26 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | richardkiss | |
from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
@pyt... | remove the default here as well | from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | @@ -0,0 +1,36 @@
+from __future__ import annotations
+
+import pytest
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia._tests.util.db_connection import DBConnection
+from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
+from chia.full_node.coin_sto... | chia/_tests/core/consensus/stores/test_coin_store_protocol.py | 13 | Python | 0.143 | suggestion | 31 | 37 | 38 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | this seems to be a duplication of the existing fixture. duplicating would defeat what i believe is it's purpose of having a single place to define a new db version to be tested against and then having all relevant tests parametried accordingly.
https://github.com/Chia-Network/chia-blockchain/blob/f782fa8341cf6caa2d... | from __future__ import annotations
import pytest
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from chia._tests.util.db_connection import DBConnection
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
from chia.full_node.coin_store import CoinStore
# bla... | @@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import pytest
+from chia_rs.sized_bytes import bytes32
+from chia_rs.sized_ints import uint32, uint64
+
+from chia._tests.util.db_connection import DBConnection
+from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
+from chia.full_node.coin_sto... | chia/_tests/core/consensus/stores/test_coin_store_protocol.py | 19 | Python | 0.786 | suggestion | 398 | 44 | 41 | false | Create `CoinStoreProtocol` to remove a dependencies on `chia.full_node` from `chia.consensus` | 19,741 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | richardkiss |
"""
db_path_replaced: Path = root_path / config["full_node"]["database_path"]
db_directory: Path = path_from_root(root_path, db_path_replaced).parent
selected_network: str = config["full_node"]["selected_network"]
suffix = "" if (selected_network is None or selected_network == "mainnet") else f"-{se... | ```suggestion
height_to_hash_filename: Path = get_height_to_hash_filename(root_path, config)
async with aiofiles.open(height_to_hash_filename, "rb") as f:
return await f.read()
```
Since you don't really need to modify the height-to-hash, keeping it as `bytes` is fine | """
db_path_replaced: Path = root_path / config["full_node"]["database_path"]
db_directory: Path = path_from_root(root_path, db_path_replaced).parent
selected_network: str = config["full_node"]["selected_network"]
suffix = "" if (selected_network is None or selected_network == "mainnet") else f"-{se... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.786 | suggestion | 291 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
time_per_block = time_taken / (end_segment - last_status_height)
print(
f"Time taken for segment"
f" {last_status_height} to {end_segment}: {time_taken:.2f} seconds\n"
f"Average time per block: {time_per_block:.4f} seconds"
... | ```suggestion
if __name__ == "__main__":
cli()
```
Is there a good reason to have an extra indirection? |
for i in range(start_height, end_height + 1):
add_tasks_for_height(height=i)
# Make Status Updates.
if len(pipeline) >= pipeline_depth:
done, pipeline = await asyncio.wait(pipeline, return_when=asyncio.FIRST_COMPLETED)
completed_requests += le... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.714 | question | 113 | 27 | 33 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
"--block_spends",
help="Test get_block_spends",
is_flag=True,
type=bool,
default=False,
)
@click.option(
"-ar",
"--additions_and_removals",
help="Test get_additions_and_removals",
is_flag=True,
type=bool,
default=False,
)
@click.option(
"-s",
"--start-height",
hel... | as I understand it, the only thing you need from the config is the `height-to-hash`. you could just take a path to this file and keep things simple. It's not a bit deal since you've already made it be pulled from config, it's just another moving part that can break in the future | type=bool,
default=False,
)
@click.option(
"-s",
"--start-height",
help="Start height for the RPC calls",
type=int,
default=None,
)
@click.option(
"-e",
"--end-height",
help="End height for the RPC calls",
type=int,
default=None,
)
@click.option(
"-r",
"--pipeline... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.643 | suggestion | 279 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
end_height=end_height,
concurrent_requests=concurrent_requests,
)
)
async def cli_async(
root_path: Path,
rpc_port: Optional[int],
spends_with_conditions: bool,
block_spends: bool,
additions_and_removals: bool,
concurrent_requests: int,
start_height: int... | ```suggestion
# Peak height is required for the cache.
``` | if result is None:
print(f"ERROR: [{height}] get_block_spends_with_conditions returned invalid result")
async def node_block_spends(
node_client: FullNodeRpcClient,
block_hash: bytes32,
height: int,
) -> None:
result = await node_client.get_block_spends(block_hash)
if result is None:
... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.571 | performance | 72 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
from typing import Any, Optional
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import FullNodeRpcClient
from chia.util.default_root import resolve_root_path
from chia.util.path import path_from_root
... | calling this `block_cache` is a bit misleading I think. In the node we refer to it as height-to-hash |
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import FullNodeRpcClient
from chia.util.default_root import resolve_root_path
from chia.util.path import path_from_root
from chia.util.task_referencer im... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.5 | performance | 100 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
selected_network: str = config["full_node"]["selected_network"]
suffix = "" if (selected_network is None or selected_network == "mainnet") else f"-{selected_network}"
return db_directory / f"height-to-hash{suffix}"
async def get_block_cache_bytearray(root_path: Path, config: dict[str, Any], peak: int) -> ... | ```suggestion
def get_block_hash_from_height(height: int, height_to_hash: bytearray) -> bytes32:
``` | selected_network: str = config["full_node"]["selected_network"]
suffix = "" if (selected_network is None or selected_network == "mainnet") else f"-{selected_network}"
return db_directory / f"height-to-hash{suffix}"
async def get_height_to_hash_bytes(root_path: Path, config: dict[str, Any]) -> bytes:
"... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.714 | suggestion | 102 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
peak_height = blockchain_state["peak"].height
assert peak_height is not None, "Blockchain peak height is None"
if end_height is None:
end_height = blockchain_state["peak"]["height"]
print("Connected to Full Node")
block_cache_bytearray: bytearray = await get_block_c... | I was going to suggest using `TaskGroup` here, as a context manager it would make this a lot cleaner. But I suppose that requires python 3.11. That might be fine for a test utility though | block_spends: bool,
additions_and_removals: bool,
pipeline_depth: int,
start_height: int,
end_height: Optional[int] = None,
) -> None:
async with get_any_service_client(FullNodeRpcClient, root_path, rpc_port) as (
node_client,
config,
):
blockchain_state: dict[str, An... | @@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.5 | refactor | 187 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
print("No blockchain found. Exiting.")
return
peak_height = blockchain_state["peak"].height
assert peak_height is not None, "Blockchain peak height is None"
if end_height is None:
end_height = blockchain_state["peak"]["height"]
print("Connected to Ful... | it's not a big deal, but by making requests in batches, and then wait for all of them before issuing the next batch, you actually stall the pipeline and will likely be a lot slower than if you would just "stream" the requests. i.e. make sure there are `concurrent_requests` tasks in the pipeline at any given time. Inste... | node_client: FullNodeRpcClient,
block_hash: bytes32,
height: int,
) -> None:
response = await node_client.get_additions_and_removals(block_hash)
if response is None:
print(f"ERROR: [{height}] get_additions_and_removals returned invalid result")
async def cli_async(
root_path: Path,
... | @@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.643 | performance | 418 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
async def cli_async(
root_path: Path,
rpc_port: Optional[int],
spends_with_conditions: bool,
block_spends: bool,
additions_and_removals: bool,
concurrent_requests: int,
start_height: int,
end_height: Optional[int] = None,
) -> None:
blocks_per_status: int = 3000
last_status_heigh... | ```suggestion
end_height = blockchain_state["peak"].height
``` | node_client: FullNodeRpcClient,
block_hash: bytes32,
height: int,
) -> None:
result = await node_client.get_block_spends_with_conditions(block_hash)
if result is None:
print(f"ERROR: [{height}] get_block_spends_with_conditions returned invalid result")
async def node_block_spends(
node... | @@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.571 | suggestion | 76 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
help="Number of concurrent requests to make to the RPC endpoints",
type=int,
default=DEFAULT_REQUESTS_PER_BATCH,
)
def cli(
root_path: str,
rpc_port: Optional[int],
spends_with_conditions: bool,
block_spends: bool,
additions_and_removals: bool,
concurrent_requests: int,
start_hei... | ```suggestion
concurrent_requests = max(concurrent_requests, requests_per_batch)
```
I'm not sure what you intended by this division, but I imagine you'd want a lower cap on the batch-size | help="Set the number of concurrent RPC calls to make.",
type=int,
default=DEFAULT_PIPELINE_DEPTH,
)
def cli(
root_path: str,
rpc_port: Optional[int],
spends_with_conditions: bool,
block_spends: bool,
additions_and_removals: bool,
pipeline_depth: int,
start_height: Optional[int] =... | @@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import g... | tools/validate_rpcs.py | 26 | Python | 0.714 | performance | 195 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
assert (await client.get_block_record_by_height(100)) is None
# NOTE: indexing and hard coded values below depend on the ordering
included_reward_coins = sorted(blocks[-1].get_included_reward_coins(), key=lambda c: c.amount)
ph = included_reward_coins[0].puzzle_hash
coins = aw... | I think you should undo this before we land |
assert (await client.get_block_record_by_height(100)) is None
# NOTE: indexing and hard coded values below depend on the ordering
included_reward_coins = sorted(blocks[-1].get_included_reward_coins(), key=lambda c: c.amount)
ph = included_reward_coins[0].puzzle_hash
coins = aw... | @@ -118,7 +118,9 @@ async def test1(
print(coins)
assert len(coins) == 2
- additions, removals = await client.get_additions_and_removals(blocks[-1].header_hash)
+ result = await client.get_additions_and_removals(blocks[-1].header_hash)
+ assert result is not None
+ additi... | chia/_tests/core/test_full_node_rpc.py | 26 | Python | 0.143 | suggestion | 43 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
result = await self.fetch("get_aggsig_additional_data", {})
return bytes32.from_hexstr(result["additional_data"])
async def get_coin_records_by_hint(
self,
hint: bytes32,
include_spent_coins: bool = True,
start_height: Optional[int] = None,
end_height: Option... | I see. The RPC client swallows errors. I think a better solution would be to not catch the exception here, and let it propagate to the caller | result = await self.fetch("get_aggsig_additional_data", {})
return bytes32.from_hexstr(result["additional_data"])
async def get_coin_records_by_hint(
self,
hint: bytes32,
include_spent_coins: bool = True,
start_height: Optional[int] = None,
end_height: Option... | @@ -176,11 +176,13 @@ async def get_coin_records_by_hint(
response = await self.fetch("get_coin_records_by_hint", d)
return [CoinRecord.from_json_dict(coin_record_dict_backwards_compat(coin)) for coin in response["coin_records"]]
- async def get_additions_and_removals(self, header_hash: bytes32) ... | chia/full_node/full_node_rpc_client.py | 26 | Python | 0.571 | suggestion | 141 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
#!/usr/bin/env python3
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Optional
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import F... | this should probably not be called "batch". This technique is typically called "pipelining", so this could be either "concurrent requests", "requests in flight" or "pipeline depth" or something like that.
Also, this should be 5, or something in that vicinity. 25000 is too many and is the reason you see request timeo... | #!/usr/bin/env python3
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Optional
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import F... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 20 | Python | 0.5 | performance | 323 | 45 | 45 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
def add_tasks_for_height(height: int) -> None:
block_header_hash = get_block_hash_from_height(height, height_to_hash_bytes)
# Create tasks for each RPC call based on the flags
if spends_with_conditions:
in_flight.add(
create_referenced_tas... | I think it would be simpler (and sufficient) to just print this every 5 seconds or so. i.e.
```suggestion
now = time.monotonic()
if cycle_start + 5 < now:
``` | pipeline.add(create_referenced_task(node_block_spends(node_client, block_header_hash, height)))
if additions_and_removals:
pipeline.add(create_referenced_task(node_additions_removals(node_client, block_header_hash, height)))
for i in range(start_height, end_height + ... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 26 | Python | 0.714 | suggestion | 194 | 51 | 36 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
async with get_any_service_client(FullNodeRpcClient, root_path, rpc_port) as (
node_client,
config,
):
blockchain_state: dict[str, Any] = await node_client.get_blockchain_state()
if blockchain_state is None or blockchain_state["peak"] is None:
# Peak height is require... | minor thing, but this should be:
```suggestion
cycle_start: float = time.monotonic()
``` | print("No blockchain found. Exiting.")
return
peak_height = blockchain_state["peak"].height
assert peak_height is not None, "Blockchain peak height is None"
if end_height is None:
end_height = peak_height
print("Connected to Full Node")
heigh... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 26 | Python | 0.643 | suggestion | 99 | 51 | 51 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
)
)
if block_spends:
in_flight.add(
create_referenced_task(node_block_spends(node_client, block_header_hash, height, repeat_list))
)
if additions_and_removals:
in_flight.add(
... | ```suggestion
cycle_start = now
``` | done, pipeline = await asyncio.wait(pipeline, return_when=asyncio.FIRST_COMPLETED)
completed_requests += len(done)
now = time.monotonic()
if cycle_start + 5 < now:
time_taken = now - cycle_start
print(
... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 26 | Python | 0.571 | suggestion | 57 | 51 | 28 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
completed_requests += len(done)
if completed_requests >= REQUESTS_PER_STATUS_UPDATE:
time_taken = time.time() - cycle_start
print(
f"Processed {completed_requests} RPCs in {time_taken:.2f}s, "
f"{time... | I don't think you should retry failed requests. That would only hide real problems | #!/usr/bin/env python3
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Optional
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import F... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 26 | Python | 0.286 | bug | 82 | 37 | 263 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
if additions_and_removals:
in_flight.add(
create_referenced_task(node_additions_removals(node_client, block_header_hash, height, repeat_list))
)
for i in range(start_height, end_height + 1):
add_tasks_for_height(height=i)
#... | I don't think you should retry failed blocks | #!/usr/bin/env python3
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Optional
import aiofiles
import click
from chia_rs.sized_bytes import bytes32
from chia.cmds.cmds_util import get_any_service_client
from chia.full_node.full_node_rpc_client import F... | @@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import aiofiles
+import click
+from chia_rs.sized_bytes import bytes32
+
+from chia.cmds.cmds_util import get_any_service_client
+from chia.full_n... | tools/validate_rpcs.py | 26 | Python | 0.143 | bug | 44 | 47 | 263 | false | CHIA-2638 Full Node RPC Validation Tool | 19,743 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | jack60612 |
pool_public_key=G1Element(),
pool_contract_puzzle_hash=bytes32(b"1" * 32),
expected_error="Plot size is lower than the minimum",
),
ProofOfSpaceCase(
id="v2 plot size 34",
pos_challenge=bytes32(b"1" * 32),
plot_size=uint8(0x80 | 34),
plot_public_key=G1Elem... | we should still have a case that is not 0 and is valid to check that we raise NotImplementedError | pool_contract_puzzle_hash=bytes32(b"1" * 32),
expected_error="Plot size is lower than the minimum",
),
ProofOfSpaceCase(
id="v2 plot size 34",
pos_challenge=bytes32(b"1" * 32),
plot_size=uint8(0x80 | 34),
plot_public_key=G1Element(),
pool_public_key=G1Elem... | @@ -157,16 +157,17 @@ def test_verify_and_get_quality_string_v2(caplog: pytest.LogCaptureFixture, case
size = pos.size()
assert size.size_v2 is not None
assert size.size_v1 is None
- with pytest.raises(NotImplementedError):
- verify_and_get_quality_string(
- pos=pos,
- con... | chia/_tests/core/custom_types/test_proof_of_space.py | 26 | Python | 0.429 | suggestion | 97 | 51 | 51 | false | bump chia_rs to 0.26.0 | 19,746 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn |
)
def test_verify_and_get_quality_string_v2(caplog: pytest.LogCaptureFixture, case: ProofOfSpaceCase) -> None:
pos = ProofOfSpace(
challenge=case.pos_challenge,
pool_public_key=case.pool_public_key,
pool_contract_puzzle_hash=case.pool_contract_puzzle_hash,
plot_public_key=case.plot_p... | ```suggestion
except Exception as e:
assert case.expected_error is not None
assert case.expected_error in repr(e)
else:
assert case.expected_error is None
``` | )
def test_verify_and_get_quality_string_v2(caplog: pytest.LogCaptureFixture, case: ProofOfSpaceCase) -> None:
pos = ProofOfSpace(
challenge=case.pos_challenge,
pool_public_key=case.pool_public_key,
pool_contract_puzzle_hash=case.pool_contract_puzzle_hash,
plot_public_key=case.plot_p... | @@ -167,6 +174,11 @@ def test_verify_and_get_quality_string_v2(caplog: pytest.LogCaptureFixture, case
signage_point=bytes32.from_hexstr("0x7b3e23dbd438f9aceefa9827e2c5538898189987f49b06eceb7a43067e77b531"),
height=case.height,
)
+ assert quality_string is None
+ assert l... | chia/_tests/core/custom_types/test_proof_of_space.py | 26 | Python | 0.857 | suggestion | 196 | 49 | 50 | false | bump chia_rs to 0.26.0 | 19,746 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | arvidn |
async def farm_block(self, puzzle_hash: bytes32 = bytes32(b"0" * 32)) -> tuple[list[Coin], list[Coin]]:
# Fees get calculated
fees = uint64(0)
for item in self.mempool_manager.mempool.all_items():
fees = uint64(fees + item.fee)
# Rewards get created
next_block_he... | ```suggestion
additions = []
removals = []
```
It looks like you could just call this `additions` and have it be assigned if there is a block. | async def farm_block(self, puzzle_hash: bytes32 = bytes32(b"0" * 32)) -> tuple[list[Coin], list[Coin]]:
# Fees get calculated
fees = uint64(0)
for item in self.mempool_manager.mempool.all_items():
fees = uint64(fees + item.fee)
# Rewards get created
next_block_he... | @@ -258,7 +258,7 @@ async def farm_block(self, puzzle_hash: bytes32 = bytes32(b"0" * 32)) -> tuple[l
]
# Coin store gets updated
generator_bundle: Optional[SpendBundle] = None
- return_additions: list[Coin] = []
+ tx_additions = []
return_removals: list[Coin] = [] | chia/_tests/util/spend_sim.py | 26 | Python | 0.786 | suggestion | 164 | 51 | 51 | false | CHIA-3217 Simplify SpendSim's farm_block | 19,760 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
for quality_str, proof_of_space in proofs_of_space_and_q:
all_responses.append(
harvester_protocol.NewProofOfSpace(
new_challenge.challenge_hash,
new_challenge.sp_hash,
quality_str.hex() + str(filenam... | this should be the height of the latest peak not the last_tx_height | for quality_str, proof_of_space in proofs_of_space_and_q:
all_responses.append(
harvester_protocol.NewProofOfSpace(
new_challenge.challenge_hash,
new_challenge.sp_hash,
quality_str.hex() + str(filenam... | @@ -248,8 +249,11 @@ async def lookup_challenge(
# Passes the plot filter (does not check sp filter yet though, since we have not reached sp)
# This is being executed at the beginning of the slot
total += 1
+ filter_prefix_bits = uint8(
+ ... | chia/harvester/harvester_api.py | 26 | Python | 0.286 | suggestion | 67 | 51 | 51 | false | compute plot filter on the harvester | 19,765 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn |
@dataclass(frozen=True)
class ForkAdd:
coin: Coin
confirmed_height: uint32
timestamp: uint64
hint: Optional[bytes]
is_coinbase: bool
@dataclass(frozen=True)
class ForkRem:
puzzle_hash: bytes32
height: uint32
def update_fork_peak(fork_info: ForkInfo, block: FullBlock, header_hash: bytes32... | it looks like both of these should be member functions. is there a good reason to make them free? | @dataclass(frozen=True)
class ForkAdd:
coin: Coin
confirmed_height: uint32
timestamp: uint64
hint: Optional[bytes]
is_coinbase: bool
@dataclass(frozen=True)
class ForkRem:
puzzle_hash: bytes32
height: uint32
@dataclass
class ForkInfo:
# defines the last block shared by the fork and t... | @@ -56,6 +56,26 @@ class ForkRem:
height: uint32
+def update_fork_peak(fork_info: ForkInfo, block: FullBlock, header_hash: bytes32) -> None:
+ """Updates `fork_info` with `block`'s height and `header_hash`."""
+ assert fork_info.peak_height == block.height - 1
+ assert len(fork_info.block_hashes) == f... | chia/consensus/block_body_validation.py | 26 | Python | 0.286 | question | 97 | 51 | 51 | false | CHIA-3250 Unify fork peak and reward coins handling between ForkInfo's include_spends and include_block | 19,766 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | AmineKhaldi |
wpf = WeightProofHandler(
blockchain_constants, BlockchainMock(sub_blocks, header_cache, height_to_hash, summaries)
)
wpf_verify = WeightProofHandler(
blockchain_constants, BlockchainMock(sub_blocks, header_cache, height_to_hash, {})
)
for x in range(10, -... | i think all these tests need to move, how are they related to Weight Proofs ? | from __future__ import annotations
import pytest
from chia_rs import BlockRecord, ConsensusConstants, FullBlock, HeaderBlock, SubEpochSummary
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32
from chia._tests.util.blockchain_mock import BlockchainMock
from chia.consensus.full_block_to_bloc... | @@ -493,9 +493,12 @@ async def test_weight_proof_extend_multiple_ses(
@pytest.mark.parametrize("height,expected", [(0, 3), (5496000, 2), (10542000, 1), (15592000, 0), (20643000, 0)]) | chia/_tests/weight_proof/test_weight_proof.py | 26 | Python | 0.286 | question | 77 | 51 | 491 | false | Plot v2 quality string | 19,769 | Chia-Network/chia-blockchain | 10,822 | Python | almogdepaz | arvidn |
[],
[],
[],
0,
),
]
def test_tx_removals_and_additions() -> None:
conditions = SpendBundleConditions(
spends, uint64(0), uint32(0), uint64(0), None, None, [], uint64(0), 0, 0, False, 0, 0
)
expected_rems = [coin_ids[0], coin_ids[1]]
expected_additions = []
... | Do we not have this elsewhere that we can import?
I'd also suggest renaming it to make it more explicit that this is a malicious generator
```suggestion
# this is a malicious generator which should fail
``` | [],
[],
[],
0,
),
]
def test_tx_removals_and_additions() -> None:
conditions = SpendBundleConditions(
spends, uint64(0), uint32(0), uint64(0), None, None, [], uint64(0), 0, 0, False, 0, 0
)
expected_rems = [coin_ids[0], coin_ids[1]]
expected_additions = []
... | @@ -81,3 +86,23 @@ def test_tx_removals_and_additions() -> None:
def test_empty_conditions() -> None:
assert tx_removals_and_additions(None) == ([], [])
+
+ | chia/_tests/core/full_node/test_generator_tools.py | 26 | Python | 0.857 | bug | 212 | 45 | 46 | false | [CHIA-2639] drop spends we can't serialize rather than the whole request | 19,773 | Chia-Network/chia-blockchain | 10,822 | Python | matt-o-how | arvidn |
request.get("p2_singleton_delay_time", None),
delayed_address,
extra_conditions=extra_conditions,
)
except Exception as e:
raise ValueError(str(e))
... | feels like we shouldn't need to convert to json, modify, then back? | else: # undefined wallet_type
pass
# TODO: rework this function to report detailed errors for each error case
return {"success": False, "error": "invalid request"}
##########################################################################################
# Wallet
#####... | @@ -1297,22 +1302,21 @@ async def _get_wallet_balance(self, wallet_id: uint32) -> dict[str, Any]:
assert isinstance(wallet, CRCATWallet)
wallet_balance["pending_approval_balance"] = await wallet.get_pending_approval_balance()
- return wallet_balance
+ return BalanceResp... | chia/wallet/wallet_rpc_api.py | 26 | Python | 0.286 | question | 67 | 51 | 51 | false | [CHIA-3294] Port `get_wallet_balance(s)` to `@marshal` | 19,774 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | Quexington |
"pending_coin_removal_count": -1,
}
},
),
WalletStateTransition(
pre_block_balance_updates={},
post_block_balance_updates={},
),
]
)
... | maybe?
```suggestion
assert txs["transactions"][0]["metadata"]["coin_id"] == "0x" + merkle_coin.name().hex()
``` | "pending_coin_removal_count": -1,
}
},
),
WalletStateTransition(
pre_block_balance_updates={},
post_block_balance_updates={},
),
]
)
... | @@ -395,7 +395,7 @@ async def test_wallet_clawback_clawback(self, wallet_environments: WalletTestFra
assert len(txs["transactions"]) == 1
assert not txs["transactions"][0]["confirmed"]
assert txs["transactions"][0]["metadata"]["recipient_puzzle_hash"][2:] == normal_puzhash.hex()
- asse... | chia/_tests/wallet/test_wallet.py | 26 | Python | 0.714 | suggestion | 121 | 51 | 51 | false | [CHIA-3297] Port `get_transaction(s)` to `@marshal` | 19,775 | Chia-Network/chia-blockchain | 10,822 | Python | altendky | Quexington |
set_farmer_peer: str,
set_node_introducer: str,
set_fullnode_port: str,
set_harvester_port: str,
set_log_level: str,
enable_upnp: str,
set_outbound_peer_count: str,
set_peer_count: str,
testnet: str,
peer_connect_timeout: str,
crawler_db_path: str,
crawler_minimum_version... | ```suggestion
config["full_node"]["introducer_peer"]["port"] = port
config["introducer"]["port"] = port
```
I'm guessing `port` is already an `int` here, right? There are more places like this | set_farmer_peer: str,
set_node_introducer: str,
set_fullnode_port: str,
set_harvester_port: str,
set_log_level: str,
enable_upnp: str,
set_outbound_peer_count: str,
set_peer_count: str,
testnet: str,
peer_connect_timeout: str,
crawler_db_path: str,
crawler_minimum_version... | @@ -42,28 +43,20 @@ def configure(
change_made = False
if set_node_introducer:
try:
- if set_node_introducer.index(":"):
- host, port = (
- ":".join(set_node_introducer.split(":")[:-1]),
- set_node_introducer.... | chia/cmds/configure.py | 26 | Python | 0.786 | suggestion | 228 | 51 | 51 | false | ruff issues | 19,787 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | richardkiss |
# Map of coin ID to SpendConditions
spend_conditions = {bytes32(spend.coin_id): spend for spend in conds.spends}
if len(new_spend.coin_spends) != len(spend_conditions):
# if this happens, the SpendBundle doesn't match the
# SpendBundleConditions.
return Err.I... | Same thing here, the default value suggests that `eligibility_and_additions` may not have the coin ID in it. Which I think would be some internal error or an invalid `SpendBundle`. The new version fails with `Err.INVALID_SPEND_BUNDLE` if this happens | # Map of coin ID to SpendConditions
spend_conditions = {bytes32(spend.coin_id): spend for spend in conds.spends}
# if this happens, the SpendBundle doesn't match the
# SpendBundleConditions.
assert len(new_spend.coin_spends) == len(spend_conditions)
bundle_coin_spends: ... | @@ -584,60 +583,53 @@ async def validate_spend_bundle(
removal_names: set[bytes32] = set()
additions_dict: dict[bytes32, Coin] = {}
addition_amount: int = 0
- # Map of coin ID to eligibility information
- eligibility_and_additions: dict[bytes32, EligibilityAndAdditions] = {}
- ... | chia/full_node/mempool_manager.py | 26 | Python | 0.714 | bug | 250 | 51 | 51 | false | [CHIA-2827] simplify MempoolManager by removing EligibilityAndAdditions | 19,801 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | arvidn |
if self.peak is None:
return Err.MEMPOOL_NOT_INITIALIZED, None, []
cost = conds.cost
removal_names: set[bytes32] = set()
additions_dict: dict[bytes32, Coin] = {}
addition_amount: int = 0
# Map of coin ID to SpendConditions
spend_conditions = {bytes3... | There is an earlier check to this effect, so this is no longer possible and we can simplify this into an assert.
```suggestion
assert spend_conds is not None
``` | if self.peak is None:
return Err.MEMPOOL_NOT_INITIALIZED, None, []
cost = conds.cost
removal_names: set[bytes32] = set()
additions_dict: dict[bytes32, Coin] = {}
addition_amount: int = 0
# Map of coin ID to SpendConditions
spend_conditions = {bytes3... | @@ -584,60 +583,53 @@ async def validate_spend_bundle(
removal_names: set[bytes32] = set()
additions_dict: dict[bytes32, Coin] = {}
addition_amount: int = 0
- # Map of coin ID to eligibility information
- eligibility_and_additions: dict[bytes32, EligibilityAndAdditions] = {}
- ... | chia/full_node/mempool_manager.py | 26 | Python | 0.786 | refactor | 176 | 51 | 51 | false | [CHIA-2827] simplify MempoolManager by removing EligibilityAndAdditions | 19,801 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
addition_amount: int = 0
# Map of coin ID to SpendConditions
spend_conditions = {bytes32(spend.coin_id): spend for spend in conds.spends}
if len(new_spend.coin_spends) != len(spend_conditions):
# if this happens, the SpendBundle doesn't match the
# SpendBundleCo... | We can rename this now (here and below, when constructing `BundleCoinSpend`) to `eligible_for_fast_forward`.
```suggestion
eligible_for_fast_forward = bool(spend_conds.flags & ELIGIBLE_FOR_FF) and supports_fast_forward(coin_spend)
if eligible_for_fast_forward:
``` | addition_amount: int = 0
# Map of coin ID to SpendConditions
spend_conditions = {bytes32(spend.coin_id): spend for spend in conds.spends}
# if this happens, the SpendBundle doesn't match the
# SpendBundleConditions.
assert len(new_spend.coin_spends) == len(spend_conditi... | @@ -584,60 +583,53 @@ async def validate_spend_bundle(
removal_names: set[bytes32] = set()
additions_dict: dict[bytes32, Coin] = {}
addition_amount: int = 0
- # Map of coin ID to eligibility information
- eligibility_and_additions: dict[bytes32, EligibilityAndAdditions] = {}
- ... | chia/full_node/mempool_manager.py | 26 | Python | 0.857 | suggestion | 292 | 51 | 51 | false | [CHIA-2827] simplify MempoolManager by removing EligibilityAndAdditions | 19,801 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
if record is None:
# Fetch from DB
record = await self.service.blockchain.block_store.get_block_record(header_hash)
if record is None:
raise ValueError(f"Block {header_hash.hex()} does not exist")
records.append(record)
return ... | this looks suspicious. does the rust implementation really add the `block_spends` key? | if record is None:
# Fetch from DB
record = await self.service.blockchain.block_store.get_block_record(header_hash)
if record is None:
raise ValueError(f"Block {header_hash.hex()} does not exist")
records.append(record)
return ... | @@ -482,14 +481,19 @@ async def get_block_spends(self, request: dict[str, Any]) -> EndpointResult:
if full_block is None:
raise ValueError(f"Block {header_hash.hex()} not found")
- spends: list[CoinSpend] = []
+ spends: list[dict[str, list[CoinSpend]]] = []
block_generator... | chia/full_node/full_node_rpc_api.py | 26 | Python | 0.357 | question | 86 | 51 | 51 | false | Use chia_rs in API instead of clvm | 19,803 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | matt-o-how |
self.service.constants,
block_generator.program,
block_generator.generator_refs,
get_flags_for_height_and_constants(full_block.height, self.service.constants),
)
return spends[0]
async def get_block_spends_with_conditions(self, request: dict[str, Any... | do you end up hex encoding the arguments like we do currently? | self.service.constants,
block_generator.program,
block_generator.generator_refs,
get_flags_for_height_and_constants(full_block.height, self.service.constants),
)
# chia_rs returning a list is a mistake that will be fixed in the next release
# it o... | @@ -503,22 +507,13 @@ async def get_block_spends_with_conditions(self, request: dict[str, Any]) -> End
if block_generator is None: # if block is not a transaction block.
return {"block_spends_with_conditions": []}
- spends_with_conditions = get_spends_for_block_with_conditions(
- ... | chia/full_node/full_node_rpc_api.py | 26 | Python | 0.214 | question | 62 | 51 | 51 | false | Use chia_rs in API instead of clvm | 19,803 | Chia-Network/chia-blockchain | 10,822 | Python | arvidn | matt-o-how |
result = mempool.get_items_by_coin_ids(coin_ids)
assert set(result) == set(expected)
def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = False) -> SpendBundle:
conditions = []
actual_fee = fee
if with_higher_cost:
conditions.extend([[ConditionOpcode.CREATE_COIN,... | We can still return the saved cost to maintain the test intent. I addressed this as part of an addendum (PR #19816). | FeeRate(uint64(1000000)),
CLVMCost(test_constants.MAX_BLOCK_COST_CLVM),
)
return Mempool(mempool_info, fee_estimator)
def make_coin(idx: int) -> Coin:
return Coin(IDENTITY_PUZZLE_HASH, IDENTITY_PUZZLE_HASH, uint64(2_000_000_000 + idx * 2))
@pytest.mark.parametrize("old", [True, False])
d... | @@ -3135,15 +3134,11 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool =
def test_aggregating_on_a_solution_then_a_more_cost_saving_one_appears() -> None:
- def agg_and_add_sb_returning_cost_info(mempool: Mempool, spend_bundles: list[SpendBundle]) -> uint64:
+ def agg_and_add_s... | chia/_tests/core/mempool/test_mempool.py | 26 | Python | 0.357 | suggestion | 116 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
def test_aggregating_on_a_solution_then_a_more_cost_saving_one_appears() -> None:
def agg_and_add_sb_returning_cost_info(mempool: Mempool, spend_bundles: list[SpendBundle]) -> None:
sb = SpendBundle.aggregate(spend_bundles)
mi = mempool_item_from_spendbundle(sb)
mempool.add_to_pool(mi)
... | We can still have this as a result of the above (already addressed). | """
mempool = construct_mempool()
def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None:
sb = SpendBundle.aggregate(spend_bundles)
mi = mempool_item_from_spendbundle(sb)
mempool.add_to_pool(mi)
invariant_check_mempool(mempool)
DEDUP_COIN = make_coin(0)
COI... | @@ -3163,7 +3158,7 @@ def agg_and_add_sb_returning_cost_info(mempool: Mempool, spend_bundles: list[Spe
invariant_check_mempool(mempool)
# Create a ~2 FPC item that spends the eligible coin using the same solution A
sb_low_rate = make_test_spendbundle(coins[2], fee=highest_fee // 5)
- saved_cost_on_sol... | chia/_tests/core/mempool/test_mempool.py | 26 | Python | 0.214 | suggestion | 68 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
invariant_check_mempool(mempool)
# Create a ~2 FPC item that spends the eligible coin using the same solution A
sb_low_rate = make_test_spendbundle(coins[2], fee=highest_fee // 5)
agg_and_add_sb_returning_cost_info(mempool, [sb_A, sb_low_rate])
invariant_check_mempool(mempool)
result = mempool.c... | Same here (addressed in addendum). |
create_block = mempool.create_block_generator if old else mempool.create_block_generator2
# validate that dedup happens at all for sb_A
result = create_block(test_constants, uint32(0), 5.0)
assert result is not None
# Make sure both items would be processed
assert result.removals == [DEDUP_COIN... | @@ -3177,10 +3172,8 @@ def agg_and_add_sb_returning_cost_info(mempool: Mempool, spend_bundles: list[Spe
# We're picking this fee to get a ~3 FPC, and get picked after sb_A1
# (which has ~10 FPC) but before sb_A2 (which has ~2 FPC)
sb_mid_rate = make_test_spendbundle(coins[i], fee=38004852 - i... | chia/_tests/core/mempool/test_mempool.py | 26 | Python | 0.071 | suggestion | 34 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
# 10000 that's 300000
(make_test_conds(seconds_absolute=20000, seconds_relative=20000), expect(seconds=30000)),
# Same thing but without the absolute seconds
(make_test_conds(seconds_relative=20000), expect(seconds=30000)),
],
)
def test_compute_assert_height(conds: SpendBundleCondit... | This is unrelated to the patch, it resulted from an unrelated change below to `add_spendbundle`'s failure path. I've addressed this as well in the addendum. | # 10000 that's 300000
(make_test_conds(seconds_absolute=20000, seconds_relative=20000), expect(seconds=30000)),
# Same thing but without the absolute seconds
(make_test_conds(seconds_relative=20000), expect(seconds=30000)),
],
)
def test_compute_assert_height(conds: SpendBundleCondit... | @@ -535,7 +534,7 @@ def spend_bundle_from_conditions(
async def add_spendbundle(
mempool_manager: MempoolManager, sb: SpendBundle, sb_name: bytes32
-) -> tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]:
+) -> tuple[uint64, MempoolInclusionStatus, Optional[Err]]: | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.571 | bug | 156 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
assert compute_assert_height(coin_records, conds) == expected
def spend_bundle_from_conditions(
conditions: list[list[Any]], coin: Coin = TEST_COIN, aggsig: G2Element = G2Element()
) -> SpendBundle:
solution = SerializedProgram.to(conditions)
coin_spend = make_spend(coin, IDENTITY_PUZZLE, solution)
... | Same here as above (already addressed in addendum). | assert compute_assert_height(coin_records, conds) == expected
def spend_bundle_from_conditions(
conditions: list[list[Any]], coin: Coin = TEST_COIN, aggsig: G2Element = G2Element()
) -> SpendBundle:
solution = SerializedProgram.to(conditions)
coin_spend = make_spend(coin, IDENTITY_PUZZLE, solution)
... | @@ -547,7 +546,7 @@ async def generate_and_add_spendbundle(
conditions: list[list[Any]],
coin: Coin = TEST_COIN,
aggsig: G2Element = G2Element(),
-) -> tuple[SpendBundle, bytes32, tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]]:
+) -> tuple[SpendBundle, bytes32, tuple[uint64, MempoolInclu... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.214 | suggestion | 51 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
sb = spend_bundle_from_conditions(conditions)
with pytest.raises(ValidationError, match="MINTING_COIN"):
await mempool_manager.pre_validate_spendbundle(sb)
@pytest.mark.anyio
async def test_reserve_fee_condition() -> None:
mempool_manager = await instantiate_mempool_manager(zero_calls_get_coin_rec... | Same here as above (already addressed in addendum). | conditions = [[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT + 1]]
sb = spend_bundle_from_conditions(conditions)
with pytest.raises(ValidationError, match="MINTING_COIN"):
await mempool_manager.pre_validate_spendbundle(sb)
@pytest.mark.anyio
async def test_reserve_fee_conditi... | @@ -703,7 +703,7 @@ async def get_coin_records(_: Collection[bytes32]) -> list[CoinRecord]:
mempool_manager = await instantiate_mempool_manager(get_coin_records)
conditions = [[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, 1]]
_, _, result = await generate_and_add_spendbundle(mempool_manager, condit... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.214 | suggestion | 51 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
assert unique_additions == [Coin(TEST_COIN_ID, IDENTITY_PUZZLE_HASH, uint64(1))]
assert dedup_coin_spends == IdenticalSpendDedup()
def test_dedup_info_eligible_1st_time() -> None:
# Eligible coin encountered for the first time
conditions = [
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, ... | I sent a clarification on this magic number. | assert cost_saving == 0
assert unique_additions == [Coin(TEST_COIN_ID, IDENTITY_PUZZLE_HASH, uint64(1))]
assert dedup_coin_spends == IdenticalSpendDedup()
def test_dedup_info_eligible_1st_time() -> None:
# Eligible coin encountered for the first time
conditions = [
[ConditionOpcode.CREATE_... | @@ -1636,7 +1622,9 @@ def test_dedup_info_eligible_1st_time() -> None:
Coin(TEST_COIN_ID, IDENTITY_PUZZLE_HASH, uint64(1)),
Coin(TEST_COIN_ID, IDENTITY_PUZZLE_HASH, uint64(TEST_COIN_AMOUNT - 1)),
}
- assert dedup_coin_spends == IdenticalSpendDedup({TEST_COIN_ID: DedupCoinSpend(solution=solutio... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.071 | suggestion | 44 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
# Eligible coin but different solution from the one we encountered
initial_conditions = [
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, 1],
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT],
]
initial_solution = SerializedProgram.to(initial_conditions)
dedup... | I sent a clarification on this. |
def test_dedup_info_eligible_but_different_solution() -> None:
# Eligible coin but different solution from the one we encountered
initial_conditions = [
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, 1],
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT],
]
initi... | @@ -1663,7 +1651,9 @@ def test_dedup_info_eligible_2nd_time_and_another_1st_time() -> None:
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT - 1],
]
initial_solution = SerializedProgram.to(initial_conditions)
- dedup_coin_spends = IdenticalSpendDedup({TEST_COIN_ID: DedupCoinSpe... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.071 | suggestion | 31 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
[ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT - 1],
]
initial_solution = SerializedProgram.to(initial_conditions)
dedup_coin_spends = IdenticalSpendDedup(
{TEST_COIN_ID: DedupCoinSpend(solution=initial_solution, cost=uint64(1337))}
)
sb1 = spend_bundle_from_con... | I sent a clarification on these numbers. | [ConditionOpcode.CREATE_COIN, IDENTITY_PUZZLE_HASH, TEST_COIN_AMOUNT - 1],
]
initial_solution = SerializedProgram.to(initial_conditions)
test_coin_cost = uint64(1337)
dedup_coin_spends = IdenticalSpendDedup(
{TEST_COIN_ID: DedupCoinSpend(solution=initial_solution, cost=test_coin_cost)}
... | @@ -1676,15 +1666,14 @@ def test_dedup_info_eligible_2nd_time_and_another_1st_time() -> None:
)
# Only the eligible one that we encountered more than once gets deduplicated
assert unique_coin_spends == sb2.coin_spends
- saved_cost = uint64(3600044)
- assert cost_saving == saved_cost
+ assert cos... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.071 | suggestion | 40 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
@pytest.mark.anyio
async def test_bundle_coin_spends() -> None:
# This tests the construction of bundle_coin_spends map for mempool items
# We're creating sb123e with 4 coins, one of them being eligible
mempool_manager, coins = await setup_mempool_with_coins(coin_amounts=list(range(1000000000, 1000000005))... | I sent a clarification on these numbers. | assert mempool_manager.mempool.size() == 0
assert len(list(mempool_manager.mempool.items_by_feerate())) == 0
@pytest.mark.anyio
async def test_bundle_coin_spends() -> None:
# This tests the construction of bundle_coin_spends map for mempool items
# We're creating sb123e with 4 coins, one of them being... | @@ -1805,12 +1794,14 @@ async def test_bundle_coin_spends() -> None:
eligible_for_dedup=False,
eligible_for_fast_forward=False,
additions=[Coin(coins[i].name(), IDENTITY_PUZZLE_HASH, coins[i].amount)],
+ cost=uint64(3000044),
)
assert mi123e.bundle_coin_sp... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.071 | suggestion | 40 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
test_coin_records[coin.name()] = CoinRecord(coin, uint32(20), uint32(0), False, uint64(2000))
async def get_coin_records(coin_ids: Collection[bytes32]) -> list[CoinRecord]:
ret: list[CoinRecord] = []
for name in coin_ids:
r = test_coin_records.get(name)
if r is not None:... | This is unrelated to the patch (addressed in the addendum), it's a result of altering `add_spendbundle`'s failure path. | coins.append(coin)
test_coin_records[coin.name()] = CoinRecord(coin, uint32(10), uint32(0), False, uint64(1000))
coin = Coin(IDENTITY_PUZZLE_HASH, IDENTITY_PUZZLE_HASH, uint64(2))
coins.append(coin)
test_coin_records[coin.name()] = CoinRecord(coin, uint32(20), uint32(0), False, uint64(2000))
as... | @@ -2162,7 +2153,7 @@ async def get_coin_records(coin_ids: Collection[bytes32]) -> list[CoinRecord]:
result = await add_spendbundle(mempool_manager, bundle, bundle_name)
print(result)
if expected is not None:
- assert result == (None, MempoolInclusionStatus.FAILED, expected)
+ ... | chia/_tests/core/mempool/test_mempool_manager.py | 26 | Python | 0.5 | bug | 119 | 51 | 51 | false | use per-puzzle cost to estimate DEDUP savings | 19,811 | Chia-Network/chia-blockchain | 10,822 | Python | AmineKhaldi | arvidn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.