1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
// Copyright 2021 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // 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 crate::{errors::Error, Client}; use log::{debug, trace}; use sn_data_types::{ PublicKey, Sequence, SequenceAddress, SequenceEntries, SequenceEntry, SequenceIndex, SequencePermissions, SequencePrivatePermissions, SequencePrivatePolicy, SequencePublicPermissions, SequencePublicPolicy, SequenceUser, }; use sn_messaging::client::{ Cmd, DataCmd, DataQuery, Query, QueryResponse, SequenceRead, SequenceWrite, }; use std::collections::BTreeMap; use xor_name::XorName; fn wrap_seq_read(read: SequenceRead) -> Query { Query::Data(DataQuery::Sequence(read)) } impl Client { //---------------------- // Write Operations //--------------------- /// Create Private Sequence Data on to the Network /// /// Creates a private sequence on the network which can be appended to. /// Private data can be removed from the network at a later date. /// /// A tag must be supplied. /// A xorname must be supplied, this can be random or deterministic as per your apps needs. /// /// # Examples /// /// Store data /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let _address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn store_private_sequence( &self, sequence: Option<SequenceEntries>, name: XorName, tag: u64, owner: PublicKey, permissions: BTreeMap<PublicKey, SequencePrivatePermissions>, ) -> Result<SequenceAddress, Error> { trace!("Store Private Sequence Data {:?}", name); let pk = self.public_key().await; let policy = SequencePrivatePolicy { owner, permissions }; let mut data = Sequence::new_private(pk, pk.to_string(), name, tag, Some(policy)); let address = *data.address(); if let Some(entries) = sequence { for entry in entries { let mut op = data.create_unsigned_append_op(entry)?; let bytes = bincode::serialize(&op.crdt_op)?; let signature = self.keypair.sign(&bytes); op.signature = Some(signature); data.apply_op(op.clone())?; } } self.pay_and_write_sequence_to_network(data.clone()).await?; Ok(address) } /// Create Public Sequence Data into the Network /// /// Creates a public sequence on the network which can be appended to. /// Public data can _not_ be removed from the network at a later date. /// /// A tag must be supplied. /// A xorname must be supplied, this can be random or deterministic as per your apps needs. /// /// # Examples /// /// Store data /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, SequenceUser, Token, SequencePublicPermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// SequenceUser::Key(owner), /// SequencePublicPermissions::new(true), /// ); /// /// // The returned address can then be used to `append` data to. /// let _address = client.store_public_sequence(None, name, tag, owner, perms).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn store_public_sequence( &self, sequence: Option<SequenceEntries>, name: XorName, tag: u64, owner: PublicKey, permissions: BTreeMap<SequenceUser, SequencePublicPermissions>, ) -> Result<SequenceAddress, Error> { trace!("Store Public Sequence Data {:?}", name); let pk = self.public_key().await; let policy = SequencePublicPolicy { owner, permissions }; let mut data = Sequence::new_public(pk, pk.to_string(), name, tag, Some(policy)); let address = *data.address(); if let Some(entries) = sequence { for entry in entries { let mut op = data.create_unsigned_append_op(entry)?; let bytes = bincode::serialize(&op.crdt_op)?; let signature = self.keypair.sign(&bytes); op.signature = Some(signature); data.apply_op(op.clone())?; } } self.pay_and_write_sequence_to_network(data.clone()).await?; Ok(address) } /// Delete sequence /// /// You're only able to delete a PrivateSequence. Public data can no be removed from the network. /// /// # Examples /// /// Delete data /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// client.delete_sequence(address).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn delete_sequence(&self, address: SequenceAddress) -> Result<(), Error> { let cmd = DataCmd::Sequence(SequenceWrite::Delete(address)); // Payment for PUT let payment_proof = self.create_write_payment_proof(&cmd).await?; // The _actual_ message let msg_contents = Cmd::Data { cmd, payment: payment_proof.clone(), }; let message = self.create_cmd_message(msg_contents).await?; let _ = self.session.send_cmd(&message).await?; self.apply_write_payment_to_local_actor(payment_proof).await } /// Append to Sequence /// /// Public or private isn't important for append. You can append to either (though the data you append will be Public or Private). /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// client.append_to_sequence(address, b"New Entry Value".to_vec()).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn append_to_sequence( &self, address: SequenceAddress, entry: SequenceEntry, ) -> Result<(), Error> { // First we fetch it so we can get the causality info, // either from local CRDT replica or from the network if not found let mut sequence = self.get_sequence(address).await?; // We can now append the entry to the Sequence let mut op = sequence.create_unsigned_append_op(entry)?; let bytes = bincode::serialize(&op.crdt_op)?; let signature = self.keypair.sign(&bytes); op.signature = Some(signature); sequence.apply_op(op.clone())?; // Finally we can send the mutation to the network's replicas let cmd = DataCmd::Sequence(SequenceWrite::Edit(op)); self.pay_and_send_data_command(cmd).await } /// Store a new public sequenced data object /// Wraps msg_contents for payment validation and mutation pub(crate) async fn pay_and_write_sequence_to_network( &self, data: Sequence, ) -> Result<(), Error> { debug!("Attempting to pay and write data to network"); let cmd = DataCmd::Sequence(SequenceWrite::New(data)); self.pay_and_send_data_command(cmd).await } //---------------------- // Get Sequence //--------------------- /// Get Sequence Data from the Network /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// let _data = client.get_sequence(address).await?; /// /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence(&self, address: SequenceAddress) -> Result<Sequence, Error> { trace!("Get Sequence Data at {:?}", address.name()); // Let's fetch the Sequence from the network let query_result = self .send_query(wrap_seq_read(SequenceRead::Get(address))) .await?; let msg_id = query_result.msg_id; match query_result.response { QueryResponse::GetSequence(res) => res.map_err(|err| Error::from((err, msg_id))), _ => Err(Error::ReceivedUnexpectedEvent), } } /// Get the last data entry from a Sequence Data. /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// client.append_to_sequence(address, b"New Entry Value".to_vec()).await?; /// client.append_to_sequence(address, b"Another New Entry Value".to_vec()).await?; /// /// // Now we can retrieve the alst entry in the sequence: /// let (_position, last_entry) = client.get_sequence_last_entry(address).await?; /// /// assert_eq!(last_entry, b"Another New Entry Value".to_vec()); /// /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_last_entry( &self, address: SequenceAddress, ) -> Result<(u64, SequenceEntry), Error> { trace!( "Get latest entry from Sequence Data at {:?}", address.name() ); let sequence = self.get_sequence(address).await?; // TODO: do we need to query with some specific PK? match sequence.last_entry(None)? { Some(entry) => Ok((sequence.len(None)? - 1, entry.to_vec())), None => Err(Error::from(sn_data_types::Error::NoSuchEntry)), } } /// Get Sequence Data from the Network at a specific version /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// client.append_to_sequence(address, b"New Entry Value".to_vec()).await?; /// client.append_to_sequence(address, b"Another New Entry Value".to_vec()).await?; /// /// // Now we can retrieve the alst entry in the sequence: /// let entry_v1 = client.get_sequence_entry(address, 1).await?; /// /// assert_eq!(entry_v1, b"Another New Entry Value".to_vec()); /// # Ok(()) } ); } /// ``` pub async fn get_sequence_entry( &self, address: SequenceAddress, index_from_start: u64, ) -> Result<SequenceEntry, Error> { trace!( "Get entry at index {:?} from Sequence Data {:?}", index_from_start, address.name() ); let sequence = self.get_sequence(address).await?; let index = SequenceIndex::FromStart(index_from_start); match sequence.get(index, None)? { Some(entry) => Ok(entry.to_vec()), None => Err(Error::from(sn_data_types::Error::NoSuchEntry)), } } /// Get a set of Entries for the requested range from a Sequence. /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions, SequenceIndex}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// client.append_to_sequence(address, b"New Entry Value".to_vec()).await?; /// client.append_to_sequence(address, b"Another New Entry Value".to_vec()).await?; /// client.append_to_sequence(address, b"Third Entry Value".to_vec()).await?; /// /// // Now we can retrieve the alst entry in the sequence: /// let entries = client.get_sequence_range(address, (SequenceIndex::FromStart(1), SequenceIndex::FromEnd(0) )).await?; /// /// assert_eq!(entries[0], b"Another New Entry Value".to_vec()); /// assert_eq!(entries[1], b"Third Entry Value".to_vec()); /// /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_range( &self, address: SequenceAddress, range: (SequenceIndex, SequenceIndex), ) -> Result<SequenceEntries, Error> { trace!( "Get range of entries from Sequence Data at {:?}", address.name() ); let sequence = self.get_sequence(address).await?; // TODO: do we need to query with some specific PK? sequence .in_range(range.0, range.1, None)? .ok_or_else(|| Error::from(sn_data_types::Error::NoSuchEntry)) } //---------------------- // Ownership //--------------------- /// Get the owner of a Sequence. /// /// # Examples /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// let seq_owner = client.get_sequence_owner(address).await?; /// assert_eq!(seq_owner, owner); /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_owner(&self, address: SequenceAddress) -> Result<PublicKey, Error> { trace!("Get owner of the Sequence Data at {:?}", address.name()); // TODO: perhaps we want to grab it directly from the network and update local replica let sequence = self.get_sequence(address).await?; let owner = if sequence.is_public() { sequence.public_policy()?.owner } else { // TODO: do we need to query with some specific PK? sequence.private_policy(None)?.owner }; Ok(owner) } //---------------------- // Permissions //--------------------- /// Get the set of Permissions of a Public Sequence. /// /// # Examples /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, Token, SequenceUser,SequencePublicPermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// SequenceUser::Key(owner), /// SequencePublicPermissions::new(true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_public_sequence(None, name, tag, owner, perms).await?; /// /// let _permissions = client.get_sequence_public_permissions_for_user(address, owner).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_public_permissions_for_user( &self, address: SequenceAddress, user: PublicKey, ) -> Result<SequencePublicPermissions, Error> { trace!( "Get permissions from Public Sequence Data at {:?}", address.name() ); // TODO: perhaps we want to grab it directly from // the network and update local replica let sequence = self.get_sequence(address).await?; // TODO: do we need to query with some specific PK? let perms = match sequence .permissions(SequenceUser::Key(user), None) .map_err(Error::from)? { SequencePermissions::Public(perms) => perms, _ => return Err(Error::NotPublicPermissions), }; Ok(perms) } /// Get the set of Permissions of a Private Sequence. /// /// # Examples /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// let _permissions = client.get_sequence_private_permissions_for_user(address, owner).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_private_permissions_for_user( &self, address: SequenceAddress, user: PublicKey, ) -> Result<SequencePrivatePermissions, Error> { trace!( "Get permissions from Private Sequence Data at {:?}", address.name() ); let sequence = self.get_sequence(address).await?; // TODO: do we need to query with some specific PK? let perms = match sequence .permissions(SequenceUser::Key(user), None) .map_err(Error::from)? { SequencePermissions::Private(perms) => perms, _ => return Err(Error::NotPrivatePermissions), }; Ok(perms) } /// Get the set of Permissions for a specific user in a Sequence. /// /// # Examples /// /// ```no_run /// # extern crate tokio; use anyhow::Result; use std::str::FromStr; /// # use sn_client::utils::test_utils::read_network_conn_info; /// use sn_client::Client; /// use sn_data_types::{Keypair, PublicKey, Token, SequencePrivatePermissions}; /// use std::collections::BTreeMap; /// use xor_name::XorName; /// use rand::rngs::OsRng; /// # #[tokio::main] async fn main() { let _: Result<()> = futures::executor::block_on( async { /// // Let's use an existing client, with a pre-existing balance to be used for write payments. /// let id = Keypair::new_ed25519(&mut OsRng); /// # let bootstrap_contacts = Some(read_network_conn_info()?); /// let mut client = Client::new(Some(id), None, bootstrap_contacts).await?; /// # let initial_balance = Token::from_str("100")?; client.trigger_simulated_farming_payout(initial_balance).await?; /// let name = XorName::random(); /// let tag = 10; /// let owner = client.public_key().await; /// let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); /// /// // Set the access permissions /// let _ = perms.insert( /// owner, /// SequencePrivatePermissions::new(true, true), /// ); /// /// // The returned address can then be used to `append` data to. /// let address = client.store_private_sequence(None, name, tag, owner, perms).await?; /// /// let _permissions = client.get_sequence_public_permissions_for_user(address, owner).await?; /// # let balance_after_write = client.get_local_balance().await; assert_ne!(initial_balance, balance_after_write); Ok(()) } ); } /// ``` pub async fn get_sequence_permissions( &self, address: SequenceAddress, user: SequenceUser, ) -> Result<SequencePermissions, Error> { trace!( "Get permissions for user {:?} from Sequence Data at {:?}", user, address.name() ); // TODO: perhaps we want to grab it directly from // the network and update local replica let sequence = self.get_sequence(address).await?; // TODO: do we need to query with some specific PK? let perms = sequence.permissions(user, None).map_err(Error::from)?; Ok(perms) } } #[cfg(test)] mod tests { use super::*; use crate::utils::test_utils::{create_test_client, gen_ed_keypair}; use anyhow::{anyhow, bail, Result}; use sn_data_types::{Error as DtError, SequenceAction, SequencePrivatePermissions, Token}; use sn_messaging::client::Error as ErrorMessage; use std::str::FromStr; use tokio::time::{sleep, Duration}; use xor_name::XorName; #[tokio::test] pub async fn sequence_deletions_should_cost_put_price() -> Result<()> { let name = XorName(rand::random()); let tag = 10; let client = create_test_client().await?; let owner = client.public_key().await; let perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); let sequence_address = client .store_private_sequence(None, name, tag, owner, perms) .await?; let mut balance_before_delete = client.get_balance().await?; while balance_before_delete == Token::from_str("0")? || balance_before_delete == Token::from_str("10")? { sleep(Duration::from_millis(200)).await; balance_before_delete = client.get_balance().await?; } client.delete_sequence(sequence_address).await?; let mut new_balance = client.get_balance().await?; // now let's ensure we've paid _something_ while new_balance == balance_before_delete { sleep(Duration::from_millis(200)).await; new_balance = client.get_balance().await?; } Ok(()) } /// Sequence data tests /// #[tokio::test] pub async fn sequence_basics() -> Result<()> { let client = create_test_client().await?; let name = XorName(rand::random()); let tag = 15000; let owner = client.public_key().await; // store a Private Sequence let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); let _ = perms.insert(owner, SequencePrivatePermissions::new(true, true)); let address = client .store_private_sequence(None, name, tag, owner, perms) .await?; let mut seq_res = client.get_sequence(address).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.get_sequence(address).await; } let sequence = seq_res?; assert!(sequence.is_private()); assert_eq!(*sequence.name(), name); assert_eq!(sequence.tag(), tag); assert_eq!(sequence.len(None)?, 0); // store a Public Sequence let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); let _ = perms.insert(SequenceUser::Anyone, SequencePublicPermissions::new(true)); let address = client .store_public_sequence(None, name, tag, owner, perms) .await?; let mut seq_res = client.get_sequence(address).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.get_sequence(address).await; } let sequence = seq_res?; assert!(sequence.is_public()); assert_eq!(*sequence.name(), name); assert_eq!(sequence.tag(), tag); assert_eq!(sequence.len(None)?, 0); Ok(()) } #[tokio::test] pub async fn sequence_private_permissions() -> Result<()> { let client = create_test_client().await?; let name = XorName(rand::random()); let tag = 15000; let owner = client.public_key().await; let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); let _ = perms.insert(owner, SequencePrivatePermissions::new(true, true)); let address = client .store_private_sequence(None, name, tag, owner, perms) .await?; let mut seq_res = client.get_sequence(address).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.get_sequence(address).await; } let data = seq_res?; assert_eq!(data.len(None)?, 0); let mut seq_res = client .get_sequence_private_permissions_for_user(address, owner) .await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client .get_sequence_private_permissions_for_user(address, owner) .await; } let user_perms = seq_res?; assert!(user_perms.is_allowed(SequenceAction::Read)); assert!(user_perms.is_allowed(SequenceAction::Append)); let mut seq_res = client .get_sequence_permissions(address, SequenceUser::Key(owner)) .await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client .get_sequence_permissions(address, SequenceUser::Key(owner)) .await; } match seq_res? { SequencePermissions::Private(user_perms) => { assert!(user_perms.is_allowed(SequenceAction::Read)); assert!(user_perms.is_allowed(SequenceAction::Append)); } SequencePermissions::Public(_) => return Err(Error::IncorrectPermissions.into()), } let other_user = gen_ed_keypair().public_key(); match client .get_sequence_private_permissions_for_user(address, other_user) .await { Err(Error::NetworkDataError(DtError::NoSuchEntry)) => {} other => bail!( "Unexpected result when querying private permissions: {:?}", other ), } match client .get_sequence_permissions(address, SequenceUser::Key(other_user)) .await { Err(Error::NetworkDataError(DtError::NoSuchEntry)) => Ok(()), other => Err(anyhow!( "Unexpected result when querying permissions: {:?}", other )), } } #[tokio::test] pub async fn sequence_public_permissions() -> Result<()> { let client = create_test_client().await?; let name = XorName(rand::random()); let tag = 15000; let owner = client.public_key().await; let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); let _ = perms.insert( SequenceUser::Key(owner), SequencePublicPermissions::new(None), ); let address = client .store_public_sequence(None, name, tag, owner, perms) .await?; let mut seq_res = client .get_sequence_public_permissions_for_user(address, owner) .await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client .get_sequence_public_permissions_for_user(address, owner) .await; } let user_perms = seq_res?; assert_eq!(Some(true), user_perms.is_allowed(SequenceAction::Read)); assert_eq!(None, user_perms.is_allowed(SequenceAction::Append)); let mut seq_res = client .get_sequence_permissions(address, SequenceUser::Key(owner)) .await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client .get_sequence_permissions(address, SequenceUser::Key(owner)) .await; } match seq_res? { SequencePermissions::Public(user_perms) => { assert_eq!(Some(true), user_perms.is_allowed(SequenceAction::Read)); assert_eq!(None, user_perms.is_allowed(SequenceAction::Append)); } SequencePermissions::Private(_) => { return Err(anyhow!("Unexpectedly obtained incorrect user permissions",)); } } let other_user = gen_ed_keypair().public_key(); match client .get_sequence_public_permissions_for_user(address, other_user) .await { Err(Error::NetworkDataError(DtError::NoSuchEntry)) => {} other => bail!( "Unexpected result when querying private permissions: {:?}", other ), } match client .get_sequence_permissions(address, SequenceUser::Key(other_user)) .await { Err(Error::NetworkDataError(DtError::NoSuchEntry)) => Ok(()), other => Err(anyhow!( "Unexpected result when querying permissions: {:?}", other )), } } #[tokio::test] pub async fn append_to_sequence() -> Result<()> { let name = XorName(rand::random()); let tag = 10; let client = create_test_client().await?; let owner = client.public_key().await; let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); let _ = perms.insert( SequenceUser::Key(owner), SequencePublicPermissions::new(true), ); let address = client .store_public_sequence(None, name, tag, owner, perms) .await?; // append to the data the data let mut seq_res = client.append_to_sequence(address, b"VALUE1".to_vec()).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.append_to_sequence(address, b"VALUE1".to_vec()).await; } // now check last entry let mut seq_res = client.get_sequence_last_entry(address).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.get_sequence_last_entry(address).await; } let (index, data) = seq_res?; assert_eq!(0, index); assert_eq!(std::str::from_utf8(&data)?, "VALUE1"); // append to the data the data let mut seq_res = client.append_to_sequence(address, b"VALUE2".to_vec()).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.append_to_sequence(address, b"VALUE2".to_vec()).await; } // and then lets check last entry let mut seq_res = client.get_sequence_last_entry(address).await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client.get_sequence_last_entry(address).await; } let (mut index, mut data) = seq_res?; // we might still be getting old data here while index == 0 { sleep(Duration::from_millis(200)).await; let (i, d) = client.get_sequence_last_entry(address).await?; index = i; data = d; } assert_eq!(1, index); assert_eq!(std::str::from_utf8(&data)?, "VALUE2"); let mut seq_res = client .get_sequence_range( address, (SequenceIndex::FromStart(0), SequenceIndex::FromEnd(0)), ) .await; while seq_res.is_err() { sleep(Duration::from_millis(200)).await; seq_res = client .get_sequence_range( address, (SequenceIndex::FromStart(0), SequenceIndex::FromEnd(0)), ) .await; } let data = seq_res?; assert_eq!(std::str::from_utf8(&data[0])?, "VALUE1"); assert_eq!(std::str::from_utf8(&data[1])?, "VALUE2"); // get_sequence_entry let data0 = client.get_sequence_entry(address, 0).await?; assert_eq!(std::str::from_utf8(&data0)?, "VALUE1"); let data1 = client.get_sequence_entry(address, 1).await?; assert_eq!(std::str::from_utf8(&data1)?, "VALUE2"); // Requesting a version that's too high throws an error let res = client.get_sequence_entry(address, 2).await; match res { Err(_) => Ok(()), Ok(_data) => Err(anyhow!( "Unexpectedly retrieved a sequence entry at index that's too high!", )), } } #[tokio::test] pub async fn sequence_owner() -> Result<()> { let name = XorName(rand::random()); let tag = 10; let client = create_test_client().await?; let owner = client.public_key().await; let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); let _ = perms.insert(owner, SequencePrivatePermissions::new(true, true)); let address = client .store_private_sequence(None, name, tag, owner, perms) .await?; // Assert that the data is stored. let mut owner_res = client.get_sequence_owner(address).await; while owner_res.is_err() { sleep(Duration::from_millis(200)).await; owner_res = client.get_sequence_owner(address).await; } let current_owner = owner_res?; assert_eq!(owner, current_owner); Ok(()) } #[tokio::test] pub async fn sequence_can_delete_private() -> Result<()> { let client = create_test_client().await?; let name = XorName(rand::random()); let tag = 15000; let owner = client.public_key().await; // store a Private Sequence let mut perms = BTreeMap::<PublicKey, SequencePrivatePermissions>::new(); let _ = perms.insert(owner, SequencePrivatePermissions::new(true, true)); let address = client .store_private_sequence(None, name, tag, owner, perms) .await?; let mut sequence = client.get_sequence(address).await; while sequence.is_err() { sleep(Duration::from_millis(200)).await; sequence = client.get_sequence(address).await; } assert!(sequence?.is_private()); client.delete_sequence(address).await?; let mut res = client.get_sequence(address).await; while res.is_ok() { sleep(Duration::from_millis(200)).await; res = client.get_sequence(address).await; } match res { Err(Error::ErrorMessage { source: ErrorMessage::DataNotFound(_), .. }) => Ok(()), Err(err) => Err(anyhow!( "Unexpected error returned when deleting a nonexisting Private Sequence: {}", err )), Ok(_data) => Err(anyhow!( "Unexpectedly retrieved a deleted Private Sequence!", )), } } #[tokio::test] pub async fn sequence_cannot_delete_public() -> Result<()> { let client = create_test_client().await?; let name = XorName(rand::random()); let tag = 15000; let owner = client.public_key().await; // store a Public Sequence let mut perms = BTreeMap::<SequenceUser, SequencePublicPermissions>::new(); let _ = perms.insert(SequenceUser::Anyone, SequencePublicPermissions::new(true)); let address = client .store_public_sequence(None, name, tag, owner, perms) .await?; let mut sequence = client.get_sequence(address).await; while sequence.is_err() { sequence = client.get_sequence(address).await; } assert!(sequence?.is_public()); client.delete_sequence(address).await?; // Check that our data still exists. match client.get_sequence(address).await { Err(Error::ErrorMessage { source: ErrorMessage::InvalidOperation(_), .. }) => Ok(()), Err(err) => Err(anyhow!( "Unexpected error returned when attempting to get a Public Sequence: {}", err )), Ok(_data) => Ok(()), } } }