diff --git a/.gitignore b/.gitignore index 2403c3ed58..abe32bf911 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ uv.lock /vendor/ + # Node.js node_modules/ diff --git a/ant-networking/Cargo.toml b/ant-networking/Cargo.toml index da438d95aa..a2619fd510 100644 --- a/ant-networking/Cargo.toml +++ b/ant-networking/Cargo.toml @@ -11,7 +11,6 @@ version = "0.3.1" [features] default = [] -encrypt-records = [] local = ["libp2p/mdns"] loud = [] open-metrics = ["libp2p/metrics", "prometheus-client", "hyper", "sysinfo"] diff --git a/ant-networking/src/cmd.rs b/ant-networking/src/cmd.rs index 8d4352e976..345668c36e 100644 --- a/ant-networking/src/cmd.rs +++ b/ant-networking/src/cmd.rs @@ -664,14 +664,14 @@ impl SwarmDriver { RecordKind::Chunk => RecordType::Chunk, RecordKind::Scratchpad => RecordType::Scratchpad, RecordKind::Pointer => RecordType::Pointer, - RecordKind::LinkedList | RecordKind::Register => { + RecordKind::GraphEntry | RecordKind::Register => { let content_hash = XorName::from_content(&record.value); RecordType::NonChunk(content_hash) } RecordKind::ChunkWithPayment | RecordKind::RegisterWithPayment | RecordKind::PointerWithPayment - | RecordKind::LinkedListWithPayment + | RecordKind::GraphEntryWithPayment | RecordKind::ScratchpadWithPayment => { error!("Record {record_key:?} with payment shall not be stored locally."); return Err(NetworkError::InCorrectRecordHeader); diff --git a/ant-networking/src/error.rs b/ant-networking/src/error.rs index 8af5915c8b..ee066a850c 100644 --- a/ant-networking/src/error.rs +++ b/ant-networking/src/error.rs @@ -6,7 +6,7 @@ // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. -use ant_protocol::storage::LinkedListAddress; +use ant_protocol::storage::GraphEntryAddress; use ant_protocol::{messages::Response, storage::RecordKind, NetworkAddress, PrettyPrintRecordKey}; use libp2p::{ kad::{self, QueryId, Record}, @@ -123,14 +123,13 @@ pub enum NetworkError { #[error("Record header is incorrect")] InCorrectRecordHeader, - // ---------- Chunk Errors #[error("Failed to verify the ChunkProof with the provided quorum")] FailedToVerifyChunkProof(NetworkAddress), - // ---------- LinkedList Errors - #[error("Linked list not found: {0:?}")] - NoLinkedListFoundInsideRecord(LinkedListAddress), + // ---------- Graph Errors + #[error("Graph entry not found: {0:?}")] + NoGraphEntryFoundInsideRecord(GraphEntryAddress), // ---------- Store Error #[error("No Store Cost Responses")] diff --git a/ant-networking/src/event/kad.rs b/ant-networking/src/event/kad.rs index d0c1f6e91f..5c83bf103c 100644 --- a/ant-networking/src/event/kad.rs +++ b/ant-networking/src/event/kad.rs @@ -7,12 +7,12 @@ // permissions and limitations relating to use of the SAFE Network Software. use crate::{ - driver::PendingGetClosestType, get_linked_list_from_record, get_quorum_value, + driver::PendingGetClosestType, get_graph_entry_from_record, get_quorum_value, target_arch::Instant, GetRecordCfg, GetRecordError, NetworkError, Result, SwarmDriver, CLOSE_GROUP_SIZE, }; use ant_protocol::{ - storage::{try_serialize_record, LinkedList, RecordKind}, + storage::{try_serialize_record, GraphEntry, RecordKind}, NetworkAddress, PrettyPrintRecordKey, }; use itertools::Itertools; @@ -399,7 +399,7 @@ impl SwarmDriver { debug!("For record {pretty_key:?} task {query_id:?}, fetch completed with split record"); let mut accumulated_transactions = BTreeSet::new(); for (record, _) in result_map.values() { - match get_linked_list_from_record(record) { + match get_graph_entry_from_record(record) { Ok(transactions) => { accumulated_transactions.extend(transactions); } @@ -412,11 +412,11 @@ impl SwarmDriver { info!("For record {pretty_key:?} task {query_id:?}, found split record for a transaction, accumulated and sending them as a single record"); let accumulated_transactions = accumulated_transactions .into_iter() - .collect::>(); + .collect::>(); let bytes = try_serialize_record( &accumulated_transactions, - RecordKind::LinkedList, + RecordKind::GraphEntry, )?; let new_accumulated_record = Record { diff --git a/ant-networking/src/linked_list.rs b/ant-networking/src/graph.rs similarity index 67% rename from ant-networking/src/linked_list.rs rename to ant-networking/src/graph.rs index 2834cf9ddc..d58e77599c 100644 --- a/ant-networking/src/linked_list.rs +++ b/ant-networking/src/graph.rs @@ -7,7 +7,7 @@ // permissions and limitations relating to use of the SAFE Network Software. use crate::{driver::GetRecordCfg, Network, NetworkError, Result}; -use ant_protocol::storage::{LinkedList, LinkedListAddress}; +use ant_protocol::storage::{GraphEntry, GraphEntryAddress}; use ant_protocol::{ storage::{try_deserialize_record, RecordHeader, RecordKind, RetryStrategy}, NetworkAddress, PrettyPrintRecordKey, @@ -15,9 +15,9 @@ use ant_protocol::{ use libp2p::kad::{Quorum, Record}; impl Network { - /// Gets LinkedList at LinkedListAddress from the Network. - pub async fn get_linked_list(&self, address: LinkedListAddress) -> Result> { - let key = NetworkAddress::from_linked_list_address(address).to_record_key(); + /// Gets GraphEntry at GraphEntryAddress from the Network. + pub async fn get_graph_entry(&self, address: GraphEntryAddress) -> Result> { + let key = NetworkAddress::from_graph_entry_address(address).to_record_key(); let get_cfg = GetRecordCfg { get_quorum: Quorum::All, retry_strategy: Some(RetryStrategy::Quick), @@ -31,20 +31,20 @@ impl Network { PrettyPrintRecordKey::from(&record.key) ); - get_linked_list_from_record(&record) + get_graph_entry_from_record(&record) } } -pub fn get_linked_list_from_record(record: &Record) -> Result> { +pub fn get_graph_entry_from_record(record: &Record) -> Result> { let header = RecordHeader::from_record(record)?; - if let RecordKind::LinkedList = header.kind { - let transactions = try_deserialize_record::>(record)?; + if let RecordKind::GraphEntry = header.kind { + let transactions = try_deserialize_record::>(record)?; Ok(transactions) } else { warn!( - "RecordKind mismatch while trying to retrieve linked_list from record {:?}", + "RecordKind mismatch while trying to retrieve graph_entry from record {:?}", PrettyPrintRecordKey::from(&record.key) ); - Err(NetworkError::RecordKindMismatch(RecordKind::LinkedList)) + Err(NetworkError::RecordKindMismatch(RecordKind::GraphEntry)) } } diff --git a/ant-networking/src/lib.rs b/ant-networking/src/lib.rs index 4d165ef4d8..6bfe3031c3 100644 --- a/ant-networking/src/lib.rs +++ b/ant-networking/src/lib.rs @@ -17,7 +17,7 @@ mod error; mod event; mod external_address; mod fifo_register; -mod linked_list; +mod graph; mod log_markers; #[cfg(feature = "open-metrics")] mod metrics; @@ -40,7 +40,7 @@ pub use self::{ }, error::{GetRecordError, NetworkError}, event::{MsgResponder, NetworkEvent}, - linked_list::get_linked_list_from_record, + graph::get_graph_entry_from_record, record_store::NodeRecordStore, }; #[cfg(feature = "open-metrics")] @@ -75,7 +75,7 @@ use tokio::sync::{ }; use tokio::time::Duration; use { - ant_protocol::storage::LinkedList, + ant_protocol::storage::GraphEntry, ant_protocol::storage::{ try_deserialize_record, try_serialize_record, RecordHeader, RecordKind, }, @@ -634,17 +634,17 @@ impl Network { match kind { RecordKind::Chunk | RecordKind::ChunkWithPayment - | RecordKind::LinkedListWithPayment + | RecordKind::GraphEntryWithPayment | RecordKind::RegisterWithPayment | RecordKind::PointerWithPayment | RecordKind::ScratchpadWithPayment => { error!("Encountered a split record for {pretty_key:?} with unexpected RecordKind {kind:?}, skipping."); continue; } - RecordKind::LinkedList => { + RecordKind::GraphEntry => { info!("For record {pretty_key:?}, we have a split record for a transaction attempt. Accumulating transactions"); - match get_linked_list_from_record(record) { + match get_graph_entry_from_record(record) { Ok(transactions) => { accumulated_transactions.extend(transactions); } @@ -730,10 +730,10 @@ impl Network { info!("For record {pretty_key:?} task found split record for a transaction, accumulated and sending them as a single record"); let accumulated_transactions = accumulated_transactions .into_iter() - .collect::>(); + .collect::>(); let record = Record { key: key.clone(), - value: try_serialize_record(&accumulated_transactions, RecordKind::LinkedList) + value: try_serialize_record(&accumulated_transactions, RecordKind::GraphEntry) .map_err(|err| { error!( "Error while serializing the accumulated transactions for {pretty_key:?}: {err:?}" diff --git a/ant-networking/src/record_store.rs b/ant-networking/src/record_store.rs index b4ab4ff6b3..33ae76191a 100644 --- a/ant-networking/src/record_store.rs +++ b/ant-networking/src/record_store.rs @@ -434,24 +434,17 @@ impl NodeRecordStore { key: &Key, encryption_details: &(Aes256GcmSiv, [u8; 4]), ) -> Option> { - let mut record = Record { - key: key.clone(), - value: bytes, - publisher: None, - expires: None, - }; - - // if we're not encrypting, lets just return the record - if !cfg!(feature = "encrypt-records") { - return Some(Cow::Owned(record)); - } - let (cipher, nonce_starter) = encryption_details; let nonce = generate_nonce_for_record(nonce_starter, key); - match cipher.decrypt(&nonce, record.value.as_ref()) { + match cipher.decrypt(&nonce, bytes.as_slice()) { Ok(value) => { - record.value = value; + let record = Record { + key: key.clone(), + value, + publisher: None, + expires: None, + }; Some(Cow::Owned(record)) } Err(error) => { @@ -630,15 +623,11 @@ impl NodeRecordStore { } /// Prepare record bytes for storage - /// If feats are enabled, this will eg, encrypt the record for storage + /// This will encrypt the record for storage fn prepare_record_bytes( record: Record, encryption_details: (Aes256GcmSiv, [u8; 4]), ) -> Option> { - if !cfg!(feature = "encrypt-records") { - return Some(record.value); - } - let (cipher, nonce_starter) = encryption_details; let nonce = generate_nonce_for_record(&nonce_starter, &record.key); @@ -1144,8 +1133,10 @@ mod tests { ..Default::default() }; let self_id = PeerId::random(); - let (network_event_sender, _) = mpsc::channel(1); - let (swarm_cmd_sender, _) = mpsc::channel(1); + + // Create channels with proper receivers + let (network_event_sender, _network_event_receiver) = mpsc::channel(1); + let (swarm_cmd_sender, mut swarm_cmd_receiver) = mpsc::channel(1); let mut store = NodeRecordStore::with_config( self_id, @@ -1172,31 +1163,46 @@ mod tests { .put_verified(record.clone(), RecordType::Chunk) .is_ok()); - // Mark as stored (simulating the CompletedWrite event) - store.mark_as_stored(record.key.clone(), RecordType::Chunk); + // Wait for the async write operation to complete + if let Some(cmd) = swarm_cmd_receiver.recv().await { + match cmd { + LocalSwarmCmd::AddLocalRecordAsStored { key, record_type } => { + store.mark_as_stored(key, record_type); + } + _ => panic!("Unexpected command received"), + } + } // Verify the chunk is stored let stored_record = store.get(&record.key); - assert!(stored_record.is_some(), "Chunk should be stored"); + assert!(stored_record.is_some(), "Chunk should be stored initially"); // Sleep a while to let OS completes the flush to disk - sleep(Duration::from_secs(5)).await; + sleep(Duration::from_secs(1)).await; - // Restart the store with same encrypt_seed + // Create new channels for the restarted store + let (new_network_event_sender, _new_network_event_receiver) = mpsc::channel(1); + let (new_swarm_cmd_sender, _new_swarm_cmd_receiver) = mpsc::channel(1); + + // Restart the store with same encrypt_seed but new channels drop(store); let store = NodeRecordStore::with_config( self_id, store_config, - network_event_sender.clone(), - swarm_cmd_sender.clone(), + new_network_event_sender, + new_swarm_cmd_sender, ); - // Sleep a lit bit to let OS completes restoring - sleep(Duration::from_secs(1)).await; - // Verify the record still exists let stored_record = store.get(&record.key); - assert!(stored_record.is_some(), "Chunk should be stored"); + assert!( + stored_record.is_some(), + "Chunk should be stored after restart with same key" + ); + + // Create new channels for the different seed test + let (diff_network_event_sender, _diff_network_event_receiver) = mpsc::channel(1); + let (diff_swarm_cmd_sender, _diff_swarm_cmd_receiver) = mpsc::channel(1); // Restart the store with different encrypt_seed let self_id_diff = PeerId::random(); @@ -1208,25 +1214,16 @@ mod tests { let store_diff = NodeRecordStore::with_config( self_id_diff, store_config_diff, - network_event_sender, - swarm_cmd_sender, + diff_network_event_sender, + diff_swarm_cmd_sender, ); - // Sleep a lit bit to let OS completes restoring (if has) - sleep(Duration::from_secs(1)).await; - - // Verify the record existence, shall get removed when encryption enabled - if cfg!(feature = "encrypt-records") { - assert!( - store_diff.get(&record.key).is_none(), - "Chunk should be gone" - ); - } else { - assert!( - store_diff.get(&record.key).is_some(), - "Chunk shall persists without encryption" - ); - } + // When encryption is enabled, the record should be gone because it can't be decrypted + // with the different encryption seed + assert!( + store_diff.get(&record.key).is_none(), + "Chunk should be gone with different encryption key" + ); Ok(()) } @@ -1557,7 +1554,7 @@ mod tests { // via NetworkEvent::CompletedWrite) store.mark_as_stored(record_key.clone(), RecordType::Chunk); - stored_records.push(record_key); + stored_records.push(record_key.clone()); stored_records.sort_by(|a, b| { let a = NetworkAddress::from_record_key(a); let b = NetworkAddress::from_record_key(b); diff --git a/ant-node/Cargo.toml b/ant-node/Cargo.toml index cc724a9359..9d689d0041 100644 --- a/ant-node/Cargo.toml +++ b/ant-node/Cargo.toml @@ -14,10 +14,14 @@ name = "antnode" path = "src/bin/antnode/main.rs" [features] -default = ["metrics", "upnp", "open-metrics", "encrypt-records"] -encrypt-records = ["ant-networking/encrypt-records"] +default = ["metrics", "upnp", "open-metrics"] extension-module = ["pyo3/extension-module"] -local = ["ant-networking/local", "ant-evm/local", "ant-bootstrap/local", "ant-logging/process-metrics"] +local = [ + "ant-networking/local", + "ant-evm/local", + "ant-bootstrap/local", + "ant-logging/process-metrics", +] loud = ["ant-networking/loud"] # loud mode: print important messages to console metrics = [] nightly = [] @@ -83,7 +87,9 @@ walkdir = "~2.5.0" xor_name = "5.0.0" [dev-dependencies] -ant-protocol = { path = "../ant-protocol", version = "0.3.1", features = ["rpc"] } +ant-protocol = { path = "../ant-protocol", version = "0.3.1", features = [ + "rpc", +] } assert_fs = "1.0.0" evmlib = { path = "../evmlib", version = "0.1.6" } autonomi = { path = "../autonomi", version = "0.3.1", features = ["registers"] } diff --git a/ant-node/src/put_validation.rs b/ant-node/src/put_validation.rs index 1a5311c303..23d458211d 100644 --- a/ant-node/src/put_validation.rs +++ b/ant-node/src/put_validation.rs @@ -12,10 +12,10 @@ use crate::{node::Node, Error, Marker, Result}; use ant_evm::payment_vault::verify_data_payment; use ant_evm::{AttoTokens, ProofOfPayment}; use ant_networking::NetworkError; -use ant_protocol::storage::LinkedList; +use ant_protocol::storage::GraphEntry; use ant_protocol::{ storage::{ - try_deserialize_record, try_serialize_record, Chunk, LinkedListAddress, Pointer, + try_deserialize_record, try_serialize_record, Chunk, GraphEntryAddress, Pointer, RecordHeader, RecordKind, RecordType, Scratchpad, }, NetworkAddress, PrettyPrintRecordKey, @@ -163,19 +163,19 @@ impl Node { self.validate_and_store_scratchpad_record(scratchpad, key, false) .await } - RecordKind::LinkedList => { + RecordKind::GraphEntry => { // Transactions should always be paid for error!("Transaction should not be validated at this point"); Err(Error::InvalidPutWithoutPayment( PrettyPrintRecordKey::from(&record.key).into_owned(), )) } - RecordKind::LinkedListWithPayment => { + RecordKind::GraphEntryWithPayment => { let (payment, transaction) = - try_deserialize_record::<(ProofOfPayment, LinkedList)>(&record)?; + try_deserialize_record::<(ProofOfPayment, GraphEntry)>(&record)?; // check if the deserialized value's TransactionAddress matches the record's key - let net_addr = NetworkAddress::from_linked_list_address(transaction.address()); + let net_addr = NetworkAddress::from_graph_entry_address(transaction.address()); let key = net_addr.to_record_key(); let pretty_key = PrettyPrintRecordKey::from(&key); if record.key != key { @@ -349,7 +349,7 @@ impl Node { } } - let res = self.validate_and_store_pointer_record(pointer, key).await; + let res = self.validate_and_store_pointer_record(pointer, key); if res.is_ok() { let content_hash = XorName::from_content(&record.value); Marker::ValidPointerPutFromClient(&PrettyPrintRecordKey::from(&record.key)) @@ -377,7 +377,7 @@ impl Node { match record_header.kind { // A separate flow handles payment for chunks and registers RecordKind::ChunkWithPayment - | RecordKind::LinkedListWithPayment + | RecordKind::GraphEntryWithPayment | RecordKind::RegisterWithPayment | RecordKind::ScratchpadWithPayment | RecordKind::PointerWithPayment => { @@ -409,9 +409,9 @@ impl Node { self.validate_and_store_scratchpad_record(scratchpad, key, false) .await } - RecordKind::LinkedList => { + RecordKind::GraphEntry => { let record_key = record.key.clone(); - let transactions = try_deserialize_record::>(&record)?; + let transactions = try_deserialize_record::>(&record)?; self.validate_merge_and_store_transactions(transactions, &record_key) .await } @@ -432,7 +432,7 @@ impl Node { RecordKind::Pointer => { let pointer = try_deserialize_record::(&record)?; let key = record.key.clone(); - self.validate_and_store_pointer_record(pointer, key).await + self.validate_and_store_pointer_record(pointer, key) } } } @@ -621,19 +621,19 @@ impl Node { /// If we already have a transaction at this address, the Vec is extended and stored. pub(crate) async fn validate_merge_and_store_transactions( &self, - transactions: Vec, + transactions: Vec, record_key: &RecordKey, ) -> Result<()> { let pretty_key = PrettyPrintRecordKey::from(record_key); debug!("Validating transactions before storage at {pretty_key:?}"); // only keep transactions that match the record key - let transactions_for_key: Vec = transactions + let transactions_for_key: Vec = transactions .into_iter() .filter(|s| { // get the record key for the transaction let transaction_address = s.address(); - let network_address = NetworkAddress::from_linked_list_address(transaction_address); + let network_address = NetworkAddress::from_graph_entry_address(transaction_address); let transaction_record_key = network_address.to_record_key(); let transaction_pretty = PrettyPrintRecordKey::from(&transaction_record_key); if &transaction_record_key != record_key { @@ -653,7 +653,7 @@ impl Node { } // verify the transactions - let mut validated_transactions: BTreeSet = transactions_for_key + let mut validated_transactions: BTreeSet = transactions_for_key .into_iter() .filter(|t| t.verify()) .collect(); @@ -670,12 +670,12 @@ impl Node { // add local transactions to the validated transactions, turn to Vec let local_txs = self.get_local_transactions(addr).await?; validated_transactions.extend(local_txs.into_iter()); - let validated_transactions: Vec = validated_transactions.into_iter().collect(); + let validated_transactions: Vec = validated_transactions.into_iter().collect(); // store the record into the local storage let record = Record { key: record_key.clone(), - value: try_serialize_record(&validated_transactions, RecordKind::LinkedList)?.to_vec(), + value: try_serialize_record(&validated_transactions, RecordKind::GraphEntry)?.to_vec(), publisher: None, expires: None, }; @@ -826,9 +826,9 @@ impl Node { /// Get the local transactions for the provided `TransactionAddress` /// This only fetches the transactions from the local store and does not perform any network operations. - async fn get_local_transactions(&self, addr: LinkedListAddress) -> Result> { + async fn get_local_transactions(&self, addr: GraphEntryAddress) -> Result> { // get the local transactions - let record_key = NetworkAddress::from_linked_list_address(addr).to_record_key(); + let record_key = NetworkAddress::from_graph_entry_address(addr).to_record_key(); debug!("Checking for local transactions with key: {record_key:?}"); let local_record = match self.network().get_local_record(&record_key).await? { Some(r) => r, @@ -841,16 +841,16 @@ impl Node { // deserialize the record and get the transactions let local_header = RecordHeader::from_record(&local_record)?; let record_kind = local_header.kind; - if !matches!(record_kind, RecordKind::LinkedList) { + if !matches!(record_kind, RecordKind::GraphEntry) { error!("Found a {record_kind} when expecting to find Spend at {addr:?}"); - return Err(NetworkError::RecordKindMismatch(RecordKind::LinkedList).into()); + return Err(NetworkError::RecordKindMismatch(RecordKind::GraphEntry).into()); } - let local_transactions: Vec = try_deserialize_record(&local_record)?; + let local_transactions: Vec = try_deserialize_record(&local_record)?; Ok(local_transactions) } /// Validate and store a pointer record - pub(crate) async fn validate_and_store_pointer_record( + pub(crate) fn validate_and_store_pointer_record( &self, pointer: Pointer, key: RecordKey, diff --git a/ant-node/src/quote.rs b/ant-node/src/quote.rs index 59d9eda832..f248f00392 100644 --- a/ant-node/src/quote.rs +++ b/ant-node/src/quote.rs @@ -23,7 +23,7 @@ impl Node { ) -> Result { let content = match address { NetworkAddress::ChunkAddress(addr) => *addr.xorname(), - NetworkAddress::LinkedListAddress(addr) => *addr.xorname(), + NetworkAddress::GraphEntryAddress(addr) => *addr.xorname(), NetworkAddress::RegisterAddress(addr) => addr.xorname(), NetworkAddress::ScratchpadAddress(addr) => addr.xorname(), NetworkAddress::PointerAddress(addr) => *addr.xorname(), @@ -61,7 +61,7 @@ pub(crate) fn verify_quote_for_storecost( // check address let content = match address { NetworkAddress::ChunkAddress(addr) => *addr.xorname(), - NetworkAddress::LinkedListAddress(addr) => *addr.xorname(), + NetworkAddress::GraphEntryAddress(addr) => *addr.xorname(), NetworkAddress::RegisterAddress(addr) => addr.xorname(), NetworkAddress::ScratchpadAddress(addr) => addr.xorname(), NetworkAddress::PointerAddress(addr) => *addr.xorname(), diff --git a/ant-protocol/src/lib.rs b/ant-protocol/src/lib.rs index 08d8f621b7..bd9254da9a 100644 --- a/ant-protocol/src/lib.rs +++ b/ant-protocol/src/lib.rs @@ -32,13 +32,12 @@ pub use error::Error; pub use error::Error as NetworkError; use storage::ScratchpadAddress; -use self::storage::{ChunkAddress, LinkedListAddress, PointerAddress, RegisterAddress}; +use self::storage::{ChunkAddress, GraphEntryAddress, PointerAddress, RegisterAddress}; /// Re-export of Bytes used throughout the protocol pub use bytes::Bytes; use ant_evm::U256; -use hex; use libp2p::{ kad::{KBucketDistance as Distance, KBucketKey as Key, RecordKey}, multiaddr::Protocol, @@ -96,7 +95,7 @@ pub enum NetworkAddress { /// The NetworkAddress is representing a ChunkAddress. ChunkAddress(ChunkAddress), /// The NetworkAddress is representing a TransactionAddress. - LinkedListAddress(LinkedListAddress), + GraphEntryAddress(GraphEntryAddress), /// The NetworkAddress is representing a RegisterAddress. RegisterAddress(RegisterAddress), /// The NetworkAddress is representing a ScratchpadAddress. @@ -114,8 +113,8 @@ impl NetworkAddress { } /// Return a `NetworkAddress` representation of the `TransactionAddress`. - pub fn from_linked_list_address(transaction_address: LinkedListAddress) -> Self { - NetworkAddress::LinkedListAddress(transaction_address) + pub fn from_graph_entry_address(transaction_address: GraphEntryAddress) -> Self { + NetworkAddress::GraphEntryAddress(transaction_address) } /// Return a `NetworkAddress` representation of the `TransactionAddress`. @@ -148,8 +147,8 @@ impl NetworkAddress { match self { NetworkAddress::PeerId(bytes) | NetworkAddress::RecordKey(bytes) => bytes.to_vec(), NetworkAddress::ChunkAddress(chunk_address) => chunk_address.xorname().0.to_vec(), - NetworkAddress::LinkedListAddress(linked_list_address) => { - linked_list_address.xorname().0.to_vec() + NetworkAddress::GraphEntryAddress(graph_entry_address) => { + graph_entry_address.xorname().0.to_vec() } NetworkAddress::ScratchpadAddress(addr) => addr.xorname().0.to_vec(), NetworkAddress::RegisterAddress(register_address) => { @@ -185,8 +184,8 @@ impl NetworkAddress { NetworkAddress::RegisterAddress(register_address) => { RecordKey::new(®ister_address.xorname()) } - NetworkAddress::LinkedListAddress(linked_list_address) => { - RecordKey::new(linked_list_address.xorname()) + NetworkAddress::GraphEntryAddress(graph_entry_address) => { + RecordKey::new(graph_entry_address.xorname()) } NetworkAddress::PointerAddress(pointer_address) => { RecordKey::new(pointer_address.xorname()) @@ -228,7 +227,7 @@ impl Debug for NetworkAddress { &chunk_address.to_hex()[0..6] ) } - NetworkAddress::LinkedListAddress(transaction_address) => { + NetworkAddress::GraphEntryAddress(transaction_address) => { format!( "NetworkAddress::TransactionAddress({} - ", &transaction_address.to_hex()[0..6] @@ -253,7 +252,7 @@ impl Debug for NetworkAddress { ) } NetworkAddress::RecordKey(bytes) => { - format!("NetworkAddress::RecordKey({:?} - ", bytes) + format!("NetworkAddress::RecordKey({bytes:?} - ") } }; @@ -270,7 +269,7 @@ impl Display for NetworkAddress { NetworkAddress::ChunkAddress(addr) => { write!(f, "NetworkAddress::ChunkAddress({addr:?})") } - NetworkAddress::LinkedListAddress(addr) => { + NetworkAddress::GraphEntryAddress(addr) => { write!(f, "NetworkAddress::TransactionAddress({addr:?})") } NetworkAddress::ScratchpadAddress(addr) => { @@ -409,15 +408,15 @@ impl std::fmt::Debug for PrettyPrintRecordKey<'_> { #[cfg(test)] mod tests { - use crate::storage::LinkedListAddress; + use crate::storage::GraphEntryAddress; use crate::NetworkAddress; use bls::rand::thread_rng; #[test] fn verify_transaction_addr_is_actionable() { let xorname = xor_name::XorName::random(&mut thread_rng()); - let transaction_addr = LinkedListAddress::new(xorname); - let net_addr = NetworkAddress::from_linked_list_address(transaction_addr); + let transaction_addr = GraphEntryAddress::new(xorname); + let net_addr = NetworkAddress::from_graph_entry_address(transaction_addr); let transaction_addr_hex = &transaction_addr.to_hex()[0..6]; // we only log the first 6 chars let net_addr_fmt = format!("{net_addr}"); diff --git a/ant-protocol/src/storage/address/linked_list.rs b/ant-protocol/src/storage/address/graph.rs similarity index 91% rename from ant-protocol/src/storage/address/linked_list.rs rename to ant-protocol/src/storage/address/graph.rs index 4e290f9d37..deaf270d7d 100644 --- a/ant-protocol/src/storage/address/linked_list.rs +++ b/ant-protocol/src/storage/address/graph.rs @@ -12,9 +12,9 @@ use xor_name::XorName; /// Address of a transaction, is derived from the owner's public key #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] -pub struct LinkedListAddress(pub XorName); +pub struct GraphEntryAddress(pub XorName); -impl LinkedListAddress { +impl GraphEntryAddress { pub fn from_owner(owner: PublicKey) -> Self { Self(XorName::from_content(&owner.to_bytes())) } @@ -32,7 +32,7 @@ impl LinkedListAddress { } } -impl std::fmt::Debug for LinkedListAddress { +impl std::fmt::Debug for GraphEntryAddress { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "TransactionAddress({})", &self.to_hex()[0..6]) } diff --git a/ant-protocol/src/storage/address/mod.rs b/ant-protocol/src/storage/address/mod.rs index 92bdd045e4..f1bf8abd4a 100644 --- a/ant-protocol/src/storage/address/mod.rs +++ b/ant-protocol/src/storage/address/mod.rs @@ -1,9 +1,9 @@ pub mod chunk; -pub mod linked_list; +pub mod graph; pub mod pointer_address; pub mod scratchpad; pub use chunk::ChunkAddress; -pub use linked_list::LinkedListAddress; +pub use graph::GraphEntryAddress; pub use pointer_address::PointerAddress; pub use scratchpad::ScratchpadAddress; diff --git a/ant-protocol/src/storage/linked_list.rs b/ant-protocol/src/storage/graph.rs similarity index 78% rename from ant-protocol/src/storage/linked_list.rs rename to ant-protocol/src/storage/graph.rs index e93a64c699..c84e16d156 100644 --- a/ant-protocol/src/storage/linked_list.rs +++ b/ant-protocol/src/storage/graph.rs @@ -6,34 +6,34 @@ // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. -use super::address::LinkedListAddress; +use super::address::GraphEntryAddress; use bls::SecretKey; use serde::{Deserialize, Serialize}; // re-exports pub use bls::{PublicKey, Signature}; -/// Content of a transaction, limited to 32 bytes -pub type LinkedListContent = [u8; 32]; +/// Content of a graph, limited to 32 bytes +pub type GraphContent = [u8; 32]; -/// A generic Transaction on the Network +/// A generic GraphEntry on the Network #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash, Ord, PartialOrd)] -pub struct LinkedList { +pub struct GraphEntry { pub owner: PublicKey, pub parents: Vec, - pub content: LinkedListContent, - pub outputs: Option>, + pub content: GraphContent, + pub outputs: Option>, /// signs the above 4 fields with the owners key pub signature: Signature, } -impl LinkedList { - /// Create a new transaction, signing it with the provided secret key. +impl GraphEntry { + /// Create a new graph entry, signing it with the provided secret key. pub fn new( owner: PublicKey, parents: Vec, - content: LinkedListContent, - outputs: Option>, + content: GraphContent, + outputs: Option>, signing_key: &SecretKey, ) -> Self { let signature = signing_key.sign(Self::bytes_to_sign(&owner, &parents, &content, &outputs)); @@ -46,12 +46,12 @@ impl LinkedList { } } - /// Create a new transaction, with the signature already calculated. + /// Create a new graph entry, with the signature already calculated. pub fn new_with_signature( owner: PublicKey, parents: Vec, - content: LinkedListContent, - outputs: Option>, + content: GraphContent, + outputs: Option>, signature: Signature, ) -> Self { Self { @@ -68,7 +68,7 @@ impl LinkedList { owner: &PublicKey, parents: &[PublicKey], content: &[u8], - outputs: &Option>, + outputs: &Option>, ) -> Vec { let mut bytes = Vec::new(); bytes.extend_from_slice(&owner.to_bytes()); @@ -94,8 +94,8 @@ impl LinkedList { bytes } - pub fn address(&self) -> LinkedListAddress { - LinkedListAddress::from_owner(self.owner) + pub fn address(&self) -> GraphEntryAddress { + GraphEntryAddress::from_owner(self.owner) } /// Get the bytes that the signature is calculated from. diff --git a/ant-protocol/src/storage/header.rs b/ant-protocol/src/storage/header.rs index c62b0e8685..74a13ee6a7 100644 --- a/ant-protocol/src/storage/header.rs +++ b/ant-protocol/src/storage/header.rs @@ -23,7 +23,7 @@ pub enum RecordType { Chunk, Scratchpad, Pointer, - LinkedList, + GraphEntry, NonChunk(XorName), } @@ -36,8 +36,8 @@ pub struct RecordHeader { pub enum RecordKind { Chunk, ChunkWithPayment, - LinkedList, - LinkedListWithPayment, + GraphEntry, + GraphEntryWithPayment, Register, RegisterWithPayment, Scratchpad, @@ -54,12 +54,12 @@ impl Serialize for RecordKind { match *self { Self::ChunkWithPayment => serializer.serialize_u32(0), Self::Chunk => serializer.serialize_u32(1), - Self::LinkedList => serializer.serialize_u32(2), + Self::GraphEntry => serializer.serialize_u32(2), Self::Register => serializer.serialize_u32(3), Self::RegisterWithPayment => serializer.serialize_u32(4), Self::Scratchpad => serializer.serialize_u32(5), Self::ScratchpadWithPayment => serializer.serialize_u32(6), - Self::LinkedListWithPayment => serializer.serialize_u32(7), + Self::GraphEntryWithPayment => serializer.serialize_u32(7), Self::Pointer => serializer.serialize_u32(8), Self::PointerWithPayment => serializer.serialize_u32(9), } @@ -75,12 +75,12 @@ impl<'de> Deserialize<'de> for RecordKind { match num { 0 => Ok(Self::ChunkWithPayment), 1 => Ok(Self::Chunk), - 2 => Ok(Self::LinkedList), + 2 => Ok(Self::GraphEntry), 3 => Ok(Self::Register), 4 => Ok(Self::RegisterWithPayment), 5 => Ok(Self::Scratchpad), 6 => Ok(Self::ScratchpadWithPayment), - 7 => Ok(Self::LinkedListWithPayment), + 7 => Ok(Self::GraphEntryWithPayment), 8 => Ok(Self::Pointer), 9 => Ok(Self::PointerWithPayment), _ => Err(serde::de::Error::custom( @@ -192,7 +192,7 @@ mod tests { assert_eq!(chunk.len(), RecordHeader::SIZE); let transaction = RecordHeader { - kind: RecordKind::LinkedList, + kind: RecordKind::GraphEntry, } .try_serialize()?; assert_eq!(transaction.len(), RecordHeader::SIZE); @@ -235,8 +235,8 @@ mod tests { let kinds = vec![ RecordKind::Chunk, RecordKind::ChunkWithPayment, - RecordKind::LinkedList, - RecordKind::LinkedListWithPayment, + RecordKind::GraphEntry, + RecordKind::GraphEntryWithPayment, RecordKind::Register, RecordKind::RegisterWithPayment, RecordKind::Scratchpad, diff --git a/ant-protocol/src/storage/mod.rs b/ant-protocol/src/storage/mod.rs index cb0cca01c5..706beaede0 100644 --- a/ant-protocol/src/storage/mod.rs +++ b/ant-protocol/src/storage/mod.rs @@ -8,8 +8,8 @@ mod address; mod chunks; +mod graph; mod header; -mod linked_list; pub mod pointer; pub use pointer::{Pointer, PointerTarget}; mod scratchpad; @@ -19,10 +19,10 @@ use exponential_backoff::Backoff; use std::{num::NonZeroUsize, time::Duration}; pub use self::{ - address::{ChunkAddress, LinkedListAddress, PointerAddress, ScratchpadAddress}, + address::{ChunkAddress, GraphEntryAddress, PointerAddress, ScratchpadAddress}, chunks::Chunk, + graph::GraphEntry, header::{try_deserialize_record, try_serialize_record, RecordHeader, RecordKind, RecordType}, - linked_list::LinkedList, scratchpad::Scratchpad, }; diff --git a/ant-protocol/src/storage/pointer.rs b/ant-protocol/src/storage/pointer.rs index 38d42347f1..cb87e3a509 100644 --- a/ant-protocol/src/storage/pointer.rs +++ b/ant-protocol/src/storage/pointer.rs @@ -1,4 +1,4 @@ -use crate::storage::{ChunkAddress, LinkedListAddress, PointerAddress, ScratchpadAddress}; +use crate::storage::{ChunkAddress, GraphEntryAddress, PointerAddress, ScratchpadAddress}; use bls::{Error as BlsError, PublicKey, SecretKey, Signature}; use hex::FromHexError; use rand::thread_rng; @@ -31,7 +31,7 @@ pub struct Pointer { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum PointerTarget { ChunkAddress(ChunkAddress), - LinkedListAddress(LinkedListAddress), + GraphEntryAddress(GraphEntryAddress), PointerAddress(PointerAddress), ScratchpadAddress(ScratchpadAddress), } @@ -40,7 +40,7 @@ impl PointerTarget { pub fn xorname(&self) -> XorName { match self { PointerTarget::ChunkAddress(addr) => *addr.xorname(), - PointerTarget::LinkedListAddress(addr) => *addr.xorname(), + PointerTarget::GraphEntryAddress(addr) => *addr.xorname(), PointerTarget::PointerAddress(ptr) => *ptr.xorname(), PointerTarget::ScratchpadAddress(addr) => addr.xorname(), } @@ -153,7 +153,7 @@ mod tests { let counter = 1; let mut rng = thread_rng(); let target = - PointerTarget::LinkedListAddress(LinkedListAddress::new(XorName::random(&mut rng))); + PointerTarget::GraphEntryAddress(GraphEntryAddress::new(XorName::random(&mut rng))); // Create and sign pointer let pointer = Pointer::new(owner_pk, counter, target.clone(), &owner_sk); @@ -172,7 +172,7 @@ mod tests { let counter = 1; let mut rng = thread_rng(); let target = - PointerTarget::LinkedListAddress(LinkedListAddress::new(XorName::random(&mut rng))); + PointerTarget::GraphEntryAddress(GraphEntryAddress::new(XorName::random(&mut rng))); let pointer = Pointer::new(owner_pk, counter, target.clone(), &owner_sk); let xorname = pointer.xorname(); @@ -186,7 +186,7 @@ mod tests { let counter = 1; let mut rng = thread_rng(); let target = - PointerTarget::LinkedListAddress(LinkedListAddress::new(XorName::random(&mut rng))); + PointerTarget::GraphEntryAddress(GraphEntryAddress::new(XorName::random(&mut rng))); let pointer = Pointer::new(owner_pk, counter, target, &owner_sk); let hex = pointer.encode_hex(); diff --git a/ant-protocol/src/storage/scratchpad.rs b/ant-protocol/src/storage/scratchpad.rs index 348ad3a0bf..7a6416845e 100644 --- a/ant-protocol/src/storage/scratchpad.rs +++ b/ant-protocol/src/storage/scratchpad.rs @@ -135,7 +135,7 @@ impl Scratchpad { pub fn to_xor_name_vec(&self) -> Vec { [self.network_address()] .iter() - .filter_map(|f| Some(XorName::from_content(f.as_bytes().as_ref()))) + .map(|f| XorName::from_content(f.as_bytes().as_ref())) .collect::>() } diff --git a/autonomi/src/client/linked_list.rs b/autonomi/src/client/graph.rs similarity index 83% rename from autonomi/src/client/linked_list.rs rename to autonomi/src/client/graph.rs index a3a3a359c4..71749b3289 100644 --- a/autonomi/src/client/linked_list.rs +++ b/autonomi/src/client/graph.rs @@ -13,8 +13,8 @@ use crate::client::UploadSummary; use ant_evm::Amount; use ant_evm::AttoTokens; -pub use ant_protocol::storage::LinkedList; -use ant_protocol::storage::LinkedListAddress; +pub use ant_protocol::storage::GraphEntry; +use ant_protocol::storage::GraphEntryAddress; pub use bls::SecretKey; use ant_evm::{EvmWallet, EvmWalletError}; @@ -28,41 +28,41 @@ use libp2p::kad::{Quorum, Record}; use super::data::CostError; #[derive(Debug, thiserror::Error)] -pub enum TransactionError { +pub enum GraphError { #[error("Cost error: {0}")] Cost(#[from] CostError), #[error("Network error")] Network(#[from] NetworkError), #[error("Serialization error")] Serialization, - #[error("Transaction could not be verified (corrupt)")] + #[error("Verification failed (corrupt)")] FailedVerification, - #[error("Payment failure occurred during transaction creation.")] + #[error("Payment failure occurred during creation.")] Pay(#[from] PayError), #[error("Failed to retrieve wallet payment")] Wallet(#[from] EvmWalletError), #[error("Received invalid quote from node, this node is possibly malfunctioning, try another node by trying another transaction name")] InvalidQuote, - #[error("Transaction already exists at this address: {0:?}")] - TransactionAlreadyExists(LinkedListAddress), + #[error("Entry already exists at this address: {0:?}")] + AlreadyExists(GraphEntryAddress), } impl Client { /// Fetches a Transaction from the network. pub async fn transaction_get( &self, - address: LinkedListAddress, - ) -> Result, TransactionError> { - let transactions = self.network.get_linked_list(address).await?; + address: GraphEntryAddress, + ) -> Result, GraphError> { + let transactions = self.network.get_graph_entry(address).await?; Ok(transactions) } pub async fn transaction_put( &self, - transaction: LinkedList, + transaction: GraphEntry, wallet: &EvmWallet, - ) -> Result<(), TransactionError> { + ) -> Result<(), GraphError> { let address = transaction.address(); // pay for the transaction @@ -81,16 +81,16 @@ impl Client { None => { // transaction was skipped, meaning it was already paid for error!("Transaction at address: {address:?} was already paid for"); - return Err(TransactionError::TransactionAlreadyExists(address)); + return Err(GraphError::AlreadyExists(address)); } }; // prepare the record for network storage let payees = proof.payees(); let record = Record { - key: NetworkAddress::from_linked_list_address(address).to_record_key(), - value: try_serialize_record(&(proof, &transaction), RecordKind::LinkedListWithPayment) - .map_err(|_| TransactionError::Serialization)? + key: NetworkAddress::from_graph_entry_address(address).to_record_key(), + value: try_serialize_record(&(proof, &transaction), RecordKind::GraphEntryWithPayment) + .map_err(|_| GraphError::Serialization)? .to_vec(), publisher: None, expires: None, @@ -133,11 +133,11 @@ impl Client { } /// Get the cost to create a transaction - pub async fn transaction_cost(&self, key: SecretKey) -> Result { + pub async fn transaction_cost(&self, key: SecretKey) -> Result { let pk = key.public_key(); trace!("Getting cost for transaction of {pk:?}"); - let address = LinkedListAddress::from_owner(pk); + let address = GraphEntryAddress::from_owner(pk); let xor = *address.xorname(); let store_quote = self.get_store_quotes(std::iter::once(xor)).await?; let total_cost = AttoTokens::from_atto( diff --git a/autonomi/src/client/mod.rs b/autonomi/src/client/mod.rs index 73e1add961..9c8ae7b4b8 100644 --- a/autonomi/src/client/mod.rs +++ b/autonomi/src/client/mod.rs @@ -15,7 +15,7 @@ pub mod quote; pub mod data; pub mod files; -pub mod linked_list; +pub mod graph; pub mod pointer; #[cfg(feature = "external-signer")] diff --git a/autonomi/src/client/pointer.rs b/autonomi/src/client/pointer.rs index ce2c3f4462..dd759209f5 100644 --- a/autonomi/src/client/pointer.rs +++ b/autonomi/src/client/pointer.rs @@ -1,11 +1,11 @@ -use crate::client::Client; use crate::client::data::PayError; +use crate::client::Client; use tracing::{debug, error, trace}; use ant_evm::{Amount, AttoTokens, EvmWallet, EvmWalletError}; use ant_networking::{GetRecordCfg, NetworkError, PutRecordCfg, VerificationKind}; use ant_protocol::{ - storage::{Pointer, PointerAddress, RecordKind, RetryStrategy, try_serialize_record}, + storage::{try_serialize_record, Pointer, PointerAddress, RecordKind, RetryStrategy}, NetworkAddress, }; use bls::SecretKey; @@ -35,13 +35,10 @@ pub enum PointerError { impl Client { /// Get a pointer from the network - pub async fn pointer_get( - &self, - address: PointerAddress, - ) -> Result { + pub async fn pointer_get(&self, address: PointerAddress) -> Result { let key = NetworkAddress::from_pointer_address(address).to_record_key(); let record = self.network.get_local_record(&key).await?; - + match record { Some(record) => { let (_, pointer): (Vec, Pointer) = rmp_serde::from_slice(&record.value) diff --git a/autonomi/src/python.rs b/autonomi/src/python.rs index f2dd5e1056..6f98801b12 100644 --- a/autonomi/src/python.rs +++ b/autonomi/src/python.rs @@ -192,14 +192,9 @@ impl Client { wallet: &Wallet, ) -> PyResult<()> { let rt = tokio::runtime::Runtime::new().expect("Could not start tokio runtime"); - let pointer = RustPointer::new( - owner.inner.clone(), - counter, - target.inner.clone(), - &key.inner, - ); + let pointer = RustPointer::new(owner.inner, counter, target.inner.clone(), &key.inner); rt.block_on(self.inner.pointer_put(pointer, &wallet.inner)) - .map_err(|e| PyValueError::new_err(format!("Failed to put pointer: {}", e))) + .map_err(|e| PyValueError::new_err(format!("Failed to put pointer: {e}"))) } fn pointer_cost(&self, key: &PySecretKey) -> PyResult { @@ -215,7 +210,7 @@ impl Client { fn pointer_address(&self, owner: &PyPublicKey, counter: u32) -> PyResult { let mut rng = thread_rng(); let pointer = RustPointer::new( - owner.inner.clone(), + owner.inner, counter, RustPointerTarget::ChunkAddress(ChunkAddress::new(XorName::random(&mut rng))), &RustSecretKey::random(), @@ -237,7 +232,7 @@ impl PyPointerAddress { #[new] pub fn new(hex_str: String) -> PyResult { let bytes = hex::decode(&hex_str) - .map_err(|e| PyValueError::new_err(format!("Invalid hex string: {}", e)))?; + .map_err(|e| PyValueError::new_err(format!("Invalid hex string: {e}")))?; let xorname = XorName::from_content(&bytes); Ok(Self { inner: RustPointerAddress::new(xorname), @@ -267,12 +262,7 @@ impl PyPointer { key: &PySecretKey, ) -> PyResult { Ok(Self { - inner: RustPointer::new( - owner.inner.clone(), - counter, - target.inner.clone(), - &key.inner, - ), + inner: RustPointer::new(owner.inner, counter, target.inner.clone(), &key.inner), }) } @@ -291,7 +281,7 @@ impl PyPointer { #[getter] fn target(&self) -> PyPointerTarget { PyPointerTarget { - inner: RustPointerTarget::ChunkAddress(ChunkAddress::new(self.inner.xorname().clone())), + inner: RustPointerTarget::ChunkAddress(ChunkAddress::new(self.inner.xorname())), } } } @@ -322,7 +312,7 @@ impl PyPointerTarget { #[getter] fn target(&self) -> PyPointerTarget { PyPointerTarget { - inner: RustPointerTarget::ChunkAddress(ChunkAddress::new(self.inner.xorname().clone())), + inner: RustPointerTarget::ChunkAddress(ChunkAddress::new(self.inner.xorname())), } } @@ -338,7 +328,7 @@ impl PyPointerTarget { #[staticmethod] fn from_chunk_address(addr: &PyChunkAddress) -> Self { Self { - inner: RustPointerTarget::ChunkAddress(addr.inner.clone()), + inner: RustPointerTarget::ChunkAddress(addr.inner), } } } diff --git a/autonomi/tests/transaction.rs b/autonomi/tests/graph.rs similarity index 86% rename from autonomi/tests/transaction.rs rename to autonomi/tests/graph.rs index af25785126..55c76679ca 100644 --- a/autonomi/tests/transaction.rs +++ b/autonomi/tests/graph.rs @@ -7,8 +7,8 @@ // permissions and limitations relating to use of the SAFE Network Software. use ant_logging::LogBuilder; -use ant_protocol::storage::LinkedList; -use autonomi::{client::linked_list::TransactionError, Client}; +use ant_protocol::storage::GraphEntry; +use autonomi::{client::graph::GraphError, Client}; use eyre::Result; use test_utils::evm::get_funded_wallet; @@ -21,7 +21,7 @@ async fn transaction_put() -> Result<()> { let key = bls::SecretKey::random(); let content = [0u8; 32]; - let transaction = LinkedList::new(key.public_key(), vec![], content, vec![].into(), &key); + let transaction = GraphEntry::new(key.public_key(), vec![], content, vec![].into(), &key); // estimate the cost of the transaction let cost = client.transaction_cost(key.clone()).await?; @@ -41,12 +41,12 @@ async fn transaction_put() -> Result<()> { // try put another transaction with the same address let content2 = [1u8; 32]; - let transaction2 = LinkedList::new(key.public_key(), vec![], content2, vec![].into(), &key); + let transaction2 = GraphEntry::new(key.public_key(), vec![], content2, vec![].into(), &key); let res = client.transaction_put(transaction2.clone(), &wallet).await; assert!(matches!( res, - Err(TransactionError::TransactionAlreadyExists(address)) + Err(GraphError::AlreadyExists(address)) if address == transaction2.address() )); Ok(()) diff --git a/docs/pointer_design_doc.md b/docs/pointer_design_doc.md index 390887d1e4..42034ab41c 100644 --- a/docs/pointer_design_doc.md +++ b/docs/pointer_design_doc.md @@ -2,7 +2,7 @@ ## Overview -The `Pointer` data type is designed to represent a reference to a `LinkedList` in the system. It will include metadata such as the owner, a counter, and a signature to ensure data integrity and authenticity. +The `Pointer` data type is designed to represent a reference to a `GraphEntry` in the system. It will include metadata such as the owner, a counter, and a signature to ensure data integrity and authenticity. ## Structure @@ -10,7 +10,7 @@ The `Pointer` data type is designed to represent a reference to a `LinkedList` i struct Pointer { owner: PubKey, // This is the address of this data type counter: U32, - target: PointerTarget, // Can be PointerAddress, LinkedListAddress, ChunksAddress, or ScratchpadAddress + target: PointerTarget, // Can be PointerAddress, GraphEntryAddress, ChunksAddress, or ScratchpadAddress signature: Sig, // Signature of counter and pointer (and target) } ``` @@ -22,7 +22,7 @@ The `PointerTarget` enum will define the possible target types for a `Pointer`: ```rust enum PointerTarget { PointerAddress(PointerAddress), - LinkedListAddress(LinkedListAddress), + GraphEntryAddress(GraphEntryAddress), ChunkAddress(ChunkAddress), ScratchpadAddress(ScratchpadAddress), } @@ -31,11 +31,11 @@ enum PointerTarget { ## Detailed Implementation and Testing Strategy 1. **Define the `Pointer` Struct**: - - Implement the `Pointer` struct in a new Rust file alongside `linked_list.rs`. + - Implement the `Pointer` struct in a new Rust file alongside `graph_entry.rs`. - **Testing**: Write unit tests to ensure the struct is correctly defined and can be instantiated. 2. **Address Handling**: - - Implement address handling similar to `LinkedListAddress`. + - Implement address handling similar to `GraphEntryAddress`. - **Testing**: Verify address conversion and serialization through unit tests. 3. **Integration with `record_store.rs`**: @@ -47,17 +47,17 @@ enum PointerTarget { - **Testing**: Write tests to validate the signature creation and verification process. 5. **Output Handling**: - - The `Pointer` will point to a `LinkedList`, and the `LinkedList` output will be used as the value. If there is more than one output, the return will be a vector of possible values. + - The `Pointer` will point to a `GraphEntry`, and the `GraphEntry` output will be used as the value. If there is more than one output, the return will be a vector of possible values. - **Testing**: Test the output handling logic to ensure it returns the correct values. 6. **Integration with ant-networking**: - - Implement methods to serialize and deserialize `Pointer` records, similar to how `LinkedList` records are handled. + - Implement methods to serialize and deserialize `Pointer` records, similar to how `GraphEntry` records are handled. - Ensure that the `Pointer` type is supported in the `NodeRecordStore` for storage and retrieval operations. - **Testing**: Conduct end-to-end tests to verify the integration with `ant-networking`. 7. **Payment Handling**: - Introduce `RecordKind::PointerWithPayment` to handle `Pointer` records with payments. - - Implement logic to process `Pointer` records with payments, similar to `LinkedListWithPayment`. + - Implement logic to process `Pointer` records with payments, similar to `GraphEntryWithPayment`. - **Testing**: Test the payment processing logic to ensure it handles payments correctly. 8. **Documentation and Review**: @@ -72,4 +72,4 @@ enum PointerTarget { ## Conclusion -The `Pointer` data type will enhance the system's ability to reference and manage `LinkedList` structures efficiently. Further details will be added as the implementation progresses. +The `Pointer` data type will enhance the system's ability to reference and manage `GraphEntry` structures efficiently. Further details will be added as the implementation progresses.