Skip to content

Commit 6936950

Browse files
committed
Merge commit 'a8a30e3541a9074e2e5ca85e7869c90f61448b8b' into catchup/long_lived_datalayer_merkle_blob_from_main_a8a30e3541a9074e2e5ca85e7869c90f61448b8b
2 parents 76374b0 + a8a30e3 commit 6936950

File tree

221 files changed

+1859
-1331
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

221 files changed

+1859
-1331
lines changed
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
from __future__ import annotations
2+
3+
import asyncio
4+
import io
5+
import random
6+
import tempfile
7+
import time
8+
from datetime import datetime
9+
from ipaddress import IPv4Address
10+
from pathlib import Path
11+
12+
import aiofiles
13+
from chia_rs.sized_ints import uint16, uint64
14+
15+
from chia.server.address_manager import (
16+
NEW_BUCKETS_PER_ADDRESS,
17+
AddressManager,
18+
ExtendedPeerInfo,
19+
)
20+
from chia.types.peer_info import TimestampedPeerInfo
21+
from chia.util.files import write_file_async
22+
23+
24+
def generate_random_ip(rand: random.Random) -> str:
25+
return str(IPv4Address(rand.getrandbits(32)))
26+
27+
28+
def populate_address_manager(num_new: int = 500000, num_tried: int = 200000) -> AddressManager:
29+
rand = random.Random()
30+
rand.seed(1337)
31+
am = AddressManager()
32+
current_time = int(datetime.now().timestamp())
33+
total = num_new + num_tried
34+
35+
for i in range(total):
36+
host = generate_random_ip(rand)
37+
port = rand.randint(1024, 65535)
38+
timestamp = current_time - rand.randint(0, 100000)
39+
40+
# Construct TimestampedPeerInfo
41+
tpi = TimestampedPeerInfo(host=host, port=uint16(port), timestamp=uint64(timestamp))
42+
43+
# Create the ExtendedPeerInfo
44+
epi = ExtendedPeerInfo(
45+
addr=tpi,
46+
src_peer=None, # will default to itself inside constructor
47+
)
48+
49+
am.tried_count += 1 # why do we even have `assert tried_ids != tried_count`?
50+
node_id = am.id_count
51+
am.id_count += 1
52+
epi.random_pos = len(am.random_pos)
53+
am.map_info[node_id] = epi
54+
am.map_addr[epi.peer_info.host] = node_id
55+
am.random_pos.append(node_id)
56+
57+
if i >= num_new:
58+
# make a tried_table entry
59+
epi.is_tried = True
60+
epi.last_success = timestamp
61+
epi.last_try = timestamp - rand.randint(0, 1000)
62+
bucket = epi.get_tried_bucket(am.key)
63+
pos = epi.get_bucket_position(am.key, False, bucket)
64+
if am.tried_matrix[bucket][pos] == -1:
65+
am.tried_matrix[bucket][pos] = node_id
66+
am.tried_count += 1
67+
else:
68+
# make a new_table entry
69+
ref_count = rand.randint(1, NEW_BUCKETS_PER_ADDRESS)
70+
epi.ref_count = ref_count
71+
assigned = False
72+
for _ in range(ref_count):
73+
bucket = epi.get_new_bucket(am.key)
74+
pos = epi.get_bucket_position(am.key, True, bucket)
75+
if am.new_matrix[bucket][pos] == -1:
76+
am.new_matrix[bucket][pos] = node_id
77+
am.new_count += 1
78+
assigned = True
79+
break
80+
if not assigned:
81+
# fallback if no bucket available
82+
epi.ref_count = 0
83+
84+
return am
85+
86+
87+
async def benchmark_serialize_deserialize(iterations: int = 5) -> None:
88+
"""
89+
Benchmarks the serialization and deserialization of peer data.
90+
"""
91+
92+
total_serialize_time = 0.0
93+
total_deserialize_time = 0.0
94+
95+
with tempfile.TemporaryDirectory() as tmpdir:
96+
peers_file_path = Path(tmpdir) / "peers.dat"
97+
98+
for i in range(iterations):
99+
address_manager: AddressManager = populate_address_manager()
100+
print(f"--- Benchmark Run {i + 1} ---")
101+
102+
# Benchmark serialize
103+
start_serialize = time.perf_counter()
104+
105+
serialised_bytes = address_manager.serialize_bytes()
106+
await write_file_async(peers_file_path, serialised_bytes, file_mode=0o644)
107+
end_serialize = time.perf_counter()
108+
serialize_duration = end_serialize - start_serialize
109+
total_serialize_time += serialize_duration
110+
print(f"Serialize time: {serialize_duration:.6f} seconds")
111+
112+
# Benchmark deserialize
113+
async with aiofiles.open(peers_file_path, "rb") as f:
114+
data = io.BytesIO(await f.read())
115+
start_deserialize = time.perf_counter()
116+
_ = AddressManager.deserialize_bytes(data)
117+
end_deserialize = time.perf_counter()
118+
deserialize_duration = end_deserialize - start_deserialize
119+
total_deserialize_time += deserialize_duration
120+
print(f"Deserialize time: {deserialize_duration:.6f} seconds")
121+
122+
print(f"\n=== Benchmark Summary ({iterations} iterations) ===")
123+
print(f"Average serialize time: {total_serialize_time / iterations:.6f} seconds")
124+
print(f"Average deserialize time: {total_deserialize_time / iterations:.6f} seconds")
125+
126+
127+
async def main() -> None:
128+
await benchmark_serialize_deserialize(iterations=10)
129+
130+
131+
if __name__ == "__main__":
132+
asyncio.run(main())

