From ee5e135b23824a6ce2e312873c11c487f34476da Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Fri, 26 Apr 2024 14:06:04 -0400 Subject: [PATCH 01/18] main: init remove fake networking --- .../kns_indexer/kns_indexer/src/lib.rs | 8 ++--- kinode/src/main.rs | 31 +++++++------------ kinode/src/net/mod.rs | 18 ----------- 3 files changed, 16 insertions(+), 41 deletions(-) diff --git a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs index 97c4dfa7f..2d99b8d12 100644 --- a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs +++ b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs @@ -17,6 +17,7 @@ wit_bindgen::generate!({ // perhaps a constant in process_lib? const KNS_OPTIMISM_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; +const KNS_LOCAL_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; #[derive(Clone, Debug, Serialize, Deserialize)] struct State { @@ -100,7 +101,6 @@ sol! { } fn subscribe_to_logs(eth_provider: ð::Provider, from_block: u64, filter: eth::Filter) { - #[cfg(not(feature = "simulation-mode"))] loop { match eth_provider.subscribe(1, filter.clone().from_block(from_block)) { Ok(()) => break, @@ -111,14 +111,15 @@ fn subscribe_to_logs(eth_provider: ð::Provider, from_block: u64, filter: eth: } } } - #[cfg(not(feature = "simulation-mode"))] println!("subscribed to logs successfully"); } call_init!(init); fn init(our: Address) { + #[cfg(feature = "simulation-mode")] + let (chain_id, contract_address) = (31337, KNS_LOCAL_ADDRESS.to_string()); + #[cfg(not(feature = "simulation-mode"))] let (chain_id, contract_address) = (10, KNS_OPTIMISM_ADDRESS.to_string()); - println!("indexing on contract address {}", contract_address); // if we have state, load it in @@ -182,7 +183,6 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> { let eth_provider = eth::Provider::new(state.chain_id, 60); // if block in state is < current_block, get logs from that part. - #[cfg(not(feature = "simulation-mode"))] if state.block < eth_provider.get_block_number().unwrap_or(u64::MAX) { loop { match eth_provider.get_logs(&filter) { diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 3c8ad4113..2ba56e0c4 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -125,6 +125,7 @@ async fn main() { let app = app .arg(arg!(--password "Networking password")) .arg(arg!(--"fake-node-name" "Name of fake node to boot")) + .arg(arg!(--"networking-pk" "Fake networking private key")) .arg( arg!(--detached "Run in detached mode (don't accept input)") .action(clap::ArgAction::SetTrue), @@ -142,10 +143,11 @@ async fn main() { #[cfg(not(feature = "simulation-mode"))] let is_detached = false; #[cfg(feature = "simulation-mode")] - let (password, fake_node_name, is_detached) = ( + let (password, fake_node_name, is_detached, net_pk) = ( matches.get_one::("password"), matches.get_one::("fake-node-name"), *matches.get_one::("detached").unwrap(), + matches.get_one::("networking-pk"), ); let verbose_mode = *matches.get_one::("verbosity").unwrap(); @@ -347,26 +349,27 @@ async fn main() { None => "secret".to_string(), Some(password) => password.to_string(), }; - let (pubkey, networking_keypair) = keygen::generate_networking_key(); let seed = SystemRandom::new(); let mut jwt_secret = [0u8, 32]; ring::rand::SecureRandom::fill(&seed, &mut jwt_secret).unwrap(); + let net_pk_bytes = hex::decode(net_pk.unwrap()).unwrap(); + + let networking_keypair = signature::Ed25519KeyPair::from_pkcs8( + &net_pk_bytes, + ).expect("failed to parse networking private key"); + let our = Identity { name: name.clone(), - networking_key: pubkey, + networking_key: format!("0x{}", hex::encode(networking_keypair.public_key().as_ref())), ws_routing: None, allowed_routers: vec![], }; - let decoded_keyfile = Keyfile { username: name.clone(), routers: vec![], - networking_keypair: signature::Ed25519KeyPair::from_pkcs8( - networking_keypair.as_ref(), - ) - .unwrap(), + networking_keypair, jwt_secret_bytes: jwt_secret.to_vec(), file_key: keygen::generate_file_key(), }; @@ -375,7 +378,7 @@ async fn main() { password_hash, name.clone(), decoded_keyfile.routers.clone(), - networking_keypair.as_ref(), + &net_pk_bytes, &decoded_keyfile.jwt_secret_bytes, &decoded_keyfile.file_key, ); @@ -493,7 +496,6 @@ async fn main() { }) .collect(), )); - #[cfg(not(feature = "simulation-mode"))] tasks.spawn(net::networking( our.clone(), our_ip.to_string(), @@ -506,15 +508,6 @@ async fn main() { register::KNS_OPTIMISM_ADDRESS.to_string(), *matches.get_one::("reveal-ip").unwrap_or(&true), )); - #[cfg(feature = "simulation-mode")] - tasks.spawn(net::mock_client( - *ws_networking_port.unwrap_or(&9000), - our.name.clone(), - kernel_message_sender.clone(), - net_message_receiver, - print_sender.clone(), - network_error_sender, - )); tasks.spawn(state::state_sender( our.name.clone(), kernel_message_sender.clone(), diff --git a/kinode/src/net/mod.rs b/kinode/src/net/mod.rs index f2631b4e2..c99597293 100644 --- a/kinode/src/net/mod.rs +++ b/kinode/src/net/mod.rs @@ -1,4 +1,3 @@ -#[cfg(not(feature = "simulation-mode"))] use { anyhow::{anyhow, Result}, dashmap::DashMap, @@ -14,15 +13,10 @@ use { }, }; -//#[cfg(not(feature = "simulation-mode"))] mod types; -#[cfg(not(feature = "simulation-mode"))] mod utils; -#[cfg(not(feature = "simulation-mode"))] pub use crate::net::types::*; -#[cfg(not(feature = "simulation-mode"))] pub use crate::net::utils::*; -#[cfg(not(feature = "simulation-mode"))] use lib::types::core::*; // Re-export for testing. @@ -32,16 +26,13 @@ mod mock; pub use mock::mock_client; // only used in connection initialization, otherwise, nacks and Responses are only used for "timeouts" -#[cfg(not(feature = "simulation-mode"))] const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); /// 10 MB -- TODO analyze as desired, apps can always chunk data into many messages /// note that this only applies to cross-network messages, not local ones. -#[cfg(not(feature = "simulation-mode"))] const MESSAGE_MAX_SIZE: u32 = 10_485_800; /// Entry point from the main kernel task. Runs forever, spawns listener and sender tasks. -#[cfg(not(feature = "simulation-mode"))] pub async fn networking( our: Identity, our_ip: String, @@ -119,7 +110,6 @@ pub async fn networking( } } -#[cfg(not(feature = "simulation-mode"))] async fn indirect_networking( our: Identity, our_ip: String, @@ -245,7 +235,6 @@ async fn indirect_networking( } } -#[cfg(not(feature = "simulation-mode"))] async fn connect_to_routers( our: Identity, our_ip: String, @@ -292,7 +281,6 @@ async fn connect_to_routers( Ok(()) } -#[cfg(not(feature = "simulation-mode"))] async fn direct_networking( our: Identity, our_ip: String, @@ -475,7 +463,6 @@ async fn direct_networking( } } -#[cfg(not(feature = "simulation-mode"))] async fn establish_new_peer_connection( our: Identity, our_ip: String, @@ -575,7 +562,6 @@ async fn establish_new_peer_connection( } } -#[cfg(not(feature = "simulation-mode"))] async fn init_connection_via_router( our: &Identity, our_ip: &str, @@ -621,7 +607,6 @@ async fn init_connection_via_router( false } -#[cfg(not(feature = "simulation-mode"))] async fn recv_connection( our: &Identity, our_ip: &str, @@ -702,7 +687,6 @@ async fn recv_connection( )) } -#[cfg(not(feature = "simulation-mode"))] async fn recv_connection_via_router( our: &Identity, our_ip: &str, @@ -781,7 +765,6 @@ async fn recv_connection_via_router( )) } -#[cfg(not(feature = "simulation-mode"))] async fn init_connection( our: &Identity, our_ip: &str, @@ -868,7 +851,6 @@ async fn init_connection( } /// net module only handles incoming local requests, will never return a response -#[cfg(not(feature = "simulation-mode"))] async fn handle_local_message( our: &Identity, our_ip: &str, From 1a6d8fa13c34b76cf14e912f46064acde1433f62 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Mon, 29 Apr 2024 12:02:51 -0400 Subject: [PATCH 02/18] add chain checking packages --- Cargo.lock | 72 +++++++++++++++++++++++++++++++++++++++++++++-- kinode/Cargo.toml | 4 +++ 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d5621431a..6fd71a95d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,6 +90,17 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" +[[package]] +name = "alloy-consensus" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy?rev=6f8ebb4#6f8ebb45afca1a201a11d421ec46db0f7a1d8d08" +dependencies = [ + "alloy-eips 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=6f8ebb4)", + "alloy-network", + "alloy-primitives 0.6.4", + "alloy-rlp", +] + [[package]] name = "alloy-consensus" version = "0.1.0" @@ -104,6 +115,38 @@ dependencies = [ "sha2", ] +[[package]] +name = "alloy-contract" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy?rev=6f8ebb4#6f8ebb45afca1a201a11d421ec46db0f7a1d8d08" +dependencies = [ + "alloy-dyn-abi", + "alloy-json-abi", + "alloy-primitives 0.6.4", + "alloy-providers", + "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=6f8ebb4)", + "alloy-sol-types 0.6.4", + "alloy-transport 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=6f8ebb4)", + "thiserror", +] + +[[package]] +name = "alloy-dyn-abi" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2919acdad13336bc5dc26b636cdd6892c2f27fb0d4a58320a00c2713cf6a4e9a" +dependencies = [ + "alloy-json-abi", + "alloy-primitives 0.6.4", + "alloy-sol-type-parser", + "alloy-sol-types 0.6.4", + "const-hex", + "itoa", + "serde", + "serde_json", + "winnow 0.6.6", +] + [[package]] name = "alloy-eips" version = "0.1.0" @@ -138,6 +181,18 @@ dependencies = [ "serde", ] +[[package]] +name = "alloy-json-abi" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ed0f2a6c3a1c947b4508522a53a190dba8f94dcd4e3e1a5af945a498e78f2f" +dependencies = [ + "alloy-primitives 0.6.4", + "alloy-sol-type-parser", + "serde", + "serde_json", +] + [[package]] name = "alloy-json-rpc" version = "0.1.0" @@ -325,7 +380,7 @@ name = "alloy-rpc-types" version = "0.1.0" source = "git+https://github.com/alloy-rs/alloy?rev=cad7935#cad7935d69f433e45d190902e58b1c996b35adfa" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=cad7935)", "alloy-eips 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=cad7935)", "alloy-genesis", "alloy-primitives 0.7.0", @@ -414,6 +469,15 @@ dependencies = [ "syn-solidity 0.7.0", ] +[[package]] +name = "alloy-sol-type-parser" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0045cc89524e1451ccf33e8581355b6027ac7c6e494bb02959d4213ad0d8e91d" +dependencies = [ + "winnow 0.6.6", +] + [[package]] name = "alloy-sol-types" version = "0.6.4" @@ -2603,7 +2667,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2 0.5.6", + "socket2 0.4.10", "tokio", "tower-service", "tracing", @@ -2985,6 +3049,9 @@ name = "kinode" version = "0.7.1" dependencies = [ "aes-gcm", + "alloy-consensus 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=6f8ebb4)", + "alloy-contract", + "alloy-network", "alloy-primitives 0.6.4", "alloy-providers", "alloy-pubsub", @@ -3037,6 +3104,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha2", + "sha3", "snow", "static_dir", "thiserror", diff --git a/kinode/Cargo.toml b/kinode/Cargo.toml index 1bb145a00..9173b720c 100644 --- a/kinode/Cargo.toml +++ b/kinode/Cargo.toml @@ -26,11 +26,14 @@ simulation-mode = [] [dependencies] aes-gcm = "0.10.3" +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4", features = ["ws"]} alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } alloy-providers = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "6f8ebb4" } alloy-primitives = "0.6.2" alloy-sol-macro = "0.6.2" alloy-sol-types = "0.6.2" @@ -88,3 +91,4 @@ wasi-common = "19.0.1" wasmtime = "19.0.1" wasmtime-wasi = "19.0.1" zip = "1.1.1" +sha3 = "0.10.8" From d5d25bbcaa686fb23c62caa8b9bc44ad0b741287 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Mon, 29 Apr 2024 12:03:19 -0400 Subject: [PATCH 03/18] move fakechain node registration from kit to runtime --- .../kns_indexer/kns_indexer/src/lib.rs | 18 ++++++++++++++---- kinode/src/eth/default_providers_mainnet.json | 2 +- kinode/src/main.rs | 15 +++++++++++++-- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs index c6492d7b9..94c77df02 100644 --- a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs +++ b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs @@ -18,7 +18,6 @@ wit_bindgen::generate!({ // perhaps a constant in process_lib? const KNS_OPTIMISM_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; const KNS_LOCAL_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; -const KNS_FIRST_BLOCK: u64 = 114_923_786; #[derive(Clone, Debug, Serialize, Deserialize)] struct State { @@ -123,6 +122,11 @@ fn init(our: Address) { let (chain_id, contract_address) = (10, KNS_OPTIMISM_ADDRESS.to_string()); println!("indexing on contract address {}", contract_address); + #[cfg(feature = "simulation-mode")] + let kns_first_block: u64 = 1; + #[cfg(not(feature = "simulation-mode"))] + let kns_first_block: u64 = 114_923_786; + // if we have state, load it in let state: State = match get_typed_state(|bytes| Ok(bincode::deserialize::(bytes)?)) { Some(s) => { @@ -134,7 +138,7 @@ fn init(our: Address) { contract_address, names: HashMap::new(), nodes: HashMap::new(), - block: KNS_FIRST_BLOCK, + block: kns_first_block, } } else { println!("loading in {} persisted PKI entries", s.nodes.len()); @@ -146,7 +150,7 @@ fn init(our: Address) { contract_address: contract_address.clone(), names: HashMap::new(), nodes: HashMap::new(), - block: KNS_FIRST_BLOCK, + block: kns_first_block, }, }; @@ -183,6 +187,11 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> { // if they do time out, we try them again let eth_provider = eth::Provider::new(state.chain_id, 60); + println!( + "subscribing, state.block: {}, chain_id: {}", + state.block, state.chain_id + ); + // if block in state is < current_block, get logs from that part. if state.block < eth_provider.get_block_number().unwrap_or(u64::MAX) { loop { @@ -198,7 +207,8 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> { } break; } - Err(_) => { + Err(e) => { + println!("got some kind of error: {:?}", e); println!("failed to fetch logs! trying again in 5s..."); std::thread::sleep(std::time::Duration::from_secs(5)); continue; diff --git a/kinode/src/eth/default_providers_mainnet.json b/kinode/src/eth/default_providers_mainnet.json index 9f8c00bf5..def95cc89 100644 --- a/kinode/src/eth/default_providers_mainnet.json +++ b/kinode/src/eth/default_providers_mainnet.json @@ -3,7 +3,7 @@ "chain_id": 31337, "trusted": true, "provider": { - "RpcUrl": "wss://localhost:8545" + "RpcUrl": "ws://localhost:8545" } }, { diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 4665e4f6e..46d70843f 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use tokio::sync::mpsc; mod eth; +mod fakenet; mod http; mod kernel; mod keygen; @@ -136,6 +137,8 @@ async fn main() { fake_node_name.cloned(), password.cloned(), home_directory_path, + ws_networking_port.cloned(), + http_server_port, ) .await; #[cfg(not(feature = "simulation-mode"))] @@ -450,11 +453,13 @@ async fn setup_ws_networking(ws_networking_port: Option) -> (tokio::net::Tc } } -/// TODO: writeup. +/// On simulation mode, we either boot from existing keys, or generate and post keys to chain. pub async fn simulate_node( fake_node_name: Option, password: Option, home_directory_path: &str, + router_port: Option, + node_port: u16, ) -> (Identity, Vec, Keyfile) { match fake_node_name { None => { @@ -474,7 +479,7 @@ pub async fn simulate_node( "0x{}", hex::encode(decoded.networking_keypair.public_key().as_ref()) ), - ws_routing: None, // TODO: Define WebSocket routing logic + ws_routing: None, allowed_routers: decoded.routers.clone(), }; (identity, keyfile, decoded) @@ -488,6 +493,12 @@ pub async fn simulate_node( let mut jwt_secret = [0u8; 32]; ring::rand::SecureRandom::fill(&seed, &mut jwt_secret).unwrap(); + let router_port = router_port.unwrap_or(8545); + + fakenet::register_local(&name, node_port, &pubkey, router_port) + .await + .unwrap(); + let identity = Identity { name: name.clone(), networking_key: pubkey, From e977d0e8d0b04330649d2e3c2f5e80451c5e1c10 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Mon, 29 Apr 2024 12:05:49 -0400 Subject: [PATCH 04/18] add missing fakenet dir --- kinode/src/fakenet/helpers.rs | 122 ++++++++++++++++++++++++++++++++++ kinode/src/fakenet/mod.rs | 99 +++++++++++++++++++++++++++ 2 files changed, 221 insertions(+) create mode 100644 kinode/src/fakenet/helpers.rs create mode 100644 kinode/src/fakenet/mod.rs diff --git a/kinode/src/fakenet/helpers.rs b/kinode/src/fakenet/helpers.rs new file mode 100644 index 000000000..569a80612 --- /dev/null +++ b/kinode/src/fakenet/helpers.rs @@ -0,0 +1,122 @@ +use alloy_sol_macro::sol; +use ring::pkcs8::Document; +use ring::rand::SystemRandom; +use ring::signature::{self, KeyPair}; +use sha3::{Digest, Keccak256}; + +sol! { + #[sol(rpc)] + contract RegisterHelpers { + function register( + bytes calldata _name, + address _to, + bytes[] calldata _data + ) external payable returns (uint256 nodeId_); + + function setKey(bytes32 _node, bytes32 _key); + + function setAllIp( + bytes32 _node, + uint128 _ip, + uint16 _ws, + uint16 _wt, + uint16 _tcp, + uint16 _udp + ); + + function _getOwner(bytes32 node) internal pure returns (address); + } +} + +pub fn dns_encode_fqdn(name: &str) -> Vec { + let bytes_name = name.as_bytes(); + let mut dns_name = Vec::new(); + + let mut last_pos = 0; + for (i, &b) in bytes_name.iter().enumerate() { + if b == b'.' { + if i != last_pos { + dns_name.push((i - last_pos) as u8); // length of the label + dns_name.extend_from_slice(&bytes_name[last_pos..i]); + } + last_pos = i + 1; + } + } + + if last_pos < bytes_name.len() { + dns_name.push((bytes_name.len() - last_pos) as u8); + dns_name.extend_from_slice(&bytes_name[last_pos..]); + } + + dns_name.push(0); + + dns_name +} + +pub fn encode_namehash(name: &str) -> [u8; 32] { + let mut node = [0u8; 32]; + if name.is_empty() { + return node; + } + let mut labels: Vec<&str> = name.split('.').collect(); + labels.reverse(); + + for label in labels.iter() { + let mut hasher = Keccak256::new(); + hasher.update(label.as_bytes()); + let labelhash = hasher.finalize(); + hasher = Keccak256::new(); + hasher.update(&node); + hasher.update(labelhash); + node = hasher.finalize().into(); + } + node +} + +pub fn generate_networking_key() -> (String, Document) { + let rng = SystemRandom::new(); + let doc = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); + let key_pair = signature::Ed25519KeyPair::from_pkcs8(doc.as_ref()).unwrap(); + (hex::encode(key_pair.public_key().as_ref()), doc) +} + +#[cfg(test)] +mod test { + use super::encode_namehash; + + #[test] + fn test_namehash() { + // Test cases, same than used @ EIP137 `https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md` + let cases = vec![ + ( + "", + &[ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + ), + ( + "eth", + &[ + 0x93, 0xcd, 0xeb, 0x70, 0x8b, 0x75, 0x45, 0xdc, 0x66, 0x8e, 0xb9, 0x28, 0x1, + 0x76, 0x16, 0x9d, 0x1c, 0x33, 0xcf, 0xd8, 0xed, 0x6f, 0x4, 0x69, 0xa, 0xb, + 0xcc, 0x88, 0xa9, 0x3f, 0xc4, 0xae, + ], + ), + ( + "foo.eth", + &[ + 0xde, 0x9b, 0x9, 0xfd, 0x7c, 0x5f, 0x90, 0x1e, 0x23, 0xa3, 0xf1, 0x9f, 0xec, + 0xc5, 0x48, 0x28, 0xe9, 0xc8, 0x48, 0x53, 0x98, 0x1, 0xe8, 0x65, 0x91, 0xbd, + 0x98, 0x1, 0xb0, 0x19, 0xf8, 0x4f, + ], + ), + ]; + + for (name, expected_namehash) in cases { + let namehash: &[u8] = &encode_namehash(name); + assert_eq!(namehash, expected_namehash); + } + } +} diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs new file mode 100644 index 000000000..4aafa8079 --- /dev/null +++ b/kinode/src/fakenet/mod.rs @@ -0,0 +1,99 @@ +use alloy_consensus::TxLegacy; +use alloy_network::{Transaction, TxKind}; +use alloy_primitives::Address; +use alloy_providers::provider::{Provider, TempProvider}; +use alloy_rpc_client::ClientBuilder; +use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; +use alloy_signer::{LocalWallet, Signer, SignerSync}; +use alloy_sol_types::SolCall; +use alloy_transport_ws::WsConnect; +use std::str::FromStr; + +pub mod helpers; + +pub use helpers::RegisterHelpers::*; +pub use helpers::*; + +pub async fn register_local( + name: &str, + port: u16, + pubkey: &str, + router_port: u16, +) -> Result<(), anyhow::Error> { + let wallet = LocalWallet::from_str( + "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80", + )?; + + let dotdev = Address::from_str("0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9")?; + let kns = Address::from_str("0x5FbDB2315678afecb367f032d93F642f64180aa3")?; + + let endpoint = format!("ws://localhost:{}", router_port); + let ws = WsConnect { + url: endpoint, + auth: None, + }; + + let client = ClientBuilder::default().ws(ws).await?; + let provider = Provider::new_with_client(client); + + let fqdn = dns_encode_fqdn(name); + let namehash = encode_namehash(name); + + let ip: u128 = 0x7F000001; // localhost IP (127.0.0.1) + + let set_ip = setAllIpCall { + _node: namehash.into(), + _ip: ip, + _ws: port, + _wt: 0, + _tcp: 0, + _udp: 0, + } + .abi_encode(); + + let set_key = setKeyCall { + _node: namehash.into(), + _key: pubkey.parse()?, + } + .abi_encode(); + + // TODO: set this up so that we do not call .register on something twice. + // let existsCall = _getOwnerCall { + // node: namehash.into(), + // } + // .abi_encode(); + + // let tx = TransactionRequest::default() + // .to(Some(dotdev)) + // .input(TransactionInput::new(existsCall.into())); + + // let exists = provider.call(tx, None).await?; + + let register = registerCall { + _name: fqdn.into(), + _to: Address::from_str("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266")?, + _data: vec![set_ip.into(), set_key.into()], + } + .abi_encode(); + + let nonce = provider + .get_transaction_count(wallet.address(), None) + .await?; + let mut tx = TxLegacy { + to: TxKind::Call(dotdev), + nonce: nonce.to::(), + input: register.into(), + chain_id: Some(31337), + gas_limit: 3000000, + gas_price: 100000000000, + ..Default::default() + }; + + let sig = wallet.sign_transaction_sync(&mut tx)?; + let signed_tx = tx.into_signed(sig); + let mut buf = vec![]; + signed_tx.encode_signed(&mut buf); + + let _tx_hash = provider.send_raw_transaction(buf.into()).await?; + Ok(()) +} From af877a03c7df8f3132b69a0d36356c8d928907f4 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Mon, 29 Apr 2024 13:20:10 -0400 Subject: [PATCH 05/18] fake indirect node -> direct --- kinode/src/main.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 46d70843f..4ebce672c 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -130,7 +130,6 @@ async fn main() { mpsc::channel(TERMINAL_CHANNEL_CAPACITY); let our_ip = find_public_ip().await; - let (wc_tcp_handle, flag_used) = setup_ws_networking(ws_networking_port.cloned()).await; #[cfg(feature = "simulation-mode")] let (our, encoded_keyfile, decoded_keyfile) = simulate_node( @@ -141,6 +140,9 @@ async fn main() { http_server_port, ) .await; + + #[cfg(not(feature = "simulation-mode"))] + let (wc_tcp_handle, flag_used) = setup_ws_networking(ws_networking_port.cloned()).await; #[cfg(not(feature = "simulation-mode"))] let (our, encoded_keyfile, decoded_keyfile) = serve_register_fe( &home_directory_path, @@ -479,7 +481,7 @@ pub async fn simulate_node( "0x{}", hex::encode(decoded.networking_keypair.public_key().as_ref()) ), - ws_routing: None, + ws_routing: Some(("127.0.0.1".to_string(), node_port)), allowed_routers: decoded.routers.clone(), }; (identity, keyfile, decoded) @@ -502,7 +504,7 @@ pub async fn simulate_node( let identity = Identity { name: name.clone(), networking_key: pubkey, - ws_routing: None, + ws_routing: Some(("127.0.0.1".to_string(), node_port)), allowed_routers: vec![], }; From 10c2632f20c0f419d939a8947d1ab9089497d759 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 30 Apr 2024 13:31:10 -0400 Subject: [PATCH 06/18] fakenet: reregister kns if exitsts --- kinode/src/fakenet/helpers.rs | 14 ++----- kinode/src/fakenet/mod.rs | 70 +++++++++++++++++++++++++---------- 2 files changed, 54 insertions(+), 30 deletions(-) diff --git a/kinode/src/fakenet/helpers.rs b/kinode/src/fakenet/helpers.rs index 569a80612..3df842067 100644 --- a/kinode/src/fakenet/helpers.rs +++ b/kinode/src/fakenet/helpers.rs @@ -1,7 +1,4 @@ use alloy_sol_macro::sol; -use ring::pkcs8::Document; -use ring::rand::SystemRandom; -use ring::signature::{self, KeyPair}; use sha3::{Digest, Keccak256}; sol! { @@ -24,7 +21,9 @@ sol! { uint16 _udp ); - function _getOwner(bytes32 node) internal pure returns (address); + function ownerOf(uint256 node) returns (address); + + function multicall(bytes[] calldata data); } } @@ -73,13 +72,6 @@ pub fn encode_namehash(name: &str) -> [u8; 32] { node } -pub fn generate_networking_key() -> (String, Document) { - let rng = SystemRandom::new(); - let doc = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); - let key_pair = signature::Ed25519KeyPair::from_pkcs8(doc.as_ref()).unwrap(); - (hex::encode(key_pair.public_key().as_ref()), doc) -} - #[cfg(test)] mod test { use super::encode_namehash; diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs index 4aafa8079..c3c24dc35 100644 --- a/kinode/src/fakenet/mod.rs +++ b/kinode/src/fakenet/mod.rs @@ -1,6 +1,6 @@ use alloy_consensus::TxLegacy; use alloy_network::{Transaction, TxKind}; -use alloy_primitives::Address; +use alloy_primitives::{Address, U256, B256}; use alloy_providers::provider::{Provider, TempProvider}; use alloy_rpc_client::ClientBuilder; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; @@ -38,6 +38,9 @@ pub async fn register_local( let fqdn = dns_encode_fqdn(name); let namehash = encode_namehash(name); + // todo: find a better way? + let namehash_bint: B256 = namehash.into(); + let namehash_uint: U256 = namehash_bint.into(); let ip: u128 = 0x7F000001; // localhost IP (127.0.0.1) @@ -57,32 +60,60 @@ pub async fn register_local( } .abi_encode(); - // TODO: set this up so that we do not call .register on something twice. - // let existsCall = _getOwnerCall { - // node: namehash.into(), - // } - // .abi_encode(); - - // let tx = TransactionRequest::default() - // .to(Some(dotdev)) - // .input(TransactionInput::new(existsCall.into())); - - // let exists = provider.call(tx, None).await?; - - let register = registerCall { - _name: fqdn.into(), - _to: Address::from_str("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266")?, - _data: vec![set_ip.into(), set_key.into()], + let exists_call = ownerOfCall { + node: namehash_uint, } .abi_encode(); + let exists_tx = TransactionRequest::default() + .to(Some(dotdev)) + .input(TransactionInput::new(exists_call.into())); + + + let exists = provider.call(exists_tx, None).await; + + let (call_input, to) = match exists { + Err(_e) => { + // name is not taken, register normally + let register = registerCall { + _name: fqdn.into(), + _to: Address::from_str("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266")?, + _data: vec![set_ip.into(), set_key.into()], + } + .abi_encode(); + + (register, dotdev) + } + Ok(_owner) => { + // name is taken, call setAllIp an setKey directly with multicall + let set_ip = setAllIpCall { + _node: namehash.into(), + _ip: ip, + _ws: port, + _wt: 0, + _tcp: 0, + _udp: 0, + }; + let set_key = setKeyCall { + _node: namehash.into(), + _key: pubkey.parse()?, + }; + + let multicall = multicallCall { + data: vec![set_ip.abi_encode(), set_key.abi_encode()], + }.abi_encode(); + + (multicall, kns) + } + }; let nonce = provider .get_transaction_count(wallet.address(), None) .await?; + let mut tx = TxLegacy { - to: TxKind::Call(dotdev), + to: TxKind::Call(to), nonce: nonce.to::(), - input: register.into(), + input: call_input.into(), chain_id: Some(31337), gas_limit: 3000000, gas_price: 100000000000, @@ -95,5 +126,6 @@ pub async fn register_local( signed_tx.encode_signed(&mut buf); let _tx_hash = provider.send_raw_transaction(buf.into()).await?; + Ok(()) } From d6711d695be5642646b291cb5420ef8a0b353ead Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 30 Apr 2024 17:31:37 +0000 Subject: [PATCH 07/18] Format Rust code using rustfmt --- kinode/src/fakenet/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs index c3c24dc35..bd27afd40 100644 --- a/kinode/src/fakenet/mod.rs +++ b/kinode/src/fakenet/mod.rs @@ -1,6 +1,6 @@ use alloy_consensus::TxLegacy; use alloy_network::{Transaction, TxKind}; -use alloy_primitives::{Address, U256, B256}; +use alloy_primitives::{Address, B256, U256}; use alloy_providers::provider::{Provider, TempProvider}; use alloy_rpc_client::ClientBuilder; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; @@ -38,7 +38,7 @@ pub async fn register_local( let fqdn = dns_encode_fqdn(name); let namehash = encode_namehash(name); - // todo: find a better way? + // todo: find a better way? let namehash_bint: B256 = namehash.into(); let namehash_uint: U256 = namehash_bint.into(); @@ -61,7 +61,7 @@ pub async fn register_local( .abi_encode(); let exists_call = ownerOfCall { - node: namehash_uint, + node: namehash_uint, } .abi_encode(); @@ -69,7 +69,6 @@ pub async fn register_local( .to(Some(dotdev)) .input(TransactionInput::new(exists_call.into())); - let exists = provider.call(exists_tx, None).await; let (call_input, to) = match exists { @@ -81,7 +80,7 @@ pub async fn register_local( _data: vec![set_ip.into(), set_key.into()], } .abi_encode(); - + (register, dotdev) } Ok(_owner) => { @@ -101,7 +100,8 @@ pub async fn register_local( let multicall = multicallCall { data: vec![set_ip.abi_encode(), set_key.abi_encode()], - }.abi_encode(); + } + .abi_encode(); (multicall, kns) } From 8fb147239d5a2c0283da0d8b0eedb16594ecfafb Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Wed, 1 May 2024 16:21:07 -0400 Subject: [PATCH 08/18] net: remove mock --- kinode/src/main.rs | 4 +- kinode/src/net/mock.rs | 85 ------------------------------------------ kinode/src/net/mod.rs | 3 -- 3 files changed, 3 insertions(+), 89 deletions(-) delete mode 100644 kinode/src/net/mock.rs diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 4ebce672c..77532e9cd 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -3,13 +3,14 @@ use anyhow::Result; use clap::{arg, value_parser, Command}; use lib::types::core::*; -//#[cfg(feature = "simulation-mode")] +#[cfg(feature = "simulation-mode")] use ring::{rand::SystemRandom, signature, signature::KeyPair}; use std::env; use std::sync::Arc; use tokio::sync::mpsc; mod eth; +#[cfg(feature = "simulation-mode")] mod fakenet; mod http; mod kernel; @@ -456,6 +457,7 @@ async fn setup_ws_networking(ws_networking_port: Option) -> (tokio::net::Tc } /// On simulation mode, we either boot from existing keys, or generate and post keys to chain. +#[cfg(feature = "simulation-mode")] pub async fn simulate_node( fake_node_name: Option, password: Option, diff --git a/kinode/src/net/mock.rs b/kinode/src/net/mock.rs deleted file mode 100644 index d0dfa62e5..000000000 --- a/kinode/src/net/mock.rs +++ /dev/null @@ -1,85 +0,0 @@ -use futures::{SinkExt, StreamExt}; -use tokio::sync::mpsc; -use tokio_tungstenite::{ - connect_async, - tungstenite::protocol::Message::{Binary, Text}, -}; - -use lib::types::core as types; - -type Sender = mpsc::Sender; -type Receiver = mpsc::Receiver; - -pub async fn mock_client( - port: u16, - node_identity: types::NodeId, - send_to_loop: Sender, - mut recv_from_loop: Receiver, - print_tx: types::PrintSender, - _network_error_sender: types::NetworkErrorSender, -) -> anyhow::Result<()> { - let url = format!("ws://127.0.0.1:{}", port); - - let (ws_stream, _) = connect_async(url).await?; - let (mut send_to_ws, mut recv_from_ws) = ws_stream.split(); - - // Send node identity - send_to_ws.send(Text(node_identity.clone())).await?; - - loop { - tokio::select! { - Some(kernel_message) = recv_from_loop.recv() => { - if kernel_message.target.node != node_identity { - // Serialize and send the message through WebSocket - // println!("{}:mock: outgoing {}\r", node_identity ,kernel_message); - let message = Binary(rmp_serde::to_vec(&kernel_message)?); - send_to_ws.send(message).await?; - } - }, - Some(Ok(message)) = recv_from_ws.next() => { - // Deserialize and forward the message to the loop - // println!("{}:mock: incoming {}\r", node_identity, message); - if let Binary(ref bin) = message { - let km: types::KernelMessage = rmp_serde::from_slice(bin)?; - if km.target.process == "net:distro:sys" { - if let types::Message::Request(types::Request { ref body, .. }) = km.message { - print_tx - .send(types::Printout { - verbosity: 0, - content: format!( - "\x1b[3;32m{}: {}\x1b[0m", - km.source.node, - std::str::from_utf8(body).unwrap_or("!!message parse error!!") - ), - }) - .await?; - send_to_loop - .send(types::KernelMessage { - id: km.id, - source: types::Address { - node: node_identity.clone(), - process: types::ProcessId::new(Some("net"), "distro", "sys"), - }, - target: km.rsvp.as_ref().unwrap_or(&km.source).clone(), - rsvp: None, - message: types::Message::Response(( - types::Response { - inherit: false, - body: "delivered".as_bytes().to_vec(), - metadata: None, - capabilities: vec![], - }, - None, - )), - lazy_load_blob: None, - }) - .await?; - } - } else { - send_to_loop.send(km).await?; - } - } - }, - } - } -} diff --git a/kinode/src/net/mod.rs b/kinode/src/net/mod.rs index 7837101d1..8c137f44c 100644 --- a/kinode/src/net/mod.rs +++ b/kinode/src/net/mod.rs @@ -1,6 +1,3 @@ -#[cfg(feature = "simulation-mode")] -pub mod mock; - pub mod types; pub mod utils; pub mod ws; From c4227b46697b90d958907cf32b7dad18014097fc Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Fri, 3 May 2024 12:39:24 -0400 Subject: [PATCH 09/18] fakechain: fix ws assigning --- kinode/src/fakenet/mod.rs | 39 ++++++++++++++++++++++++++++++------- kinode/src/main.rs | 41 ++++++++++++++++++++++++++------------- kinode/src/register.rs | 2 +- 3 files changed, 60 insertions(+), 22 deletions(-) diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs index bd27afd40..0b9b92dc6 100644 --- a/kinode/src/fakenet/mod.rs +++ b/kinode/src/fakenet/mod.rs @@ -7,27 +7,52 @@ use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use alloy_signer::{LocalWallet, Signer, SignerSync}; use alloy_sol_types::SolCall; use alloy_transport_ws::WsConnect; +use lib::core::Identity; use std::str::FromStr; +use std::sync::Arc; pub mod helpers; +use crate::register::assign_ws_routing; pub use helpers::RegisterHelpers::*; pub use helpers::*; +const FAKE_DOTDEV: &str = "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"; +const FAKE_KNS: &str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; + +pub async fn assign_ws_local_helper( + our: &mut Identity, + ws_port: u16, + fakechain_port: u16, +) -> Result<(), anyhow::Error> { + let kns = Address::from_str(FAKE_KNS)?; + let endpoint = format!("ws://localhost:{}", fakechain_port); + + let ws = WsConnect { + url: endpoint, + auth: None, + }; + + let client = ClientBuilder::default().ws(ws).await?; + let provider = Provider::new_with_client(client); + + assign_ws_routing(our, kns, Arc::new(provider), Some(ws_port)).await +} + pub async fn register_local( name: &str, - port: u16, + ws_port: u16, pubkey: &str, - router_port: u16, + fakechain_port: u16, ) -> Result<(), anyhow::Error> { let wallet = LocalWallet::from_str( "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80", )?; - let dotdev = Address::from_str("0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9")?; - let kns = Address::from_str("0x5FbDB2315678afecb367f032d93F642f64180aa3")?; + let dotdev = Address::from_str(FAKE_DOTDEV)?; + let kns = Address::from_str(FAKE_KNS)?; - let endpoint = format!("ws://localhost:{}", router_port); + let endpoint = format!("ws://localhost:{}", fakechain_port); let ws = WsConnect { url: endpoint, auth: None, @@ -47,7 +72,7 @@ pub async fn register_local( let set_ip = setAllIpCall { _node: namehash.into(), _ip: ip, - _ws: port, + _ws: ws_port, _wt: 0, _tcp: 0, _udp: 0, @@ -88,7 +113,7 @@ pub async fn register_local( let set_ip = setAllIpCall { _node: namehash.into(), _ip: ip, - _ws: port, + _ws: ws_port, _wt: 0, _tcp: 0, _udp: 0, diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 77532e9cd..cb4a0acdf 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -64,10 +64,11 @@ async fn main() { let is_detached = false; #[cfg(feature = "simulation-mode")] - let (password, fake_node_name, is_detached) = ( + let (password, fake_node_name, is_detached, fakechain_port) = ( matches.get_one::("password"), matches.get_one::("fake-node-name"), *matches.get_one::("detached").unwrap(), + matches.get_one::("fakechain-port").cloned(), ); // default eth providers/routers @@ -131,19 +132,18 @@ async fn main() { mpsc::channel(TERMINAL_CHANNEL_CAPACITY); let our_ip = find_public_ip().await; + let (wc_tcp_handle, flag_used) = setup_ws_networking(ws_networking_port.cloned()).await; #[cfg(feature = "simulation-mode")] let (our, encoded_keyfile, decoded_keyfile) = simulate_node( fake_node_name.cloned(), password.cloned(), home_directory_path, - ws_networking_port.cloned(), - http_server_port, + (wc_tcp_handle, flag_used), + fakechain_port, ) .await; - #[cfg(not(feature = "simulation-mode"))] - let (wc_tcp_handle, flag_used) = setup_ws_networking(ws_networking_port.cloned()).await; #[cfg(not(feature = "simulation-mode"))] let (our, encoded_keyfile, decoded_keyfile) = serve_register_fe( &home_directory_path, @@ -462,8 +462,8 @@ pub async fn simulate_node( fake_node_name: Option, password: Option, home_directory_path: &str, - router_port: Option, - node_port: u16, + (ws_networking, _ws_used): (tokio::net::TcpListener, bool), + fakechain_port: Option, ) -> (Identity, Vec, Keyfile) { match fake_node_name { None => { @@ -477,15 +477,24 @@ pub async fn simulate_node( .expect("could not read keyfile"); let decoded = keygen::decode_keyfile(&keyfile, &password) .expect("could not decode keyfile"); - let identity = Identity { + let mut identity = Identity { name: decoded.username.clone(), networking_key: format!( "0x{}", hex::encode(decoded.networking_keypair.public_key().as_ref()) ), - ws_routing: Some(("127.0.0.1".to_string(), node_port)), + ws_routing: None, allowed_routers: decoded.routers.clone(), }; + + fakenet::assign_ws_local_helper( + &mut identity, + ws_networking.local_addr().unwrap().port(), + fakechain_port.unwrap_or(8545), + ) + .await + .unwrap(); + (identity, keyfile, decoded) } } @@ -497,16 +506,17 @@ pub async fn simulate_node( let mut jwt_secret = [0u8; 32]; ring::rand::SecureRandom::fill(&seed, &mut jwt_secret).unwrap(); - let router_port = router_port.unwrap_or(8545); + let fakechain_port: u16 = fakechain_port.unwrap_or(8545); + let ws_port = ws_networking.local_addr().unwrap().port(); - fakenet::register_local(&name, node_port, &pubkey, router_port) + fakenet::register_local(&name, ws_port, &pubkey, fakechain_port) .await .unwrap(); let identity = Identity { name: name.clone(), networking_key: pubkey, - ws_routing: Some(("127.0.0.1".to_string(), node_port)), + ws_routing: Some(("127.0.0.1".into(), ws_port)), allowed_routers: vec![], }; @@ -563,7 +573,7 @@ fn build_command() -> Command { ) .arg( arg!(--"ws-port" "Kinode internal WebSockets protocol port [default: first unbound at or above 9000]") - .alias("network-router-port") + .alias("--ws-port") .value_parser(value_parser!(u16)), ) .arg( @@ -582,7 +592,10 @@ fn build_command() -> Command { let app = app .arg(arg!(--password "Networking password")) .arg(arg!(--"fake-node-name" "Name of fake node to boot")) - .arg(arg!(--"net-pk" "Networking private key")) + .arg( + arg!(--"fakechain-port" "Port to bind to for fakechain") + .value_parser(value_parser!(u16)), + ) .arg( arg!(--detached "Run in detached mode (don't accept input)") .action(clap::ArgAction::SetTrue), diff --git a/kinode/src/register.rs b/kinode/src/register.rs index 46a7343f3..7fdbde040 100644 --- a/kinode/src/register.rs +++ b/kinode/src/register.rs @@ -690,7 +690,7 @@ async fn confirm_change_network_keys( success_response(sender, our.clone(), decoded_keyfile, encoded_keyfile).await } -async fn assign_ws_routing( +pub async fn assign_ws_routing( our: &mut Identity, kns_address: EthAddress, provider: Arc>, From d1adb1b0fc2298c83e3349bd80ae1413fd524274 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Fri, 3 May 2024 17:16:22 -0400 Subject: [PATCH 10/18] fix: add 31337 chain_id port based on flag --- kinode/src/eth/default_providers_mainnet.json | 7 ------- kinode/src/main.rs | 6 ++++++ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/kinode/src/eth/default_providers_mainnet.json b/kinode/src/eth/default_providers_mainnet.json index def95cc89..9eeae49e9 100644 --- a/kinode/src/eth/default_providers_mainnet.json +++ b/kinode/src/eth/default_providers_mainnet.json @@ -1,11 +1,4 @@ [ - { - "chain_id": 31337, - "trusted": true, - "provider": { - "RpcUrl": "ws://localhost:8545" - } - }, { "chain_id": 1, "trusted": false, diff --git a/kinode/src/main.rs b/kinode/src/main.rs index cb4a0acdf..49c150a70 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -87,6 +87,12 @@ async fn main() { provider: lib::eth::NodeOrRpcUrl::RpcUrl(rpc.to_string()), }); } + let local_chain_port = matches.get_one::("fakechain-port").cloned().unwrap_or(8545); + eth_provider_config.push(lib::eth::ProviderConfig { + chain_id: 31337, + trusted: true, + provider: lib::eth::NodeOrRpcUrl::RpcUrl(format!("ws://localhost:{}", local_chain_port)), + }); // kernel receives system messages via this channel, all other modules send messages let (kernel_message_sender, kernel_message_receiver): (MessageSender, MessageReceiver) = From 0edd605a69bc0d33d8ed74b8ccc0da349f64ba97 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 3 May 2024 21:16:50 +0000 Subject: [PATCH 11/18] Format Rust code using rustfmt --- kinode/src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 49c150a70..e4bc157b6 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -87,7 +87,10 @@ async fn main() { provider: lib::eth::NodeOrRpcUrl::RpcUrl(rpc.to_string()), }); } - let local_chain_port = matches.get_one::("fakechain-port").cloned().unwrap_or(8545); + let local_chain_port = matches + .get_one::("fakechain-port") + .cloned() + .unwrap_or(8545); eth_provider_config.push(lib::eth::ProviderConfig { chain_id: 31337, trusted: true, From 3dd7ea8a8144ae32916641e0de0f3683a9cc2b1c Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 15:23:06 -0400 Subject: [PATCH 12/18] kns_indexer: better simulation mode constants --- .../kns_indexer/kns_indexer/src/lib.rs | 43 ++++++++----------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs index f06129b3e..14ccd9edd 100644 --- a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs +++ b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs @@ -14,9 +14,17 @@ wit_bindgen::generate!({ world: "process", }); -// perhaps a constant in process_lib? -const KNS_OPTIMISM_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; -const KNS_LOCAL_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; +const KNS_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; +#[cfg(feature = "simulation-mode")] +const KNS_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; + +const CHAIN_ID: u64 = 10; +#[cfg(feature = "simulation-mode")] +const CHAIN_ID: u64 = 31337; + +const KNS_FIRST_BLOCK: u64 = 114_923_786; +#[cfg(feature = "simulation-mode")] +const KNS_FIRST_BLOCK: u64 = 1; #[derive(Clone, Debug, Serialize, Deserialize)] struct State { @@ -115,33 +123,20 @@ fn subscribe_to_logs(eth_provider: ð::Provider, from_block: u64, filter: eth: call_init!(init); fn init(our: Address) { - #[cfg(feature = "simulation-mode")] - let (chain_id, contract_address) = (31337, KNS_LOCAL_ADDRESS.to_string()); - #[cfg(not(feature = "simulation-mode"))] - let (chain_id, contract_address) = (10, KNS_OPTIMISM_ADDRESS.to_string()); - - #[cfg(not(feature = "simulation-mode"))] - println!("indexing on contract address {}", contract_address); - #[cfg(feature = "simulation-mode")] - println!("simulation mode: not indexing KNS"); - - #[cfg(feature = "simulation-mode")] - let kns_first_block: u64 = 1; - #[cfg(not(feature = "simulation-mode"))] - let kns_first_block: u64 = 114_923_786; + println!("indexing on contract address {}", KNS_CONTRACT_ADDRESS); // if we have state, load it in let state: State = match get_typed_state(|bytes| Ok(bincode::deserialize::(bytes)?)) { Some(s) => { // if chain id or contract address changed from a previous run, reset state - if s.chain_id != chain_id || s.contract_address != contract_address { + if s.chain_id != CHAIN_ID || s.contract_address != KNS_CONTRACT_ADDRESS { println!("resetting state because runtime contract address or chain ID changed"); State { - chain_id, - contract_address, + chain_id: CHAIN_ID, + contract_address: KNS_CONTRACT_ADDRESS, names: HashMap::new(), nodes: HashMap::new(), - block: kns_first_block, + block: KNS_FIRST_BLOCK, } } else { println!("loading in {} persisted PKI entries", s.nodes.len()); @@ -149,11 +144,11 @@ fn init(our: Address) { } } None => State { - chain_id, - contract_address: contract_address.clone(), + chain_id: CHAIN_ID, + contract_address: KNS_CONTRACT_ADDRESS, names: HashMap::new(), nodes: HashMap::new(), - block: kns_first_block, + block: KNS_FIRST_BLOCK, }, }; From 7a60ad6e68d5a2ad9796e4b5b017ddde8ba8c633 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 15:23:21 -0400 Subject: [PATCH 13/18] app_store: simulation mode constants --- kinode/packages/app_store/app_store/src/lib.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/kinode/packages/app_store/app_store/src/lib.rs b/kinode/packages/app_store/app_store/src/lib.rs index 808f60c8b..63d39a75e 100644 --- a/kinode/packages/app_store/app_store/src/lib.rs +++ b/kinode/packages/app_store/app_store/src/lib.rs @@ -40,8 +40,16 @@ use ft_worker_lib::{ const ICON: &str = include_str!("icon"); const CHAIN_ID: u64 = 10; // optimism +#[cfg(feature = "simulation-mode")] +const CHAIN_ID: u64 = 31337; // local + const CONTRACT_ADDRESS: &str = "0x52185B6a6017E6f079B994452F234f7C2533787B"; // optimism +#[cfg(feature = "simulation-mode")] +const CONTRACT_ADDRESS: &str = "0x2279B7A0a67DB372996a5FaB50D91eAA73d2eBe6"; // local + const CONTRACT_FIRST_BLOCK: u64 = 118_590_088; +#[cfg(feature = "simulation-mode")] +const CONTRACT_FIRST_BLOCK: u64 = 1; const EVENTS: [&str; 3] = [ "AppRegistered(uint256,string,bytes,string,bytes32)", @@ -71,7 +79,6 @@ pub enum Resp { } fn fetch_logs(eth_provider: ð::Provider, filter: ð::Filter) -> Vec { - #[cfg(not(feature = "simulation-mode"))] loop { match eth_provider.get_logs(filter) { Ok(res) => return res, @@ -82,13 +89,10 @@ fn fetch_logs(eth_provider: ð::Provider, filter: ð::Filter) -> Vec break, @@ -99,7 +103,6 @@ fn subscribe_to_logs(eth_provider: ð::Provider, filter: eth::Filter) { } } } - #[cfg(not(feature = "simulation-mode"))] println!("subscribed to logs successfully"); } @@ -156,10 +159,7 @@ fn init(our: Address) { state = State::new(CONTRACT_ADDRESS.to_string()).unwrap(); } - #[cfg(not(feature = "simulation-mode"))] println!("indexing on contract address {}", state.contract_address); - #[cfg(feature = "simulation-mode")] - println!("simulation mode: not indexing packages"); // create new provider for sepolia with request-timeout of 60s // can change, log requests can take quite a long time. From 0831932abe64314f929a7a03612c992e82d9f33d Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 16:22:30 -0400 Subject: [PATCH 14/18] fakechain: update local address --- .../packages/app_store/app_store/src/lib.rs | 5 +++- .../kns_indexer/kns_indexer/src/lib.rs | 23 +++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/kinode/packages/app_store/app_store/src/lib.rs b/kinode/packages/app_store/app_store/src/lib.rs index 63d39a75e..2198597ef 100644 --- a/kinode/packages/app_store/app_store/src/lib.rs +++ b/kinode/packages/app_store/app_store/src/lib.rs @@ -39,14 +39,17 @@ use ft_worker_lib::{ const ICON: &str = include_str!("icon"); +#[cfg(not(feature = "simulation-mode"))] const CHAIN_ID: u64 = 10; // optimism #[cfg(feature = "simulation-mode")] const CHAIN_ID: u64 = 31337; // local +#[cfg(not(feature = "simulation-mode"))] const CONTRACT_ADDRESS: &str = "0x52185B6a6017E6f079B994452F234f7C2533787B"; // optimism #[cfg(feature = "simulation-mode")] -const CONTRACT_ADDRESS: &str = "0x2279B7A0a67DB372996a5FaB50D91eAA73d2eBe6"; // local +const CONTRACT_ADDRESS: &str = "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318"; // local +#[cfg(not(feature = "simulation-mode"))] const CONTRACT_FIRST_BLOCK: u64 = 118_590_088; #[cfg(feature = "simulation-mode")] const CONTRACT_FIRST_BLOCK: u64 = 1; diff --git a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs index 14ccd9edd..17c8891f2 100644 --- a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs +++ b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs @@ -14,17 +14,20 @@ wit_bindgen::generate!({ world: "process", }); -const KNS_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; +#[cfg(not(feature = "simulation-mode"))] +const KNS_ADDRESS: &'static str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; // optimism #[cfg(feature = "simulation-mode")] -const KNS_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; +const KNS_ADDRESS: &'static str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; // local -const CHAIN_ID: u64 = 10; +#[cfg(not(feature = "simulation-mode"))] +const CHAIN_ID: u64 = 10; // optimism #[cfg(feature = "simulation-mode")] -const CHAIN_ID: u64 = 31337; +const CHAIN_ID: u64 = 31337; // local -const KNS_FIRST_BLOCK: u64 = 114_923_786; +#[cfg(not(feature = "simulation-mode"))] +const KNS_FIRST_BLOCK: u64 = 114_923_786; // optimism #[cfg(feature = "simulation-mode")] -const KNS_FIRST_BLOCK: u64 = 1; +const KNS_FIRST_BLOCK: u64 = 1; // local #[derive(Clone, Debug, Serialize, Deserialize)] struct State { @@ -123,17 +126,17 @@ fn subscribe_to_logs(eth_provider: ð::Provider, from_block: u64, filter: eth: call_init!(init); fn init(our: Address) { - println!("indexing on contract address {}", KNS_CONTRACT_ADDRESS); + println!("indexing on contract address {}", KNS_ADDRESS); // if we have state, load it in let state: State = match get_typed_state(|bytes| Ok(bincode::deserialize::(bytes)?)) { Some(s) => { // if chain id or contract address changed from a previous run, reset state - if s.chain_id != CHAIN_ID || s.contract_address != KNS_CONTRACT_ADDRESS { + if s.chain_id != CHAIN_ID || s.contract_address != KNS_ADDRESS { println!("resetting state because runtime contract address or chain ID changed"); State { chain_id: CHAIN_ID, - contract_address: KNS_CONTRACT_ADDRESS, + contract_address: KNS_ADDRESS.to_string(), names: HashMap::new(), nodes: HashMap::new(), block: KNS_FIRST_BLOCK, @@ -145,7 +148,7 @@ fn init(our: Address) { } None => State { chain_id: CHAIN_ID, - contract_address: KNS_CONTRACT_ADDRESS, + contract_address: KNS_ADDRESS.to_string(), names: HashMap::new(), nodes: HashMap::new(), block: KNS_FIRST_BLOCK, From c5cd40bf135bd0a148057babf027fd32c773ae42 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 18:21:48 -0400 Subject: [PATCH 15/18] refactor feature flags --- kinode/Cargo.toml | 2 +- .../kns_indexer/kns_indexer/src/lib.rs | 6 +- kinode/src/fakenet/helpers.rs | 3 + kinode/src/fakenet/mod.rs | 86 +++++++++++++------ kinode/src/keygen.rs | 1 + kinode/src/main.rs | 12 ++- kinode/src/net/ws.rs | 11 +-- kinode/src/register.rs | 14 +-- 8 files changed, 82 insertions(+), 53 deletions(-) diff --git a/kinode/Cargo.toml b/kinode/Cargo.toml index 9173b720c..f71c34122 100644 --- a/kinode/Cargo.toml +++ b/kinode/Cargo.toml @@ -79,6 +79,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" serde_urlencoded = "0.7" sha2 = "0.10" +sha3 = "0.10.8" snow = { version = "0.9.5", features = ["ring-resolver"] } static_dir = "0.2.0" thiserror = "1.0" @@ -91,4 +92,3 @@ wasi-common = "19.0.1" wasmtime = "19.0.1" wasmtime-wasi = "19.0.1" zip = "1.1.1" -sha3 = "0.10.8" diff --git a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs index 17c8891f2..588766fb6 100644 --- a/kinode/packages/kns_indexer/kns_indexer/src/lib.rs +++ b/kinode/packages/kns_indexer/kns_indexer/src/lib.rs @@ -209,8 +209,10 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> { break; } Err(e) => { - println!("got some kind of error: {:?}", e); - println!("failed to fetch logs! trying again in 5s..."); + println!( + "got eth error while fetching logs: {:?}, trying again in 5s...", + e + ); std::thread::sleep(std::time::Duration::from_secs(5)); continue; } diff --git a/kinode/src/fakenet/helpers.rs b/kinode/src/fakenet/helpers.rs index 3df842067..b90219f2e 100644 --- a/kinode/src/fakenet/helpers.rs +++ b/kinode/src/fakenet/helpers.rs @@ -21,6 +21,9 @@ sol! { uint16 _udp ); + function ip(bytes32) external view returns (uint128, uint16, uint16, uint16, uint16); + + function ownerOf(uint256 node) returns (address); function multicall(bytes[] calldata data); diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs index 0b9b92dc6..e60c2048b 100644 --- a/kinode/src/fakenet/mod.rs +++ b/kinode/src/fakenet/mod.rs @@ -1,43 +1,22 @@ use alloy_consensus::TxLegacy; use alloy_network::{Transaction, TxKind}; -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, Bytes, FixedBytes, B256, U256}; use alloy_providers::provider::{Provider, TempProvider}; use alloy_rpc_client::ClientBuilder; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use alloy_signer::{LocalWallet, Signer, SignerSync}; -use alloy_sol_types::SolCall; +use alloy_sol_types::{SolCall, SolValue}; use alloy_transport_ws::WsConnect; use lib::core::Identity; use std::str::FromStr; -use std::sync::Arc; pub mod helpers; -use crate::register::assign_ws_routing; +use crate::{keygen, KNS_ADDRESS}; pub use helpers::RegisterHelpers::*; pub use helpers::*; const FAKE_DOTDEV: &str = "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"; -const FAKE_KNS: &str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; - -pub async fn assign_ws_local_helper( - our: &mut Identity, - ws_port: u16, - fakechain_port: u16, -) -> Result<(), anyhow::Error> { - let kns = Address::from_str(FAKE_KNS)?; - let endpoint = format!("ws://localhost:{}", fakechain_port); - - let ws = WsConnect { - url: endpoint, - auth: None, - }; - - let client = ClientBuilder::default().ws(ws).await?; - let provider = Provider::new_with_client(client); - - assign_ws_routing(our, kns, Arc::new(provider), Some(ws_port)).await -} pub async fn register_local( name: &str, @@ -50,7 +29,7 @@ pub async fn register_local( )?; let dotdev = Address::from_str(FAKE_DOTDEV)?; - let kns = Address::from_str(FAKE_KNS)?; + let kns = Address::from_str(KNS_ADDRESS)?; let endpoint = format!("ws://localhost:{}", fakechain_port); let ws = WsConnect { @@ -154,3 +133,60 @@ pub async fn register_local( Ok(()) } + +pub async fn assign_ws_local_helper( + our: &mut Identity, + ws_port: u16, + fakechain_port: u16, +) -> Result<(), anyhow::Error> { + let kns = Address::from_str(KNS_ADDRESS)?; + let endpoint = format!("ws://localhost:{}", fakechain_port); + + let ws = WsConnect { + url: endpoint, + auth: None, + }; + + let client = ClientBuilder::default().ws(ws).await?; + let provider = Provider::new_with_client(client); + + let namehash = FixedBytes::<32>::from_slice(&keygen::namehash(&our.name)); + let ip_call = ipCall { _0: namehash }.abi_encode(); + let tx_input = TransactionInput::new(Bytes::from(ip_call)); + let tx = TransactionRequest { + to: Some(kns), + input: tx_input, + ..Default::default() + }; + + let Ok(ip_data) = provider.call(tx, None).await else { + return Err(anyhow::anyhow!("Failed to fetch node IP data from PKI")); + }; + + let Ok((ip, ws, _wt, _tcp, _udp)) = <(u128, u16, u16, u16, u16)>::abi_decode(&ip_data, false) + else { + return Err(anyhow::anyhow!("Failed to decode node IP data from PKI")); + }; + + let node_ip = format!( + "{}.{}.{}.{}", + (ip >> 24) & 0xFF, + (ip >> 16) & 0xFF, + (ip >> 8) & 0xFF, + ip & 0xFF + ); + + if node_ip != *"0.0.0.0" || ws != 0 { + // direct node + if ws_port != ws { + return Err(anyhow::anyhow!( + "Binary used --ws-port flag to set port to {}, but node is using port {} onchain.", + ws_port, + ws + )); + } + + our.ws_routing = Some((node_ip, ws)); + } + Ok(()) +} diff --git a/kinode/src/keygen.rs b/kinode/src/keygen.rs index 9e422e92a..3e7d40e0d 100644 --- a/kinode/src/keygen.rs +++ b/kinode/src/keygen.rs @@ -129,6 +129,7 @@ pub fn generate_jwt(jwt_secret_bytes: &[u8], username: &str) -> Option { } } +#[cfg(not(feature = "simulation-mode"))] pub fn get_username_and_routers(keyfile: &[u8]) -> Result<(String, Vec), &'static str> { let (username, routers, _salt, _key_enc, _jwt_enc) = bincode::deserialize::<(String, Vec, Vec, Vec, Vec)>(keyfile) diff --git a/kinode/src/main.rs b/kinode/src/main.rs index 1338f06bf..5355fb0bd 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -17,6 +17,7 @@ mod kernel; mod keygen; mod kv; mod net; +#[cfg(not(feature = "simulation-mode"))] mod register; mod sqlite; mod state; @@ -39,9 +40,13 @@ const VERSION: &str = env!("CARGO_PKG_VERSION"); /// default routers as a eth-provider fallback const DEFAULT_ETH_PROVIDERS: &str = include_str!("eth/default_providers_mainnet.json"); #[cfg(not(feature = "simulation-mode"))] -const CHAIN_ID: u64 = 10; +pub const CHAIN_ID: u64 = 10; +#[cfg(feature = "simulation-mode")] +pub const CHAIN_ID: u64 = 31337; +#[cfg(not(feature = "simulation-mode"))] +pub const KNS_ADDRESS: &str = "0xca5b5811c0c40aab3295f932b1b5112eb7bb4bd6"; #[cfg(feature = "simulation-mode")] -const CHAIN_ID: u64 = 31337; +pub const KNS_ADDRESS: &str = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; #[tokio::main] async fn main() { @@ -80,7 +85,7 @@ async fn main() { } Err(_) => serde_json::from_str(DEFAULT_ETH_PROVIDERS).unwrap(), }; - if let Some(rpc) = matches.get_one::("rpc") { + if let Some(rpc) = rpc { eth_provider_config.push(lib::eth::ProviderConfig { chain_id: CHAIN_ID, trusted: true, @@ -274,7 +279,6 @@ async fn main() { print_sender.clone(), net_message_sender, net_message_receiver, - register::KNS_OPTIMISM_ADDRESS.to_string(), *matches.get_one::("reveal-ip").unwrap_or(&true), )); tasks.spawn(state::state_sender( diff --git a/kinode/src/net/ws.rs b/kinode/src/net/ws.rs index 1be934dd5..9b8ab9b46 100644 --- a/kinode/src/net/ws.rs +++ b/kinode/src/net/ws.rs @@ -15,6 +15,7 @@ use { use crate::net::types::*; use crate::net::utils::*; +use crate::KNS_ADDRESS; use lib::types::core::*; /// only used in connection initialization, otherwise, nacks and Responses are only used for "timeouts" @@ -34,7 +35,6 @@ pub async fn networking( print_tx: PrintSender, self_message_tx: MessageSender, message_rx: MessageReceiver, - contract_address: String, reveal_ip: bool, ) -> Result<()> { // branch on whether we are a direct or indirect node @@ -57,7 +57,6 @@ pub async fn networking( self_message_tx, message_rx, reveal_ip, - contract_address, ) .await } @@ -95,7 +94,6 @@ pub async fn networking( print_tx, self_message_tx, message_rx, - contract_address, ) .await } @@ -112,7 +110,6 @@ async fn indirect_networking( _self_message_tx: MessageSender, mut message_rx: MessageReceiver, reveal_ip: bool, - contract_address: String, ) -> Result<()> { print_debug(&print_tx, "net: starting as indirect").await; let pki: OnchainPKI = Arc::new(DashMap::new()); @@ -148,7 +145,6 @@ async fn indirect_networking( names.clone(), &kernel_message_tx, &print_tx, - &contract_address, ) .await { Ok(()) => continue, @@ -283,7 +279,6 @@ async fn direct_networking( print_tx: PrintSender, _self_message_tx: MessageSender, mut message_rx: MessageReceiver, - contract_address: String, ) -> Result<()> { print_debug(&print_tx, "net: starting as direct").await; let pki: OnchainPKI = Arc::new(DashMap::new()); @@ -318,7 +313,6 @@ async fn direct_networking( names.clone(), &kernel_message_tx, &print_tx, - &contract_address, ) .await { Ok(()) => continue, @@ -855,7 +849,6 @@ async fn handle_local_message( names: PKINames, kernel_message_tx: &MessageSender, print_tx: &PrintSender, - contract_address: &str, ) -> Result<()> { print_debug(print_tx, "net: handling local message").await; let body = match km.message { @@ -1019,7 +1012,7 @@ async fn handle_local_message( let mut printout = String::new(); printout.push_str(&format!( "indexing from contract address {}\r\n", - contract_address + KNS_ADDRESS )); printout.push_str(&format!("our Identity: {:#?}\r\n", our)); printout.push_str("we have connections with peers:\r\n"); diff --git a/kinode/src/register.rs b/kinode/src/register.rs index f0a985745..e0668c137 100644 --- a/kinode/src/register.rs +++ b/kinode/src/register.rs @@ -1,4 +1,5 @@ use crate::keygen; +use crate::KNS_ADDRESS; use alloy_primitives::{Address as EthAddress, Bytes, FixedBytes, U256}; use alloy_providers::provider::{Provider, TempProvider}; use alloy_pubsub::PubSubFrontend; @@ -28,16 +29,6 @@ use warp::{ type RegistrationSender = mpsc::Sender<(Identity, Keyfile, Vec)>; -// pub const KNS_SEPOLIA_ADDRESS: EthAddress = EthAddress::new([ -// 0x38, 0x07, 0xFB, 0xD6, 0x92, 0xAa, 0x5c, 0x96, 0xF1, 0xD8, 0xD7, 0xc5, 0x9a, 0x13, 0x46, 0xa8, -// 0x85, 0xF4, 0x0B, 0x1C, -// ]); - -pub const KNS_OPTIMISM_ADDRESS: EthAddress = EthAddress::new([ - 0xca, 0x5b, 0x58, 0x11, 0xc0, 0xC4, 0x0a, 0xAB, 0x32, 0x95, 0xf9, 0x32, 0xb1, 0xB5, 0x11, 0x2E, - 0xb7, 0xbb, 0x4b, 0xD6, -]); - sol! { function auth( bytes32 _node, @@ -126,7 +117,7 @@ pub async fn register( }); // KnsRegistrar contract address - let kns_address = KNS_OPTIMISM_ADDRESS; + let kns_address = EthAddress::from_str(KNS_ADDRESS).unwrap(); // This ETH provider uses public rpc endpoints to verify registration signatures. let url = if let Some(rpc_url) = maybe_rpc { @@ -737,7 +728,6 @@ pub async fn assign_ws_routing( } Ok(()) } - async fn success_response( sender: Arc, our: Identity, From fe058a2b4b43313a94b7af8b193db3a54417d026 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 18:56:48 -0400 Subject: [PATCH 16/18] local register docs --- kinode/src/fakenet/helpers.rs | 1 - kinode/src/fakenet/mod.rs | 5 +++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/kinode/src/fakenet/helpers.rs b/kinode/src/fakenet/helpers.rs index b90219f2e..cf543b85e 100644 --- a/kinode/src/fakenet/helpers.rs +++ b/kinode/src/fakenet/helpers.rs @@ -23,7 +23,6 @@ sol! { function ip(bytes32) external view returns (uint128, uint16, uint16, uint16, uint16); - function ownerOf(uint256 node) returns (address); function multicall(bytes[] calldata data); diff --git a/kinode/src/fakenet/mod.rs b/kinode/src/fakenet/mod.rs index e60c2048b..4ee5ef60a 100644 --- a/kinode/src/fakenet/mod.rs +++ b/kinode/src/fakenet/mod.rs @@ -18,6 +18,9 @@ pub use helpers::*; const FAKE_DOTDEV: &str = "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"; +/// Attempts to connect to a local anvil fakechain, +/// registering a name with its KNS contract. +/// If name is already registered, resets it. pub async fn register_local( name: &str, ws_port: u16, @@ -134,6 +137,8 @@ pub async fn register_local( Ok(()) } +/// Booting from a keyfile, fetches the node's IP data from the KNS contract +/// and assigns it to the Identity struct. pub async fn assign_ws_local_helper( our: &mut Identity, ws_port: u16, From 430d58695a0465829d5bbae726573994b0a6ef17 Mon Sep 17 00:00:00 2001 From: bitful-pannul Date: Tue, 7 May 2024 18:57:03 -0400 Subject: [PATCH 17/18] fix: widget simulation mode --- kinode/packages/kino_updates/widget/Cargo.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/kinode/packages/kino_updates/widget/Cargo.toml b/kinode/packages/kino_updates/widget/Cargo.toml index 33cdec77d..617d188e9 100644 --- a/kinode/packages/kino_updates/widget/Cargo.toml +++ b/kinode/packages/kino_updates/widget/Cargo.toml @@ -3,6 +3,9 @@ name = "widget" version = "0.1.0" edition = "2021" +[features] +simulation-mode = [] + [dependencies] anyhow = "1.0" bincode = "1.3.3" From 22e676b9a3be4781027153043e06289cfb5b655f Mon Sep 17 00:00:00 2001 From: dr-frmr Date: Tue, 7 May 2024 17:21:58 -0600 Subject: [PATCH 18/18] fix: wrap fakechain-port flag usage in feature always --- kinode/src/main.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/kinode/src/main.rs b/kinode/src/main.rs index c15d206dc..68292d3af 100644 --- a/kinode/src/main.rs +++ b/kinode/src/main.rs @@ -99,15 +99,22 @@ async fn main() { .await .expect("failed to save new eth provider config!"); } - let local_chain_port = matches - .get_one::("fakechain-port") - .cloned() - .unwrap_or(8545); - eth_provider_config.push(lib::eth::ProviderConfig { - chain_id: 31337, - trusted: true, - provider: lib::eth::NodeOrRpcUrl::RpcUrl(format!("ws://localhost:{}", local_chain_port)), - }); + + #[cfg(feature = "simulation-mode")] + { + let local_chain_port = matches + .get_one::("fakechain-port") + .cloned() + .unwrap_or(8545); + eth_provider_config.push(lib::eth::ProviderConfig { + chain_id: 31337, + trusted: true, + provider: lib::eth::NodeOrRpcUrl::RpcUrl(format!( + "ws://localhost:{}", + local_chain_port + )), + }); + } // kernel receives system messages via this channel, all other modules send messages let (kernel_message_sender, kernel_message_receiver): (MessageSender, MessageReceiver) =