Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(l1): full sync #1312

Merged
merged 285 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
285 commits
Select commit Hold shift + click to select a range
6c04bb6
Merge branch '840-rlpx-listen-loop' of github.com:lambdaclass/lambda_…
fmoletta Oct 25, 2024
05c9a5e
Replaced hardcoded capabilities strings with enums
ElFantasma Oct 25, 2024
f011aa6
Merge branch 'main' into 840-rlpx-listen-loop
ElFantasma Oct 25, 2024
8ea2644
Add snap messages to liste loop
fmoletta Oct 25, 2024
42049ab
Made Status test to pass
ElFantasma Oct 28, 2024
34e0d9c
Merge branch 'main' into 840-rlpx-listen-loop
ElFantasma Oct 28, 2024
940b6f3
Fixed format
ElFantasma Oct 28, 2024
8047f41
Removed required Debug format on error printing
ElFantasma Oct 28, 2024
f474617
Trying previous commit from hive to see if CI works
ElFantasma Oct 28, 2024
1d5223b
Fix `AccountRange message decoding
fmoletta Oct 28, 2024
80329c7
Fix
fmoletta Oct 28, 2024
297a37b
fix
fmoletta Oct 28, 2024
f25fb1a
Fix: build proof for last account not limit hash
fmoletta Oct 28, 2024
0fdf562
Using apply_fork_choice to set last block number and make blocks cann…
ElFantasma Oct 28, 2024
c989418
Merge branch 'main' into 840-rlpx-listen-loop
ElFantasma Oct 28, 2024
12010b3
Fmt + Return error instead of pancking if invalid root is used
fmoletta Oct 28, 2024
ed0186f
Calling apply_fork_choice only once for the whole chain
ElFantasma Oct 28, 2024
42f2af3
Revert change
fmoletta Oct 28, 2024
61ad329
Return empty proof if root is missing
fmoletta Oct 28, 2024
13c44cf
Calling apply_fork_choice only once for the whole chain
ElFantasma Oct 28, 2024
ecb682f
Clippy fix
ElFantasma Oct 28, 2024
f8bd1dc
use trait method
fmoletta Oct 28, 2024
b890f60
Merge remote-tracking branch 'origin/840-rlpx-listen-loop' into trie_…
fmoletta Oct 28, 2024
31aa8ac
Update hive revision
fmoletta Oct 28, 2024
34d8d84
Reorganize module
fmoletta Oct 28, 2024
9b85c69
Merge branch 'main' into 840-rlpx-listen-loop
ElFantasma Oct 29, 2024
013a977
Update hive revision
fmoletta Oct 29, 2024
66f759a
Add hive snap worflow
fmoletta Oct 29, 2024
67cb57a
Merge branch 'main' into 840-rlpx-listen-loop
ElFantasma Oct 29, 2024
b1ea882
Reverting hive version
ElFantasma Oct 29, 2024
58da873
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Oct 29, 2024
fe2fb77
Removed unnecessary info! messages
ElFantasma Oct 29, 2024
50ca190
Merge branch '840-rlpx-listen-loop' into trie_iter
fmoletta Oct 29, 2024
7062b1b
Add messages + inner structs
fmoletta Oct 29, 2024
d609cae
progress
fmoletta Oct 29, 2024
c69690d
Bump hive version
fmoletta Oct 29, 2024
65f8c77
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Oct 29, 2024
b7c0211
Fix bug in response bytes length calculation
fmoletta Oct 29, 2024
74173d2
Restore Makefile
fmoletta Oct 29, 2024
777732a
Identify storage tries by hashed account address
fmoletta Oct 29, 2024
0e3e276
Merge branch 'trie_iter' into snap-storage-range
fmoletta Oct 29, 2024
abb28cf
Impl logic
fmoletta Oct 29, 2024
fea174d
Connect to main loop
fmoletta Oct 30, 2024
dc6752c
Compute proofs
fmoletta Oct 30, 2024
03d9928
Clippy
fmoletta Oct 30, 2024
c791a89
Chamge type
fmoletta Oct 30, 2024
9fd88d3
Add test
fmoletta Oct 30, 2024
2b9d207
Add messages
fmoletta Oct 30, 2024
37becaa
Add hive test
fmoletta Oct 30, 2024
a6d2f08
fmt
fmoletta Oct 30, 2024
c502f06
Impl messages
fmoletta Oct 31, 2024
242502e
Impl Trie::get_node
fmoletta Oct 31, 2024
3b7d70e
Fix
fmoletta Oct 31, 2024
384eff7
Merge branch 'trie_iter' into snap-storage-range
fmoletta Oct 31, 2024
fa4be1b
Merge branch 'snap-storage-range' into snap-bytecodes
fmoletta Oct 31, 2024
1cf1e9b
implement get_trie_nodes for storage
fmoletta Oct 31, 2024
349d05f
Add byte limit
fmoletta Oct 31, 2024
4fd0ee5
Add request processing
fmoletta Oct 31, 2024
d02e8f2
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Oct 31, 2024
0575a44
Merge branch 'snap-storage-range' of github.com:lambdaclass/lambda_et…
fmoletta Oct 31, 2024
aa29e5f
Fix lingering conflicts
fmoletta Oct 31, 2024
89e144a
Save progress
fmoletta Oct 31, 2024
1d8c3f9
Progress
fmoletta Nov 1, 2024
ea34fbc
Progress
fmoletta Nov 1, 2024
e57f386
remove unused code
fmoletta Nov 1, 2024
0a31fc9
Handle wrong path input lens
fmoletta Nov 1, 2024
2c0e30e
Add restrictions
fmoletta Nov 1, 2024
b3c4816
Fix error handling
fmoletta Nov 1, 2024
80bbc30
clippy+fmt
fmoletta Nov 1, 2024
b7b978a
Add hive test
fmoletta Nov 1, 2024
f02d29a
Cleanup
fmoletta Nov 1, 2024
0e5a005
Draft
fmoletta Nov 1, 2024
003d445
:(
fmoletta Nov 1, 2024
23974bb
Fix code to handle nibbles properly
fmoletta Nov 1, 2024
b159f7d
Simplify code
fmoletta Nov 1, 2024
12b0268
refactor
fmoletta Nov 1, 2024
8e4c884
Remove debug code
fmoletta Nov 1, 2024
b80f19f
Cleanup code
fmoletta Nov 1, 2024
f03ef1e
Merge branch 'snap-bytecodes' into snap-trie-nodes
fmoletta Nov 1, 2024
098a584
Remove debug command
fmoletta Nov 1, 2024
9a57e37
Un-comment noisy info
fmoletta Nov 1, 2024
f54af1d
Update comment
fmoletta Nov 1, 2024
b307261
reorder
fmoletta Nov 1, 2024
9da6ec9
Cite sources
fmoletta Nov 1, 2024
8a0fbbb
Move funcs to encodings module
fmoletta Nov 1, 2024
200d014
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 4, 2024
2332889
Merge branch 'snap-storage-range' into snap-bytecodes
fmoletta Nov 4, 2024
1805ef6
Update workflow
fmoletta Nov 4, 2024
b270580
Update workflow
fmoletta Nov 4, 2024
6af2d6e
Merge branch 'snap-storage-range' into snap-bytecodes
fmoletta Nov 4, 2024
9ec2129
Update workflow
fmoletta Nov 4, 2024
2be03ee
Progress
fmoletta Nov 5, 2024
09f688b
Clippy
fmoletta Nov 5, 2024
f494ad9
Merge branch 'snap-storage-range' into snap-bytecodes
fmoletta Nov 5, 2024
64610c3
Merge branch 'snap-bytecodes' into snap-trie-nodes
fmoletta Nov 5, 2024
d3acbd4
Merge branch 'snap-trie-nodes' into validate-account-range
fmoletta Nov 5, 2024
824afbc
progress
fmoletta Nov 5, 2024
19c0bf0
Remove path field from BranchNode
fmoletta Nov 5, 2024
d32bb4e
Start dumb nibbles impl
fmoletta Nov 5, 2024
7cad9b6
Impl common_prefix
fmoletta Nov 5, 2024
3b69cd7
Update name & doc
fmoletta Nov 5, 2024
16d1432
Impl next
fmoletta Nov 5, 2024
d7c036f
Use DumbNibbles: LeafNode get & insert
fmoletta Nov 5, 2024
a2afdfd
Use DumbNibbles: ExtensionNode get & insert
fmoletta Nov 5, 2024
3a65df9
Make code compile
fmoletta Nov 5, 2024
43ae680
Fix node encoding for LeafNode
fmoletta Nov 5, 2024
e69e954
Fix leaf nibbles
fmoletta Nov 5, 2024
998ed51
Fix leaf partial when inserting to leaf
fmoletta Nov 6, 2024
3cfd7c4
Fixes
fmoletta Nov 6, 2024
ad40f23
Fix
fmoletta Nov 6, 2024
a41cf2b
Fix
fmoletta Nov 6, 2024
68d5f83
Fix
fmoletta Nov 6, 2024
275659a
Fix
fmoletta Nov 6, 2024
6e1b4b7
[DEBUG] Add debug prints
fmoletta Nov 6, 2024
167c591
[DEBUG] Add debug prints
fmoletta Nov 6, 2024
aad0bcf
Fix
fmoletta Nov 6, 2024
71357dd
[DEBUG] Add debug prints
fmoletta Nov 6, 2024
cd847b9
refactor: add next_choice method
fmoletta Nov 6, 2024
37c93d7
Simplify leaf node encoding
fmoletta Nov 7, 2024
92313f0
Simplify encoding of Leaf
fmoletta Nov 7, 2024
3eb5ee9
Simplify encoding of Extension
fmoletta Nov 7, 2024
eb4fd0c
Simplify encoding of Branch
fmoletta Nov 7, 2024
d50e0ff
Remove the NodeEncoder
fmoletta Nov 7, 2024
856224d
Clippy
fmoletta Nov 7, 2024
f713657
Update TrieIterator
fmoletta Nov 7, 2024
30ba82f
Add proptest
fmoletta Nov 7, 2024
21537d4
Remove old nibble representation
fmoletta Nov 7, 2024
28bd344
Rename DumbNibbles -> Nibbles
fmoletta Nov 7, 2024
c56ad04
Update some doc
fmoletta Nov 7, 2024
bebce62
Simplify BranchNode::remove
fmoletta Nov 7, 2024
08c6668
Simplify
fmoletta Nov 7, 2024
e1f032f
Update doc
fmoletta Nov 7, 2024
9dc2752
Fix unit test
fmoletta Nov 7, 2024
bbe367d
Fix test + code
fmoletta Nov 7, 2024
63f1645
Update test values
fmoletta Nov 7, 2024
237f291
Fix potential panick
fmoletta Nov 7, 2024
d5dfa30
Fix
fmoletta Nov 7, 2024
55b0c37
Fix unit tests
fmoletta Nov 7, 2024
01090b4
Remove outdated comment
fmoletta Nov 7, 2024
e1be0c6
[DEBUG] Remove debug prints
fmoletta Nov 7, 2024
bed25f7
Remove funny name test
fmoletta Nov 7, 2024
f2c2eef
doc nibbles module
fmoletta Nov 7, 2024
9050b0c
Remove todo
fmoletta Nov 7, 2024
345ae96
remove debug print
fmoletta Nov 7, 2024
0fa490f
avoid clone
fmoletta Nov 7, 2024
df62fab
Decode leaf & extension nodes
fmoletta Nov 8, 2024
de3695f
Decode branch nodesc
fmoletta Nov 8, 2024
cb92b60
Impl decode_raw for Node directly
fmoletta Nov 8, 2024
87994d3
Update test & remove impls for each node kind
fmoletta Nov 8, 2024
ec31d42
Clippy
fmoletta Nov 8, 2024
439a010
Remove unused fn
fmoletta Nov 8, 2024
69f583c
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 8, 2024
58d7cb0
Add doc comments
fmoletta Nov 8, 2024
797d486
Fix typos
fmoletta Nov 8, 2024
f2ea85f
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 8, 2024
34e2535
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 8, 2024
5b3f4b9
Merge branch 'decode_node' into validate-account-range
fmoletta Nov 11, 2024
b0beea8
Dont write nodes to DB if they are already inlined
fmoletta Nov 11, 2024
52fec40
Merge branch 'dont-store-if-inlined' into validate-account-range
fmoletta Nov 11, 2024
39b9d19
progress
fmoletta Nov 11, 2024
b2375ca
Save current progress
fmoletta Nov 12, 2024
04f94a3
Fix logic
fmoletta Nov 12, 2024
fc3ecc8
Fix logic
fmoletta Nov 12, 2024
774e1d1
Fix logic
fmoletta Nov 12, 2024
827439e
Add extension node logic to remove internal nodes
fmoletta Nov 12, 2024
377b794
Improve test
fmoletta Nov 12, 2024
185b884
Add comment
fmoletta Nov 12, 2024
2c8bb52
Add proptest
fmoletta Nov 12, 2024
76d719a
Add proptest
fmoletta Nov 12, 2024
9254ce8
Add test case
fmoletta Nov 12, 2024
0a27aab
rename func
fmoletta Nov 12, 2024
68661c9
Add doc
fmoletta Nov 12, 2024
fdcbc99
Add doc
fmoletta Nov 13, 2024
6f1e304
Add special case test
fmoletta Nov 13, 2024
925f536
Fix peripherial code
fmoletta Nov 13, 2024
f7f0bdb
Add proptest for special case: no keys
fmoletta Nov 13, 2024
0023b8a
Fix
fmoletta Nov 13, 2024
8e8dba3
Fix logic
fmoletta Nov 13, 2024
1a534cc
Fix logic
fmoletta Nov 13, 2024
6a9db29
Refactor has_right_element
fmoletta Nov 13, 2024
ff88780
Fix logic
fmoletta Nov 13, 2024
7583488
Unify criteria
fmoletta Nov 13, 2024
849a354
Refactor
fmoletta Nov 13, 2024
0908bd5
Clippy
fmoletta Nov 13, 2024
c445edc
Add doc
fmoletta Nov 13, 2024
ec13ce5
Reorder code + add doc
fmoletta Nov 13, 2024
2445f53
Fix logic
fmoletta Nov 13, 2024
16cb1b6
Check result in tests
fmoletta Nov 13, 2024
8151cef
Add tests for unsuccesful cases
fmoletta Nov 13, 2024
a7d5415
Add tests for unsuccesful cases
fmoletta Nov 13, 2024
6c9dd01
Add error handling
fmoletta Nov 13, 2024
87f2445
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 13, 2024
ad0f921
[Postpone] changes not related to the trie
fmoletta Nov 13, 2024
4fc5244
Fix
fmoletta Nov 13, 2024
dab6172
Remove debug code
fmoletta Nov 13, 2024
d02c374
Rename fn and module
fmoletta Nov 13, 2024
07e1f46
clippy
fmoletta Nov 13, 2024
2b36bbb
Update code
fmoletta Nov 13, 2024
2d711b6
Improve interface
fmoletta Nov 13, 2024
56a4ee9
Remove code leftover from debug
fmoletta Nov 13, 2024
c444a01
Consistency
fmoletta Nov 13, 2024
d59b09a
Fix
fmoletta Nov 13, 2024
8dd7c6d
Add test
fmoletta Nov 13, 2024
7e4205c
Remove TODO
fmoletta Nov 13, 2024
c59b8be
Revert "[Postpone] changes not related to the trie"
fmoletta Nov 13, 2024
03b73c8
Fix
fmoletta Nov 13, 2024
e7d3dc4
Add helper methods
fmoletta Nov 13, 2024
5d4ad34
Add syncmode argument
fmoletta Nov 14, 2024
a3820e4
crate
fmoletta Nov 15, 2024
afcdc5a
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 15, 2024
c3d5106
Add SnapSyncManager + send snap replies to them
fmoletta Nov 15, 2024
fa275ec
Add channel between kademlia table and peer connection handler
fmoletta Nov 15, 2024
c88d114
SyncManager first iteration
fmoletta Nov 21, 2024
798fb05
Start syncer in fork_choice handler
fmoletta Nov 21, 2024
a875680
First iteration of state retrieval planning
fmoletta Nov 22, 2024
356eaf0
[REVERT ME] Make V2 endpoints work in order to run hive sync test
fmoletta Nov 22, 2024
a6d64f9
Add parallel state fetching first draft
fmoletta Nov 25, 2024
3f6df84
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 26, 2024
fc9cc3e
Store block bodies and headers
fmoletta Nov 26, 2024
6b33d11
Set latest block
fmoletta Nov 26, 2024
e6c2a08
Start snap fetching
fmoletta Nov 26, 2024
da6cff8
Refactor comunication between backend and peer
fmoletta Nov 26, 2024
64835f3
Avoid holding the mutex for the kademlia table when sending requests …
fmoletta Nov 26, 2024
c798c35
Migrate to full sync
fmoletta Nov 27, 2024
62084e8
Error handling
fmoletta Nov 27, 2024
02a89b2
Fixes
fmoletta Nov 27, 2024
a60948d
revert uneeded changes
fmoletta Nov 27, 2024
cc4452e
revert uneeded changes
fmoletta Nov 27, 2024
c86b553
Updates & fixes
fmoletta Nov 27, 2024
05848a2
Add ethereum/sync test suite to hive (1 test)
fmoletta Nov 27, 2024
9d608f9
Default to full-sync
fmoletta Nov 27, 2024
57f1e29
revert uneeded changes
fmoletta Nov 27, 2024
a7350d8
revert uneeded changes
fmoletta Nov 27, 2024
eb3ff59
Fixes
fmoletta Nov 27, 2024
dc6fdf1
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 27, 2024
0a8d4e8
Clippy
fmoletta Nov 27, 2024
cfce53d
Merge branch 'main' of github.com:lambdaclass/lambda_ethereum_rust in…
fmoletta Nov 27, 2024
493fa91
revert hive workflow change
fmoletta Nov 27, 2024
c6d6767
Revert "[REVERT ME] Make V2 endpoints work in order to run hive sync …
fmoletta Nov 27, 2024
95a9af2
revert hive workflow change
fmoletta Nov 27, 2024
fd90f18
reduce tracing output
fmoletta Nov 27, 2024
3191ddd
fmt
fmoletta Nov 27, 2024
576ee33
Fix
fmoletta Nov 27, 2024
a0cc0a1
Merge branch 'main' into full-sync
mpaulucci Nov 28, 2024
e4ef02d
Add syncmode to the CLI doc
fmoletta Nov 28, 2024
0c21b5e
remove potential panic when indexing kademlia table
fmoletta Nov 28, 2024
dd934f5
Fix typo
fmoletta Nov 28, 2024
d563140
Merge branch 'main' into full-sync
fmoletta Nov 28, 2024
75be452
Fix merge
fmoletta Nov 28, 2024
228dfb3
Merge branch 'main' into full-sync
fmoletta Nov 28, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ stop-localnet-silent:
@kurtosis enclave stop lambdanet >/dev/null 2>&1 || true
@kurtosis enclave rm lambdanet --force >/dev/null 2>&1 || true

HIVE_REVISION := fc6ddec210095e2369019e7f4ab2f9f38e35a8e8
HIVE_REVISION := f220e0c55fb222aaaffdf17d66aa0537cd16a67a
# Shallow clones can't specify a single revision, but at least we avoid working
# the whole history by making it shallow since a given date (one day before our
# target revision).
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ ethrex supports the following command line arguments:
- `--discovery.port <PORT>`: UDP port for P2P discovery. Default value: 30303.
- `--bootnodes <BOOTNODE_LIST>`: Comma separated enode URLs for P2P discovery bootstrap.
- `--log.level <LOG_LEVEL>`: The verbosity level used for logs. Default value: info. possible values: info, debug, trace, warn, error
- `--syncmode <SYNC_MODE>`: The way in which the node will sync its state. Can be either "full" or "snap" with "snap" as default value.

# ethrex L2

Expand Down
6 changes: 6 additions & 0 deletions cmd/ethrex/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ pub fn cli() -> Command {
.required(false)
.value_name("CHAIN_RLP_PATH"),
)
.arg(
fkrause98 marked this conversation as resolved.
Show resolved Hide resolved
Arg::new("syncmode")
.long("syncmode")
.required(false)
.value_name("SYNC_MODE"),
)
.arg(
Arg::new("import_dir")
.long("import_dir")
Expand Down
54 changes: 38 additions & 16 deletions cmd/ethrex/ethrex.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
use bytes::Bytes;
use directories::ProjectDirs;

use ethrex_blockchain::add_block;
use ethrex_blockchain::fork_choice::apply_fork_choice;
use ethrex_core::types::{Block, Genesis};
use ethrex_core::H256;
use ethrex_net::bootnode::BootNode;
use ethrex_net::node_id_from_signing_key;
use ethrex_net::types::Node;
use ethrex_blockchain::{add_block, fork_choice::apply_fork_choice};
use ethrex_core::{
types::{Block, Genesis},
H256,
};
use ethrex_net::{
bootnode::BootNode, node_id_from_signing_key, peer_table, sync::SyncManager, types::Node,
};
use ethrex_rlp::decode::RLPDecode;
use ethrex_storage::{EngineType, Store};
use k256::ecdsa::SigningKey;
use local_ip_address::local_ip;
use std::fs;
use std::future::IntoFuture;
use std::path::Path;
use std::str::FromStr as _;
use std::time::Duration;
use std::{
fs::File,
fs::{self, File},
future::IntoFuture,
io,
net::{Ipv4Addr, SocketAddr, ToSocketAddrs},
path::Path,
str::FromStr as _,
time::Duration,
};
use tokio_util::task::TaskTracker;
use tracing::{error, info, warn};
use tracing_subscriber::filter::Directive;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
use tracing_subscriber::{filter::Directive, EnvFilter, FmtSubscriber};
mod cli;
mod decode;

Expand Down Expand Up @@ -117,6 +115,11 @@ async fn main() {
.get_one::<String>("datadir")
.map_or(set_datadir(DEFAULT_DATADIR), |datadir| set_datadir(datadir));

let snap_sync = is_snap_sync(&matches);
if snap_sync {
info!("snap-sync not available, defaulting to full-sync");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full sync will only work for a network with a post-merge genesis, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the sync itself here is no check specifically preventing it from happening, we would get an error when trying to execute pre-merge blocks as we don't support them.

}

let store = Store::new(&data_dir, EngineType::Libmdbx).expect("Failed to create Store");

let genesis = read_genesis_file(genesis_file_path);
Expand Down Expand Up @@ -173,6 +176,10 @@ async fn main() {
tcp_port: tcp_socket_addr.port(),
node_id: local_node_id,
};
// Create Kademlia Table here so we can access it from rpc server (for syncing)
let peer_table = peer_table(signer.clone());
// Create SyncManager
let syncer = SyncManager::new(peer_table.clone(), snap_sync);

// TODO: Check every module starts properly.
let tracker = TaskTracker::new();
Expand All @@ -182,6 +189,7 @@ async fn main() {
store.clone(),
jwt_secret,
local_p2p_node,
syncer,
)
.into_future();

Expand Down Expand Up @@ -215,6 +223,7 @@ async fn main() {
tcp_socket_addr,
bootnodes,
signer,
peer_table,
store,
)
.into_future();
Expand Down Expand Up @@ -282,6 +291,19 @@ fn parse_socket_addr(addr: &str, port: &str) -> io::Result<SocketAddr> {
))
}

fn is_snap_sync(matches: &clap::ArgMatches) -> bool {
let syncmode = matches.get_one::<String>("syncmode");
if let Some(syncmode) = syncmode {
match &**syncmode {
"full" => false,
"snap" => true,
other => panic!("Invalid syncmode {other} expected either snap or full"),
}
} else {
true
}
}

fn set_datadir(datadir: &str) -> String {
let project_dir = ProjectDirs::from("", "", datadir).expect("Couldn't find home directory");
project_dir
Expand Down
3 changes: 2 additions & 1 deletion crates/networking/p2p/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ edition = "2021"

[dependencies]
ethrex-core.workspace = true
ethrex-blockchain.workspace = true
ethrex-rlp.workspace = true
ethrex-storage.workspace = true
ethrex-blockchain.workspace = true
ethrex-trie.workspace = true

tracing.workspace = true
tokio.workspace = true
Expand Down
41 changes: 40 additions & 1 deletion crates/networking/p2p/kademlia.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::{
discv4::{time_now_unix, FindNodeRequest},
peer_channels::PeerChannels,
types::Node,
};
use ethrex_core::{H256, H512, U256};
use sha3::{Digest, Keccak256};
use tokio::sync::mpsc::UnboundedSender;
use tracing::info;

pub const MAX_NODES_PER_BUCKET: usize = 16;
const NUMBER_OF_BUCKETS: usize = 256;
Expand Down Expand Up @@ -187,7 +189,7 @@ impl KademliaTable {
/// ## Dev note:
/// This function should be improved:
/// We might keep the `peers` list sorted by last_ping as we would avoid unnecessary loops
pub fn get_least_recently_pinged_peers(&mut self, limit: usize) -> Vec<PeerData> {
pub fn get_least_recently_pinged_peers(&self, limit: usize) -> Vec<PeerData> {
let mut peers = vec![];

for bucket in &self.buckets {
Expand Down Expand Up @@ -254,6 +256,40 @@ impl KademliaTable {

None
}

/// Set the sender end of the channel between the kademlia table and the peer's active connection
/// This function should be called each time a connection is established so the backend can send requests to the peers
pub fn set_channels(&mut self, node_id: H512, channels: PeerChannels) {
let bucket_idx = bucket_number(self.local_node_id, node_id);
if let Some(peer) = self.buckets.get_mut(bucket_idx).and_then(|bucket| {
bucket
.peers
.iter_mut()
.find(|peer| peer.node.node_id == node_id)
}) {
peer.channels = Some(channels)
}
}

/// TODO: Randomly select peer
fkrause98 marked this conversation as resolved.
Show resolved Hide resolved
pub fn get_peer(&self) -> Option<PeerData> {
self.get_least_recently_pinged_peers(1).pop()
}

/// Returns the channel ends to an active peer connection
/// The peer is selected randomly (TODO), and doesn't guarantee that the selected peer is not currenlty busy
/// If no peer is found, this method will try again after 10 seconds
/// TODO: Filter peers by capabilities, set max amount of retries
pub async fn get_peer_channels(&self) -> PeerChannels {
loop {
if let Some(channels) = self.get_peer().and_then(|peer| peer.channels) {
return channels;
}
info!("[Sync] No peers available, retrying in 10 sec");
// This is the unlikely case where we just started the node and don't have peers, wait a bit and try again
fkrause98 marked this conversation as resolved.
Show resolved Hide resolved
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
}
}
}

/// Computes the distance between two nodes according to the discv4 protocol
Expand All @@ -279,6 +315,8 @@ pub struct PeerData {
pub liveness: u16,
/// if a revalidation was sent to the peer, the bool marks if it has answered
pub revalidation: Option<bool>,
/// communication channels between the peer data and its active connection
pub channels: Option<PeerChannels>,
}

impl PeerData {
Expand All @@ -292,6 +330,7 @@ impl PeerData {
last_ping_hash: None,
find_node_request: None,
revalidation: None,
channels: None,
}
}

Expand Down
17 changes: 12 additions & 5 deletions crates/networking/p2p/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ use k256::{
ecdsa::SigningKey,
elliptic_curve::{sec1::ToEncodedPoint, PublicKey},
};
use kademlia::{bucket_number, KademliaTable, MAX_NODES_PER_BUCKET};
pub use kademlia::KademliaTable;
use kademlia::{bucket_number, MAX_NODES_PER_BUCKET};
use rand::rngs::OsRng;
use rlpx::{connection::RLPxConnection, message::Message as RLPxMessage};
use tokio::{
Expand All @@ -30,8 +31,10 @@ use types::{Endpoint, Node};
pub mod bootnode;
pub(crate) mod discv4;
pub(crate) mod kademlia;
pub mod peer_channels;
pub mod rlpx;
pub(crate) mod snap;
pub mod sync;
pub mod types;

const MAX_DISC_PACKET_SIZE: usize = 1280;
Expand All @@ -42,17 +45,21 @@ const MAX_DISC_PACKET_SIZE: usize = 1280;
// we should bump this limit.
const MAX_MESSAGES_TO_BROADCAST: usize = 1000;

pub fn peer_table(signer: SigningKey) -> Arc<Mutex<KademliaTable>> {
let local_node_id = node_id_from_signing_key(&signer);
Arc::new(Mutex::new(KademliaTable::new(local_node_id)))
}

pub async fn start_network(
udp_addr: SocketAddr,
tcp_addr: SocketAddr,
bootnodes: Vec<BootNode>,
signer: SigningKey,
peer_table: Arc<Mutex<KademliaTable>>,
storage: Store,
) {
info!("Starting discovery service at {udp_addr}");
info!("Listening for requests at {tcp_addr}");
let local_node_id = node_id_from_signing_key(&signer);
let table = Arc::new(Mutex::new(KademliaTable::new(local_node_id)));
let (channel_broadcast_send_end, _) = tokio::sync::broadcast::channel::<(
tokio::task::Id,
Arc<RLPxMessage>,
Expand All @@ -61,15 +68,15 @@ pub async fn start_network(
udp_addr,
signer.clone(),
storage.clone(),
table.clone(),
peer_table.clone(),
bootnodes,
channel_broadcast_send_end.clone(),
));
let server_handle = tokio::spawn(serve_requests(
tcp_addr,
signer.clone(),
storage.clone(),
table.clone(),
peer_table.clone(),
channel_broadcast_send_end,
));

Expand Down
Loading