benchmarks/block_store.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,18 @@
77
from pathlib import Path
88
from time import monotonic
99

10-
from chia_rs import Foliage, FoliageBlockData, FoliageTransactionBlock, PoolTarget, RewardChainBlock, TransactionsInfo
10+
from chia_rs import (
11+
BlockRecord,
12+
Foliage,
13+
FoliageBlockData,
14+
FoliageTransactionBlock,
15+
FullBlock,
16+
PoolTarget,
17+
ProofOfSpace,
18+
RewardChainBlock,
19+
SubEpochSummary,
20+
TransactionsInfo,
21+
)
1122
from chia_rs.sized_bytes import bytes32
1223
from chia_rs.sized_ints import uint8, uint32, uint64, uint128
1324

@@ -23,12 +34,8 @@
2334
rand_vdf_proof,
2435
rewards,
2536
)
26-
from chia.consensus.block_record import BlockRecord
2737
from chia.full_node.block_store import BlockStore
28-
from chia.types.blockchain_format.proof_of_space import ProofOfSpace
2938
from chia.types.blockchain_format.serialized_program import SerializedProgram
30-
from chia.types.blockchain_format.sub_epoch_summary import SubEpochSummary
31-
from chia.types.full_block import FullBlock
3239

3340
# to run this benchmark:
3441
# python -m benchmarks.coin_store

benchmarks/mempool-long-lived.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from time import monotonic
77
from typing import Optional
88

9-
from chia_rs import G2Element
9+
from chia_rs import CoinSpend, G2Element, SpendBundle
1010
from chia_rs.sized_bytes import bytes32
1111
from chia_rs.sized_ints import uint32, uint64
1212
from clvm.casts import int_to_bytes
@@ -16,10 +16,8 @@
1616
from chia.types.blockchain_format.coin import Coin
1717
from chia.types.blockchain_format.serialized_program import SerializedProgram
1818
from chia.types.coin_record import CoinRecord
19-
from chia.types.coin_spend import CoinSpend
2019
from chia.types.condition_opcodes import ConditionOpcode
21-
from chia.types.eligible_coin_spends import UnspentLineageInfo
22-
from chia.types.spend_bundle import SpendBundle
20+
from chia.types.mempool_item import UnspentLineageInfo
2321

2422
# this is one week worth of blocks
2523
NUM_ITERS = 32256

benchmarks/mempool.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from time import monotonic
1010
from typing import Optional
1111

12+
from chia_rs import SpendBundle
1213
from chia_rs.sized_bytes import bytes32
1314
from chia_rs.sized_ints import uint32, uint64
1415

@@ -18,9 +19,8 @@
1819
from chia.simulator.wallet_tools import WalletTool
1920
from chia.types.blockchain_format.coin import Coin
2021
from chia.types.coin_record import CoinRecord
21-
from chia.types.eligible_coin_spends import UnspentLineageInfo
2222
from chia.types.mempool_inclusion_status import MempoolInclusionStatus
23-
from chia.types.spend_bundle import SpendBundle
23+
from chia.types.mempool_item import UnspentLineageInfo
2424
from chia.util.batches import to_batches
2525
from chia.util.task_referencer import create_referenced_task
2626

@@ -243,9 +243,7 @@ async def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None:
243243
with enable_profiler(True, f"create-{suffix}"):
244244
start = monotonic()
245245
for _ in range(10):
246-
await mempool.create_block_generator(
247-
last_tb_header_hash=rec.header_hash,
248-
)
246+
mempool.create_block_generator(last_tb_header_hash=rec.header_hash)
249247
stop = monotonic()
250248
print(f" time: {stop - start:0.4f}s")
251249
print(f" per call: {(stop - start) / 10 * 1000:0.2f}ms")
@@ -254,7 +252,7 @@ async def add_spend_bundles(spend_bundles: list[SpendBundle]) -> None:
254252
with enable_profiler(True, f"create2-{suffix}"):
255253
start = monotonic()
256254
for _ in range(10):
257-
await mempool.create_block_generator2(last_tb_header_hash=rec.header_hash)
255+
mempool.create_block_generator2(last_tb_header_hash=rec.header_hash)
258256
stop = monotonic()
259257
print(f" time: {stop - start:0.4f}s")
260258
print(f" per call: {(stop - start) / 10 * 1000:0.2f}ms")

benchmarks/streamable.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99
from typing import Any, Callable, Optional, TextIO, Union
1010

1111
import click
12+
from chia_rs import FullBlock
1213
from chia_rs.sized_bytes import bytes32
1314
from chia_rs.sized_ints import uint8, uint64
1415

1516
from benchmarks.utils import EnumType, get_commit_hash
1617
from chia._tests.util.benchmarks import rand_bytes, rand_full_block, rand_hash
17-
from chia.types.full_block import FullBlock
1818
from chia.util.streamable import Streamable, streamable
1919

2020
# to run this benchmark:

chia/_tests/blockchain/blockchain_test_utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@
22

33
from typing import Optional
44

5-
from chia_rs import SpendBundleConditions
5+
from chia_rs import FullBlock, SpendBundleConditions
66
from chia_rs.sized_ints import uint32, uint64
77

88
from chia.consensus.block_body_validation import ForkInfo
99
from chia.consensus.blockchain import AddBlockResult, Blockchain
1010
from chia.consensus.difficulty_adjustment import get_next_sub_slot_iters_and_difficulty
1111
from chia.consensus.multiprocess_validation import PreValidationResult, pre_validate_block
12-
from chia.types.full_block import FullBlock
1312
from chia.types.validation_state import ValidationState
1413
from chia.util.augmented_chain import AugmentedBlockchain
1514
from chia.util.errors import Err

chia/_tests/blockchain/test_augmented_chain.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@
44
from typing import TYPE_CHECKING, ClassVar, Optional, cast
55

66
import pytest
7+
from chia_rs import BlockRecord, FullBlock
78
from chia_rs.sized_bytes import bytes32
89
from chia_rs.sized_ints import uint32
910

1011
from chia._tests.blockchain.blockchain_test_utils import _validate_and_add_block
1112
from chia._tests.util.blockchain import create_blockchain
12-
from chia.consensus.block_record import BlockRecord
1313
from chia.simulator.block_tools import BlockTools
14-
from chia.types.full_block import FullBlock
1514
from chia.util.augmented_chain import AugmentedBlockchain
1615
from chia.util.errors import Err
1716

chia/_tests/blockchain/test_blockchain.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,16 @@
1212
import pytest
1313
from chia_rs import (
1414
AugSchemeMPL,
15+
BlockRecord,
1516
ConsensusConstants,
17+
EndOfSubSlotBundle,
18+
FullBlock,
1619
G2Element,
1720
InfusedChallengeChainSubSlot,
1821
MerkleSet,
22+
SpendBundle,
1923
TransactionsInfo,
24+
UnfinishedBlock,
2025
)
2126
from chia_rs.sized_bytes import bytes32
2227
from chia_rs.sized_ints import uint8, uint32, uint64
@@ -34,7 +39,6 @@
3439
from chia._tests.util.get_name_puzzle_conditions import get_name_puzzle_conditions
3540
from chia.consensus.block_body_validation import ForkInfo
3641
from chia.consensus.block_header_validation import validate_finished_header_block
37-
from chia.consensus.block_record import BlockRecord
3842
from chia.consensus.block_rewards import calculate_base_farmer_reward
3943
from chia.consensus.blockchain import AddBlockResult, Blockchain
4044
from chia.consensus.coinbase import create_farmer_coin
@@ -52,11 +56,7 @@
5256
from chia.types.blockchain_format.vdf import VDFInfo, VDFProof, validate_vdf
5357
from chia.types.condition_opcodes import ConditionOpcode
5458
from chia.types.condition_with_args import ConditionWithArgs
55-
from chia.types.end_of_slot_bundle import EndOfSubSlotBundle
56-
from chia.types.full_block import FullBlock
5759
from chia.types.generator_types import BlockGenerator
58-
from chia.types.spend_bundle import SpendBundle
59-
from chia.types.unfinished_block import UnfinishedBlock
6060
from chia.types.validation_state import ValidationState
6161
from chia.util.augmented_chain import AugmentedBlockchain
6262
from chia.util.errors import Err

chia/_tests/blockchain/test_blockchain_transactions.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44

55
import pytest
6+
from chia_rs import SpendBundle
67
from chia_rs.sized_bytes import bytes32
78
from chia_rs.sized_ints import uint32, uint64
89
from clvm.casts import int_to_bytes
@@ -18,7 +19,7 @@
1819
from chia.simulator.wallet_tools import WalletTool
1920
from chia.types.condition_opcodes import ConditionOpcode
2021
from chia.types.condition_with_args import ConditionWithArgs
21-
from chia.types.spend_bundle import SpendBundle, estimate_fees
22+
from chia.types.spend_bundle import estimate_fees
2223
from chia.util.errors import Err
2324
from chia.wallet.conditions import AssertCoinAnnouncement, AssertPuzzleAnnouncement
2425

@@ -65,7 +66,7 @@ async def test_basic_blockchain_tx(
6566
assert sb == spend_bundle
6667

6768
last_block = blocks[-1]
68-
result = await full_node_1.mempool_manager.create_bundle_from_mempool(last_block.header_hash)
69+
result = full_node_1.mempool_manager.create_bundle_from_mempool(last_block.header_hash)
6970
assert result is not None
7071
next_spendbundle, _ = result
7172

chia/_tests/blockchain/test_build_chains.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@
33
from typing import Optional
44

55
import pytest
6-
from chia_rs import Coin, ConsensusConstants, additions_and_removals, get_flags_for_height_and_constants
6+
from chia_rs import Coin, ConsensusConstants, FullBlock, additions_and_removals, get_flags_for_height_and_constants
77
from chia_rs.sized_ints import uint64
88

99
from chia.simulator.block_tools import BlockTools
10-
from chia.types.full_block import FullBlock
1110

1211
# These test targets are used to trigger a build of the test chains.
1312
# On CI we clone the test-cache repository to load the chains from, so they

0 commit comments

Comments
 (0)