1use core::fmt;
15use std::hash::Hash;
16
17use once_cell::sync::OnceCell;
18use serde::{Deserialize, Serialize};
19use threshold_crypto::serde_impl::SerdeSecret;
20use zeroize::{Zeroize, ZeroizeOnDrop};
21
22use crate::errors::NgError;
23use crate::utils::{
24 decode_key, decode_priv_key, dh_pubkey_array_from_ed_pubkey_slice,
25 dh_pubkey_from_ed_pubkey_slice, ed_privkey_to_ed_pubkey, from_ed_privkey_to_dh_privkey,
26 random_key,
27};
28
29pub type Blake3Digest32 = [u8; 32];
35
36#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
38pub enum Digest {
39 Blake3Digest32(Blake3Digest32),
40}
41
42impl Digest {
43 pub fn from_slice(slice: [u8; 32]) -> Digest {
44 Digest::Blake3Digest32(slice)
45 }
46 pub fn slice(&self) -> &[u8; 32] {
47 match self {
48 Self::Blake3Digest32(o) => o,
49 }
50 }
51}
52
53impl fmt::Display for Digest {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 let ser = serde_bare::to_vec(&self).unwrap();
56 write!(f, "{}", base64_url::encode(&ser))
57 }
58}
59
60impl From<&Vec<u8>> for Digest {
61 fn from(ser: &Vec<u8>) -> Self {
62 let hash = blake3::hash(ser.as_slice());
63 Digest::Blake3Digest32(hash.as_bytes().clone())
64 }
65}
66
67impl From<&[u8; 32]> for Digest {
68 fn from(ser: &[u8; 32]) -> Self {
69 let hash = blake3::hash(ser);
70 Digest::Blake3Digest32(hash.as_bytes().clone())
71 }
72}
73
74impl From<&PubKey> for Digest {
75 fn from(key: &PubKey) -> Self {
76 key.slice().into()
77 }
78}
79
80pub type ChaCha20Key = [u8; 32];
82
83#[derive(Clone, Zeroize, ZeroizeOnDrop, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
85pub enum SymKey {
86 ChaCha20Key(ChaCha20Key),
87}
88
89impl SymKey {
90 pub fn slice(&self) -> &[u8; 32] {
91 match self {
92 SymKey::ChaCha20Key(o) => o,
93 }
94 }
95 pub fn random() -> Self {
96 SymKey::ChaCha20Key(random_key())
97 }
98 pub fn from_array(array: [u8; 32]) -> Self {
99 SymKey::ChaCha20Key(array)
100 }
101 pub fn nil() -> Self {
102 SymKey::ChaCha20Key([0; 32])
103 }
104 #[cfg(any(test, feature = "testing"))]
105 pub fn dummy() -> Self {
106 SymKey::ChaCha20Key([0; 32])
107 }
108}
109
110impl fmt::Display for SymKey {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 let ser = serde_bare::to_vec(&self).unwrap();
113 write!(f, "{}", base64_url::encode(&ser))
114 }
115}
116
117impl TryFrom<&[u8]> for SymKey {
118 type Error = NgError;
119 fn try_from(buf: &[u8]) -> Result<Self, NgError> {
120 let sym_key_array = *slice_as_array!(buf, [u8; 32]).ok_or(NgError::InvalidKey)?;
121 let sym_key = SymKey::ChaCha20Key(sym_key_array);
122 Ok(sym_key)
123 }
124}
125
126pub type Ed25519PubKey = [u8; 32];
128
129pub type X25519PubKey = [u8; 32];
131
132pub type Ed25519PrivKey = [u8; 32];
134
135pub type X25519PrivKey = [u8; 32];
137
138#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
140pub enum PubKey {
141 Ed25519PubKey(Ed25519PubKey),
142 X25519PubKey(X25519PubKey),
143}
144
145impl Default for PubKey {
146 fn default() -> Self {
147 Self::nil()
148 }
149}
150
151impl PubKey {
152 pub fn to_dh(self) -> X25519PubKey {
153 match self {
154 Self::X25519PubKey(x) => x,
155 _ => panic!("cannot call to_dh on an Edward key"),
156 }
157 }
158 pub fn slice(&self) -> &[u8; 32] {
159 match self {
160 PubKey::Ed25519PubKey(o) | PubKey::X25519PubKey(o) => o,
161 }
162 }
163 pub fn to_dh_from_ed(&self) -> PubKey {
164 match self {
165 PubKey::Ed25519PubKey(ed) => dh_pubkey_from_ed_pubkey_slice(ed),
166 _ => panic!(
167 "there is no need to convert a Montgomery key to Montgomery. it is already one. check your code"
168 ),
169 }
170 }
171 pub fn to_dh_slice(&self) -> [u8; 32] {
175 match self {
176 PubKey::Ed25519PubKey(o) => dh_pubkey_array_from_ed_pubkey_slice(o),
177 _ => panic!("can only convert an edward key to montgomery"),
178 }
179 }
180
181 pub fn nil() -> Self {
182 PubKey::Ed25519PubKey([0u8; 32])
183 }
184
185 pub fn to_hash_string(&self) -> String {
186 let ser = serde_bare::to_vec(&self).unwrap();
187 let hash = blake3::hash(&ser);
188 base64_url::encode(&hash.as_bytes())
189 }
190}
191
192impl fmt::Display for PubKey {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 let ser = serde_bare::to_vec(&self).unwrap();
195 write!(f, "{}", base64_url::encode(&ser))
196 }
197}
198
199impl TryFrom<&str> for PubKey {
200 type Error = NgError;
201 fn try_from(str: &str) -> Result<Self, NgError> {
202 decode_key(str)
203 }
204}
205
206#[derive(Clone, Zeroize, ZeroizeOnDrop, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
208pub enum PrivKey {
209 Ed25519PrivKey(Ed25519PrivKey),
210 X25519PrivKey(X25519PrivKey),
211}
212
213#[allow(deprecated)]
214impl Default for PrivKey {
215 fn default() -> Self {
216 Self::nil()
217 }
218}
219
220impl PrivKey {
221 pub fn slice(&self) -> &[u8; 32] {
222 match self {
223 PrivKey::Ed25519PrivKey(o) | PrivKey::X25519PrivKey(o) => o,
224 }
225 }
226 pub fn to_pub(&self) -> PubKey {
227 match self {
228 PrivKey::Ed25519PrivKey(_) => ed_privkey_to_ed_pubkey(self),
229 _ => panic!("X25519PrivKey to pub not implemented"),
230 }
231 }
232
233 pub fn nil() -> PrivKey {
234 PrivKey::Ed25519PrivKey([0u8; 32])
235 }
236
237 #[cfg(any(test, feature = "testing"))]
238 pub fn dummy() -> PrivKey {
239 PrivKey::Ed25519PrivKey([0u8; 32])
240 }
241
242 pub fn to_dh(&self) -> PrivKey {
243 from_ed_privkey_to_dh_privkey(self)
244 }
245
246 pub fn random_ed() -> Self {
247 PrivKey::Ed25519PrivKey(random_key())
248 }
249}
250
251impl From<[u8; 32]> for PrivKey {
252 fn from(buf: [u8; 32]) -> Self {
253 let priv_key = PrivKey::Ed25519PrivKey(buf);
254 priv_key
255 }
256}
257
258impl TryFrom<&[u8]> for PrivKey {
259 type Error = NgError;
260 fn try_from(buf: &[u8]) -> Result<Self, NgError> {
261 let priv_key_array = *slice_as_array!(buf, [u8; 32]).ok_or(NgError::InvalidKey)?;
262 let priv_key = PrivKey::Ed25519PrivKey(priv_key_array);
263 Ok(priv_key)
264 }
265}
266
267impl TryFrom<&str> for PrivKey {
268 type Error = NgError;
269 fn try_from(str: &str) -> Result<Self, NgError> {
270 decode_priv_key(str)
271 }
272}
273
274impl fmt::Display for PrivKey {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 let ser = serde_bare::to_vec(&self).unwrap();
277 write!(f, "{}", base64_url::encode(&ser))
278 }
279}
280
281pub type Ed25519Sig = [[u8; 32]; 2];
283
284#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
286pub enum Sig {
287 Ed25519Sig(Ed25519Sig),
288}
289
290impl fmt::Display for Sig {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 match self {
293 Self::Ed25519Sig(ed) => {
294 write!(
295 f,
296 "{} {}",
297 base64_url::encode(&ed[0]),
298 base64_url::encode(&ed[1])
299 )
300 }
301 }
302 }
303}
304
305impl Sig {
306 pub fn nil() -> Self {
307 Sig::Ed25519Sig([[0; 32]; 2])
308 }
309}
310
311pub type Timestamp = u32;
313
314pub const EPOCH_AS_UNIX_TIMESTAMP: u64 = 1645568520;
315
316#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
318pub enum RelTime {
319 Seconds(u8),
320 Minutes(u8),
321 Hours(u8),
322 Days(u8),
323 None,
324}
325
326impl fmt::Display for RelTime {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 match self {
329 Self::Seconds(s) => writeln!(f, "{} sec.", s),
330 Self::Minutes(s) => writeln!(f, "{} min.", s),
331 Self::Hours(s) => writeln!(f, "{} h.", s),
332 Self::Days(s) => writeln!(f, "{} d.", s),
333 Self::None => writeln!(f, "None"),
334 }
335 }
336}
337
338#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
340pub struct BloomFilterV0 {
341 #[serde(with = "serde_bytes")]
343 pub f: Vec<u8>,
344}
345
346#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
347pub enum BloomFilter {
348 V0(BloomFilterV0),
349}
350
351impl BloomFilter {
352 pub fn filter(&self) -> &Vec<u8> {
353 match self {
354 Self::V0(v0) => &v0.f,
355 }
356 }
357}
358
359pub type RepoId = PubKey;
365
366pub type RepoHash = Digest;
368
369impl From<RepoId> for RepoHash {
370 fn from(id: RepoId) -> Self {
371 Digest::Blake3Digest32(*blake3::hash(id.slice()).as_bytes())
372 }
373}
374
375pub type TopicId = PubKey;
383
384pub type UserId = PubKey;
386
387pub type BranchId = PubKey;
389
390pub type BlockId = Digest;
392
393pub type BlockKey = SymKey;
394
395#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
397pub struct BlockRef {
398 pub id: BlockId,
400
401 pub key: BlockKey,
403}
404
405impl Default for BlockId {
406 fn default() -> Self {
407 Self::nil()
408 }
409}
410
411impl BlockId {
412 #[cfg(any(test, feature = "testing"))]
413 pub fn dummy() -> Self {
414 Digest::Blake3Digest32([0u8; 32])
415 }
416
417 pub fn nil() -> Self {
418 Digest::Blake3Digest32([0u8; 32])
419 }
420}
421
422impl BlockRef {
423 #[cfg(any(test, feature = "testing"))]
424 pub fn dummy() -> Self {
425 BlockRef {
426 id: Digest::Blake3Digest32([0u8; 32]),
427 key: SymKey::ChaCha20Key([0u8; 32]),
428 }
429 }
430
431 pub fn nil() -> Self {
432 BlockRef {
433 id: Digest::Blake3Digest32([0u8; 32]),
434 key: SymKey::ChaCha20Key([0u8; 32]),
435 }
436 }
437
438 pub fn from_id_key(id: BlockId, key: BlockKey) -> Self {
439 BlockRef { id, key }
440 }
441
442 pub fn nuri(&self) -> String {
443 format!(":j:{}:k:{}", self.id, self.key)
444 }
445}
446
447impl From<BlockRef> for (BlockId, BlockKey) {
448 fn from(blockref: BlockRef) -> (BlockId, BlockKey) {
449 (blockref.id.clone(), blockref.key.clone())
450 }
451}
452
453impl From<(&BlockId, &BlockKey)> for BlockRef {
454 fn from(id_key: (&BlockId, &BlockKey)) -> Self {
455 BlockRef {
456 id: id_key.0.clone(),
457 key: id_key.1.clone(),
458 }
459 }
460}
461
462impl fmt::Display for BlockRef {
463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464 write!(f, "{} {}", self.id, self.key)
465 }
466}
467
468pub type ObjectId = BlockId;
470
471pub type ObjectKey = BlockKey;
473
474pub type ObjectRef = BlockRef;
476
477pub type ReadCap = ObjectRef;
484
485pub type ReadCapSecret = ObjectKey;
489
490pub type RepoWriteCapSecret = SymKey;
492
493pub type BranchWriteCapSecret = PrivKey;
495
496pub type OuterOverlayId = Digest;
516
517pub type InnerOverlayId = Digest;
518
519#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
528pub enum OverlayId {
529 Outer(OuterOverlayId),
530 Inner(InnerOverlayId),
531 Global,
532}
533
534impl fmt::Display for OverlayId {
535 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536 let overlay_ser = serde_bare::to_vec(&self).unwrap();
537 write!(f, "{}", base64_url::encode(&overlay_ser))
538 }
539}
540
541impl OverlayId {
542 pub fn inner(
546 store_id: &PubKey,
547 store_overlay_branch_readcap_secret: &ReadCapSecret,
548 ) -> OverlayId {
549 let store_id = serde_bare::to_vec(store_id).unwrap();
550 let mut store_overlay_branch_readcap_secret_ser =
551 serde_bare::to_vec(store_overlay_branch_readcap_secret).unwrap();
552 let mut key: [u8; 32] = blake3::derive_key(
553 "NextGraph Overlay ReadCapSecret BLAKE3 key",
554 store_overlay_branch_readcap_secret_ser.as_slice(),
555 );
556 let key_hash = blake3::keyed_hash(&key, &store_id);
557 store_overlay_branch_readcap_secret_ser.zeroize();
558 key.zeroize();
559 OverlayId::Inner(Digest::from_slice(*key_hash.as_bytes()))
560 }
561
562 pub fn outer(store_id: &PubKey) -> OverlayId {
563 let store_id = serde_bare::to_vec(store_id).unwrap();
564 OverlayId::Outer((&store_id).into())
565 }
566 #[cfg(any(test, feature = "testing"))]
567 pub fn dummy() -> OverlayId {
568 OverlayId::Outer(Digest::dummy())
569 }
570 pub fn nil() -> OverlayId {
571 OverlayId::Outer(Digest::nil())
572 }
573
574 pub fn is_inner(&self) -> bool {
575 match self {
576 Self::Inner(_) => true,
577 _ => false,
578 }
579 }
580
581 pub fn is_outer(&self) -> bool {
582 match self {
583 Self::Outer(_) => true,
584 _ => false,
585 }
586 }
587}
588
589#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
591pub enum StoreOverlayV0 {
592 PublicStore(PubKey),
593 ProtectedStore(PubKey),
594 PrivateStore(PubKey),
595 Group(PubKey),
596 Dialog(Digest),
597}
598
599#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
600pub enum StoreOverlay {
601 V0(StoreOverlayV0),
602 Own(BranchId), }
604
605impl fmt::Display for StoreOverlay {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 match self {
608 Self::V0(v0) => {
609 write!(f, "StoreOverlay V0 ")?;
610 match v0 {
611 StoreOverlayV0::PublicStore(k) => writeln!(f, "PublicStore: {}", k),
612 StoreOverlayV0::ProtectedStore(k) => writeln!(f, "ProtectedStore: {}", k),
613 StoreOverlayV0::PrivateStore(k) => writeln!(f, "PrivateStore: {}", k),
614 StoreOverlayV0::Group(k) => writeln!(f, "Group: {}", k),
615 StoreOverlayV0::Dialog(k) => writeln!(f, "Dialog: {}", k),
616 }
617 }
618 Self::Own(b) => writeln!(f, "Own: {}", b),
619 }
620 }
621}
622
623impl StoreOverlay {
624 pub fn from_store_repo(overlay_branch: BranchId) -> StoreOverlay {
625 StoreOverlay::Own(overlay_branch)
626 }
627
628 pub fn overlay_id_for_read_purpose(&self) -> OverlayId {
629 match self {
630 StoreOverlay::V0(StoreOverlayV0::PublicStore(id))
631 | StoreOverlay::V0(StoreOverlayV0::ProtectedStore(id))
632 | StoreOverlay::V0(StoreOverlayV0::PrivateStore(id))
633 | StoreOverlay::V0(StoreOverlayV0::Group(id)) => OverlayId::outer(id),
634 StoreOverlay::V0(StoreOverlayV0::Dialog(d)) => OverlayId::Inner(d.clone()),
635 StoreOverlay::Own(_) => unimplemented!(),
636 }
637 }
638
639 pub fn overlay_id_for_write_purpose(
640 &self,
641 store_overlay_branch_readcap_secret: ReadCapSecret,
642 ) -> OverlayId {
643 match self {
644 StoreOverlay::V0(StoreOverlayV0::PublicStore(id))
645 | StoreOverlay::V0(StoreOverlayV0::ProtectedStore(id))
646 | StoreOverlay::V0(StoreOverlayV0::PrivateStore(id))
647 | StoreOverlay::V0(StoreOverlayV0::Group(id)) => {
648 OverlayId::inner(id, &store_overlay_branch_readcap_secret)
649 }
650 StoreOverlay::V0(StoreOverlayV0::Dialog(d)) => OverlayId::Inner(d.clone()),
651 StoreOverlay::Own(_) => unimplemented!(),
652 }
653 }
654}
655
656impl From<&StoreRepo> for StoreOverlay {
657 fn from(store_repo: &StoreRepo) -> Self {
658 match store_repo {
659 StoreRepo::V0(v0) => match v0 {
660 StoreRepoV0::PublicStore(id) => {
661 StoreOverlay::V0(StoreOverlayV0::PublicStore(id.clone()))
662 }
663 StoreRepoV0::ProtectedStore(id) => {
664 StoreOverlay::V0(StoreOverlayV0::ProtectedStore(id.clone()))
665 }
666 StoreRepoV0::PrivateStore(id) => {
667 StoreOverlay::V0(StoreOverlayV0::PrivateStore(id.clone()))
668 }
669 StoreRepoV0::Group(id) => StoreOverlay::V0(StoreOverlayV0::Group(id.clone())),
670 StoreRepoV0::Dialog((_, d)) => StoreOverlay::V0(StoreOverlayV0::Dialog(d.clone())),
671 },
672 }
673 }
674}
675
676#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
678pub enum StoreRepoV0 {
679 PublicStore(RepoId),
680 ProtectedStore(RepoId),
681 PrivateStore(RepoId),
682 Group(RepoId),
683 Dialog((RepoId, Digest)),
684}
685
686#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
687pub enum StoreRepo {
688 V0(StoreRepoV0),
689}
690
691impl fmt::Display for StoreRepo {
692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693 write!(
694 f,
695 "StoreRepo V0 {} {}",
696 match self {
697 StoreRepo::V0(v0) => match v0 {
698 StoreRepoV0::PublicStore(_) => "PublicStore",
699 StoreRepoV0::ProtectedStore(_) => "ProtectedStore",
700 StoreRepoV0::PrivateStore(_) => "PrivateStore",
701 StoreRepoV0::Group(_) => "Group",
702 StoreRepoV0::Dialog(_) => "Dialog",
703 },
704 },
705 self.repo_id()
706 )
707 }
708}
709
710impl StoreRepo {
711 pub fn repo_id(&self) -> &RepoId {
712 match self {
713 Self::V0(v0) => match v0 {
714 StoreRepoV0::PublicStore(id)
715 | StoreRepoV0::ProtectedStore(id)
716 | StoreRepoV0::PrivateStore(id)
717 | StoreRepoV0::Group(id)
718 | StoreRepoV0::Dialog((id, _)) => id,
719 },
720 }
721 }
722 #[cfg(any(test, feature = "testing"))]
723 #[allow(deprecated)]
724 pub fn dummy_public_v0() -> Self {
725 let store_pubkey = PubKey::nil();
726 StoreRepo::V0(StoreRepoV0::PublicStore(store_pubkey))
727 }
728 #[cfg(any(test, feature = "testing"))]
729 pub fn dummy_with_key(repo_pubkey: PubKey) -> Self {
730 StoreRepo::V0(StoreRepoV0::PublicStore(repo_pubkey))
731 }
732
733 pub fn nil() -> Self {
734 let store_pubkey = PubKey::nil();
735 StoreRepo::V0(StoreRepoV0::PublicStore(store_pubkey))
736 }
737
738 pub fn new_private(repo_pubkey: PubKey) -> Self {
739 StoreRepo::V0(StoreRepoV0::PrivateStore(repo_pubkey))
740 }
741
742 pub fn outer_overlay(&self) -> OverlayId {
743 self.overlay_id_for_read_purpose()
744 }
745
746 pub fn overlay_id_for_read_purpose(&self) -> OverlayId {
747 let store_overlay: StoreOverlay = self.into();
748 store_overlay.overlay_id_for_read_purpose()
749 }
751
752 pub fn is_private(&self) -> bool {
753 match self {
754 Self::V0(StoreRepoV0::PrivateStore(_)) => true,
755 _ => false,
756 }
757 }
758
759 pub fn overlay_id_for_storage_purpose(&self) -> OverlayId {
777 match self {
778 Self::V0(StoreRepoV0::PublicStore(_id))
779 | Self::V0(StoreRepoV0::ProtectedStore(_id))
780 | Self::V0(StoreRepoV0::Group(_id))
781 | Self::V0(StoreRepoV0::PrivateStore(_id)) => self.overlay_id_for_read_purpose(),
782 Self::V0(StoreRepoV0::Dialog(d)) => OverlayId::Inner(d.1.clone()),
783 }
784 }
785
786 pub fn overlay_id_for_write_purpose(
787 &self,
788 store_overlay_branch_readcap_secret: &ReadCapSecret,
789 ) -> OverlayId {
790 match self {
791 Self::V0(StoreRepoV0::PublicStore(id))
792 | Self::V0(StoreRepoV0::ProtectedStore(id))
793 | Self::V0(StoreRepoV0::Group(id))
794 | Self::V0(StoreRepoV0::PrivateStore(id)) => {
795 OverlayId::inner(id, store_overlay_branch_readcap_secret)
796 }
797 Self::V0(StoreRepoV0::Dialog(d)) => OverlayId::Inner(d.1.clone()),
798 }
799 }
800}
801
802#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
804pub enum SiteType {
805 Org,
806 Individual((PrivKey, ReadCap)), }
808
809#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
811pub struct SiteStore {
812 pub id: PubKey,
813
814 pub store_type: SiteStoreType,
815}
816
817#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
819pub enum SiteStoreType {
820 Public,
821 Protected,
822 Private,
823}
824
825#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
827pub enum SiteName {
828 Personal,
829 Name(String),
830}
831
832#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
834pub struct ReducedSiteV0 {
835 pub user_key: PrivKey,
836
837 pub private_store_read_cap: ReadCap,
838
839 pub core: PubKey,
840 pub bootstraps: Vec<PubKey>,
841}
842
843pub type InternalNode = Vec<BlockKey>;
849
850#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
852pub enum ChunkContentV0 {
853 InternalNode(InternalNode),
855
856 #[serde(with = "serde_bytes")]
857 DataChunk(Vec<u8>),
858}
859
860#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
862pub struct CommitHeaderV0 {
863 #[serde(skip)]
865 pub id: Option<ObjectId>,
866
867 pub deps: Vec<ObjectId>,
869
870 pub ndeps: Vec<ObjectId>,
872
873 pub compact: bool,
877
878 pub acks: Vec<ObjectId>,
880
881 pub nacks: Vec<ObjectId>,
883
884 pub files: Vec<ObjectId>,
886
887 pub nfiles: Vec<ObjectId>,
890}
891
892#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
893pub enum CommitHeader {
894 V0(CommitHeaderV0),
895}
896
897#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
899pub struct CommitHeaderKeysV0 {
900 pub deps: Vec<ObjectKey>,
902
903 pub acks: Vec<ObjectKey>,
907
908 pub nacks: Vec<ObjectKey>,
910
911 pub files: Vec<ObjectRef>,
914 }
917
918#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
919pub enum CommitHeaderKeys {
920 V0(CommitHeaderKeysV0),
921}
922
923#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
924pub enum CommitHeaderObject {
925 Id(ObjectId),
926 EncryptedContent(Vec<u8>),
927 None,
928 RandomAccess,
929}
930
931#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
932pub struct CommitHeaderRef {
933 pub obj: CommitHeaderObject,
934 pub key: ObjectKey,
935}
936
937impl CommitHeaderRef {
938 pub fn from_id_key(id: BlockId, key: ObjectKey) -> Self {
939 CommitHeaderRef {
940 obj: CommitHeaderObject::Id(id),
941 key,
942 }
943 }
944 pub fn from_content_key(content: Vec<u8>, key: ObjectKey) -> Self {
945 CommitHeaderRef {
946 obj: CommitHeaderObject::EncryptedContent(content),
947 key,
948 }
949 }
950 pub fn encrypted_content_len(&self) -> usize {
951 match &self.obj {
952 CommitHeaderObject::EncryptedContent(ec) => ec.len(),
953 _ => 0,
954 }
955 }
956}
957
958#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
960pub struct BlockContentV0 {
961 pub commit_header: CommitHeaderObject,
966
967 pub children: Vec<BlockId>,
970
971 #[serde(with = "serde_bytes")]
981 pub encrypted_content: Vec<u8>,
982}
983
984#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
986pub enum BlockContent {
987 V0(BlockContentV0),
988}
989
990impl BlockContent {
991 pub fn commit_header_obj(&self) -> &CommitHeaderObject {
992 match self {
993 Self::V0(v0) => &v0.commit_header,
994 }
995 }
996}
997
998#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1003pub struct BlockV0 {
1004 #[serde(skip)]
1006 pub id: Option<BlockId>,
1007
1008 #[serde(skip)]
1010 pub key: Option<SymKey>,
1011
1012 pub commit_header_key: Option<ObjectKey>,
1020
1021 pub content: BlockContent,
1022}
1023
1024#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1026pub enum Block {
1027 V0(BlockV0),
1028}
1029
1030#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1041pub struct RepositoryV0 {
1042 pub id: RepoId,
1044
1045 #[serde(with = "serde_bytes")]
1047 pub verification_program: Vec<u8>,
1048
1049 #[serde(with = "serde_bytes")]
1052 pub fork_of: Vec<u8>,
1053
1054 pub creator: Option<UserId>,
1056
1057 #[serde(with = "serde_bytes")]
1064 pub metadata: Vec<u8>,
1065}
1066
1067#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1069pub enum Repository {
1070 V0(RepositoryV0),
1071}
1072
1073impl fmt::Display for Repository {
1074 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1075 match self {
1076 Self::V0(v0) => {
1077 writeln!(f, "V0")?;
1078 writeln!(f, "repo_id: {}", v0.id)?;
1079 writeln!(
1080 f,
1081 "creator: {}",
1082 v0.creator.map_or("None".to_string(), |c| format!("{}", c))
1083 )?;
1084 Ok(())
1085 }
1086 }
1087 }
1088}
1089
1090#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1097pub struct RootBranchV0 {
1098 pub id: PubKey,
1100
1101 pub repo: ObjectRef,
1103
1104 pub store: StoreOverlay,
1107
1108 pub store_sig: Option<Signature>,
1112
1113 pub topic: TopicId,
1115
1116 #[serde(with = "serde_bytes")]
1123 pub topic_privkey: Vec<u8>,
1124
1125 pub inherit_perms_users_and_quorum_from_store: Option<ReadCap>,
1135
1136 pub quorum: Option<ObjectRef>,
1139
1140 pub reconciliation_interval: RelTime,
1142
1143 pub owners: Vec<UserId>,
1145
1146 pub owners_write_cap: Vec<serde_bytes::ByteBuf>,
1150
1151 #[serde(with = "serde_bytes")]
1153 pub metadata: Vec<u8>,
1154}
1155
1156#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1158pub enum RootBranch {
1159 V0(RootBranchV0),
1160}
1161
1162impl RootBranch {
1163 pub fn topic(&self) -> &TopicId {
1164 match self {
1165 Self::V0(v0) => &v0.topic,
1166 }
1167 }
1168 pub fn owners(&self) -> &Vec<UserId> {
1169 match self {
1170 Self::V0(v0) => &v0.owners,
1171 }
1172 }
1173 pub fn encrypt_write_cap(
1174 for_user: &UserId,
1175 write_cap: &RepoWriteCapSecret,
1176 ) -> Result<Vec<u8>, NgError> {
1177 let ser = serde_bare::to_vec(write_cap).unwrap();
1178 let mut rng = crypto_box::aead::OsRng {};
1179 let cipher = crypto_box::seal(&mut rng, &for_user.to_dh_slice().into(), &ser)
1180 .map_err(|_| NgError::EncryptionError)?;
1181 Ok(cipher)
1182 }
1183 pub fn decrypt_write_cap(
1184 by_user: &PrivKey,
1185 cipher: &Vec<u8>,
1186 ) -> Result<RepoWriteCapSecret, NgError> {
1187 let ser = crypto_box::seal_open(&(*by_user.to_dh().slice()).into(), cipher)
1188 .map_err(|_| NgError::DecryptionError)?;
1189 let write_cap: RepoWriteCapSecret =
1190 serde_bare::from_slice(&ser).map_err(|_| NgError::SerializationError)?;
1191 Ok(write_cap)
1192 }
1193}
1194
1195impl fmt::Display for RootBranch {
1196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1197 match self {
1198 Self::V0(v0) => {
1199 writeln!(f, "V0")?;
1200 writeln!(f, "repo_id: {}", v0.id)?;
1201 writeln!(f, "repo_ref: {}", v0.repo)?;
1202 write!(f, "store: {}", v0.store)?;
1203 writeln!(
1204 f,
1205 "store_sig: {}",
1206 v0.store_sig
1207 .as_ref()
1208 .map_or("None".to_string(), |c| format!("{}", c))
1209 )?;
1210 writeln!(f, "topic: {}", v0.topic)?;
1211 writeln!(
1212 f,
1213 "inherit_perms: {}",
1214 v0.inherit_perms_users_and_quorum_from_store
1215 .as_ref()
1216 .map_or("None".to_string(), |c| format!("{}", c))
1217 )?;
1218 writeln!(
1219 f,
1220 "quorum: {}",
1221 v0.quorum
1222 .as_ref()
1223 .map_or("None".to_string(), |c| format!("{}", c))
1224 )?;
1225 writeln!(f, "reconciliation_interval: {}", v0.reconciliation_interval)?;
1226 Ok(())
1227 }
1228 }
1229 }
1230}
1231
1232#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1236pub struct QuorumV0 {
1237 pub partial_order_quorum: u32,
1239
1240 pub partial_order_users: Vec<UserId>,
1242
1243 pub total_order_quorum: u32,
1245
1246 pub total_order_users: Vec<UserId>,
1248
1249 #[serde(with = "serde_bytes")]
1253 pub metadata: Vec<u8>,
1254}
1255
1256#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1259pub enum Quorum {
1260 V0(QuorumV0),
1261}
1262
1263#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1264pub enum BranchContentType {
1265 GraphOnly,
1266 YMap,
1267 YXml,
1268 YText,
1269 Automerge,
1270 None, }
1277
1278#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1287pub struct BranchV0 {
1288 pub id: PubKey,
1290
1291 pub content_type: BranchContentType,
1292
1293 pub repo: ObjectRef,
1295
1296 pub root_branch_readcap_id: ObjectId,
1300
1301 pub topic: PubKey,
1303
1304 #[serde(with = "serde_bytes")]
1310 pub topic_privkey: Vec<u8>,
1311
1312 #[serde(with = "serde_bytes")]
1315 pub pulled_from: Vec<u8>,
1316
1317 #[serde(with = "serde_bytes")]
1319 pub metadata: Vec<u8>,
1320}
1321
1322impl fmt::Display for Branch {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 match self {
1325 Self::V0(v0) => {
1326 writeln!(f, "V0")?;
1327 writeln!(f, "id: {}", v0.id)?;
1328 writeln!(f, "repo: {}", v0.repo)?;
1329 writeln!(f, "root_branch_readcap_id: {}", v0.root_branch_readcap_id)?;
1330 writeln!(f, "topic: {}", v0.topic)?;
1331 writeln!(f, "topic_privkey: {:?}", v0.topic_privkey)?;
1332 Ok(())
1333 }
1334 }
1335 }
1336}
1337
1338#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1340pub enum Branch {
1341 V0(BranchV0),
1342}
1343
1344#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1345pub enum BranchType {
1346 Main, Chat,
1348 Store,
1349 Overlay,
1350 User,
1351 Transactional, Root, }
1355
1356impl fmt::Display for BranchType {
1357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1358 write!(
1359 f,
1360 "{}",
1361 match self {
1362 Self::Main => "Main",
1363 Self::Chat => "Chat",
1364 Self::Store => "Store",
1365 Self::Overlay => "Overlay",
1366 Self::User => "User",
1367 Self::Transactional => "Transactional",
1368 Self::Root => "Root",
1369 }
1371 )
1372 }
1373}
1374
1375#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1379pub struct AddBranchV0 {
1380 pub topic_id: TopicId,
1383
1384 pub branch_id: BranchId,
1385
1386 pub branch_type: BranchType,
1387
1388 pub branch_read_cap: ReadCap,
1391}
1392
1393impl fmt::Display for AddBranch {
1394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1395 match self {
1396 Self::V0(v0) => {
1397 writeln!(f, "V0 {}", v0.branch_type)?;
1398 writeln!(f, "topic_id: {}", v0.topic_id)?;
1399 writeln!(f, "branch_read_cap: {}", v0.branch_read_cap)?;
1400 Ok(())
1401 }
1402 }
1403 }
1404}
1405
1406#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1408pub enum AddBranch {
1409 V0(AddBranchV0),
1410}
1411
1412pub type RemoveBranchV0 = ();
1413
1414#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1418pub enum RemoveBranch {
1419 V0(RemoveBranchV0),
1420}
1421
1422#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1424pub struct AddMemberV0 {
1425 pub member: UserId,
1427
1428 #[serde(with = "serde_bytes")]
1431 pub metadata: Vec<u8>,
1432}
1433
1434#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1435pub enum AddMember {
1436 V0(AddMemberV0),
1437}
1438
1439#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1444pub struct RemoveMemberV0 {
1445 pub member: UserId,
1447
1448 pub banned: bool,
1450
1451 #[serde(with = "serde_bytes")]
1454 pub metadata: Vec<u8>,
1455}
1456
1457#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1458pub enum RemoveMember {
1459 V0(RemoveMemberV0),
1460}
1461
1462#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1464pub struct SignerCap {
1465 pub repo: RepoId,
1466
1467 pub epoch: ObjectId,
1469
1470 pub owner: Option<SerdeSecret<threshold_crypto::SecretKeyShare>>,
1471
1472 pub total_order: Option<SerdeSecret<threshold_crypto::SecretKeyShare>>,
1473
1474 pub partial_order: Option<SerdeSecret<threshold_crypto::SecretKeyShare>>,
1475}
1476
1477#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
1479pub enum PermissionV0 {
1480 Create, Owner, AddReadMember, RemoveMember, AddWritePermission, WriteAsync, WriteSync, Compact, RemoveWritePermission, AddBranch, RemoveBranch, ChangeName, RefreshReadCap, RefreshWriteCap, ChangeQuorum, Admin, ChangeMainBranch,
1507
1508 Chat, Inbox, PermaShare, UpdateStore, RefreshOverlay, }
1515
1516#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1518pub struct AddPermissionV0 {
1519 pub member: UserId,
1521
1522 pub permission: PermissionV0,
1524
1525 #[serde(with = "serde_bytes")]
1533 pub metadata: Vec<u8>,
1534}
1535
1536#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1537pub enum AddPermission {
1538 V0(AddPermissionV0),
1539}
1540
1541impl AddPermission {
1542 pub fn permission_v0(&self) -> &PermissionV0 {
1543 match self {
1544 Self::V0(v0) => &v0.permission,
1545 }
1546 }
1547}
1548
1549#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1551pub struct RemovePermissionV0 {
1552 pub member: UserId,
1554
1555 pub permission: PermissionV0,
1557
1558 #[serde(with = "serde_bytes")]
1564 pub metadata: Vec<u8>,
1565}
1566
1567#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1568pub enum RemovePermission {
1569 V0(RemovePermissionV0),
1570}
1571
1572impl RemovePermission {
1573 pub fn permission_v0(&self) -> &PermissionV0 {
1574 match self {
1575 Self::V0(v0) => &v0.permission,
1576 }
1577 }
1578}
1579
1580#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1581pub enum RepoNamedItemV0 {
1582 Branch(BranchId),
1583 Commit(ObjectId),
1584}
1585
1586#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1587pub enum RepoNamedItem {
1588 V0(RepoNamedItemV0),
1589}
1590
1591#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1596pub struct AddNameV0 {
1597 pub name: String,
1599
1600 pub item: RepoNamedItem,
1602
1603 #[serde(with = "serde_bytes")]
1605 pub metadata: Vec<u8>,
1606}
1607
1608#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1609pub enum AddName {
1610 V0(AddNameV0),
1611}
1612
1613#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1617pub struct RemoveNameV0 {
1618 pub name: String,
1620
1621 #[serde(with = "serde_bytes")]
1623 pub metadata: Vec<u8>,
1624}
1625
1626#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1627pub enum RemoveName {
1628 V0(RemoveNameV0),
1629}
1630
1631#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1640pub struct AddRepoV0 {
1641 pub read_cap: ReadCap,
1642
1643 #[serde(with = "serde_bytes")]
1645 pub metadata: Vec<u8>,
1646}
1647
1648#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1649pub enum AddRepo {
1650 V0(AddRepoV0),
1651}
1652
1653#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1657pub struct RemoveRepoV0 {
1658 pub id: RepoId,
1659
1660 #[serde(with = "serde_bytes")]
1662 pub metadata: Vec<u8>,
1663}
1664
1665#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1666pub enum RemoveRepo {
1667 V0(RemoveRepoV0),
1668}
1669
1670#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1681pub struct AddLinkV0 {
1682 pub read_cap: ReadCap,
1683
1684 #[serde(with = "serde_bytes")]
1686 pub metadata: Vec<u8>,
1687}
1688
1689#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1690pub enum AddLink {
1691 V0(AddLinkV0),
1692}
1693
1694#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1698pub struct RemoveLinkV0 {
1699 pub id: RepoId,
1700
1701 #[serde(with = "serde_bytes")]
1703 pub metadata: Vec<u8>,
1704}
1705
1706#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1707pub enum RemoveLink {
1708 V0(RemoveLinkV0),
1709}
1710
1711#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1718pub struct AddSignerCapV0 {
1719 pub cap: SignerCap,
1720
1721 #[serde(with = "serde_bytes")]
1723 pub metadata: Vec<u8>,
1724}
1725
1726#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1727pub enum AddSignerCap {
1728 V0(AddSignerCapV0),
1729}
1730
1731impl fmt::Display for AddSignerCap {
1732 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1733 match self {
1734 Self::V0(v0) => {
1735 writeln!(f, "V0")?;
1736 writeln!(f, "cap: {:?}", v0.cap)?;
1737
1738 Ok(())
1739 }
1740 }
1741 }
1742}
1743
1744#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1748pub struct RemoveSignerCapV0 {
1749 pub id: RepoId,
1750
1751 #[serde(with = "serde_bytes")]
1753 pub metadata: Vec<u8>,
1754}
1755
1756#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1757pub enum RemoveSignerCap {
1758 V0(RemoveSignerCapV0),
1759}
1760
1761#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1765pub struct WalletUpdateV0 {
1766 #[serde(with = "serde_bytes")]
1767 pub op: Vec<u8>,
1768
1769 #[serde(with = "serde_bytes")]
1771 pub metadata: Vec<u8>,
1772}
1773
1774#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1775pub enum WalletUpdate {
1776 V0(WalletUpdateV0),
1777}
1778
1779#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1785pub struct StoreUpdateV0 {
1786 pub store: StoreRepo,
1788
1789 pub store_read_cap: ReadCap,
1790
1791 pub overlay_branch_read_cap: ReadCap,
1792
1793 #[serde(with = "serde_bytes")]
1795 pub metadata: Vec<u8>,
1796}
1797
1798#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1799pub enum StoreUpdate {
1800 V0(StoreUpdateV0),
1801}
1802
1803impl fmt::Display for StoreUpdate {
1804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1805 match self {
1806 Self::V0(v0) => {
1807 writeln!(f, "V0")?;
1808 writeln!(f, "store: {}", v0.store)?;
1809 writeln!(f, "store_read_cap: {}", v0.store_read_cap)?;
1810 write!(
1811 f,
1812 "overlay_branch_read_cap: {}",
1813 v0.overlay_branch_read_cap
1814 )?;
1815 Ok(())
1816 }
1817 }
1818 }
1819}
1820
1821pub type TransactionV0 = Vec<u8>;
1829
1830#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1831pub enum Transaction {
1832 #[serde(with = "serde_bytes")]
1833 V0(TransactionV0),
1834}
1835
1836#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1840pub struct AddFileV0 {
1841 pub name: Option<String>,
1843
1844 #[serde(with = "serde_bytes")]
1846 pub metadata: Vec<u8>,
1847}
1848
1849#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1850pub enum AddFile {
1851 V0(AddFileV0),
1852}
1853
1854impl fmt::Display for AddFile {
1855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856 match self {
1857 Self::V0(v0) => {
1858 writeln!(f, "V0")?;
1859 writeln!(f, "name: {:?}", v0.name)
1860 }
1861 }
1862 }
1863}
1864
1865impl AddFile {
1866 pub fn name(&self) -> &Option<String> {
1867 match self {
1868 Self::V0(v0) => &v0.name,
1869 }
1870 }
1871}
1872
1873pub type RemoveFileV0 = ();
1879
1880#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1881pub enum RemoveFile {
1882 V0(RemoveFileV0),
1883}
1884
1885#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1891pub struct SnapshotV0 {
1892 pub heads: Vec<ObjectId>,
1894
1895 #[serde(with = "serde_bytes")]
1897 pub content: Vec<u8>,
1898}
1899
1900#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1902pub enum Snapshot {
1903 V0(SnapshotV0),
1904}
1905
1906#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1917pub struct CompactV0 {
1918 pub heads: Vec<ObjectId>,
1920
1921 #[serde(with = "serde_bytes")]
1923 pub origin: Vec<u8>,
1924
1925 #[serde(with = "serde_bytes")]
1927 pub content: Vec<u8>,
1928}
1929
1930#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1932pub enum Compact {
1933 V0(CompactV0),
1934}
1935
1936#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1948pub enum AsyncSignature {
1949 V0(ObjectRef),
1950}
1951
1952impl AsyncSignature {
1953 pub fn verify(&self) -> bool {
1954 unimplemented!();
1956 }
1957}
1958
1959#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1972pub enum SyncSignature {
1973 V0(ObjectRef),
1974}
1975
1976impl SyncSignature {
1977 pub fn verify_quorum(&self) -> bool {
1978 unimplemented!();
1980 }
1981}
1982
1983impl fmt::Display for SyncSignature {
1984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1985 match self {
1986 Self::V0(v0) => {
1987 writeln!(f, "V0")?;
1988 writeln!(f, "{}", v0)?;
1989 Ok(())
1990 }
1991 }
1992 }
1993}
1994
1995#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1997pub struct RefreshSecretV0(SymKey, Option<SymKey>);
1998
1999#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2000pub struct RefreshCapV0 {
2001 pub refresh_secret: Vec<(Digest, serde_bytes::ByteBuf)>,
2006}
2007
2008#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2010pub enum RefreshCap {
2011 V0(RefreshCapV0),
2012}
2013
2014#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2027pub struct RootCapRefreshV0 {
2028 pub refresh_ref: ObjectRef,
2030
2031 pub write_cap: Option<RepoWriteCapSecret>,
2034}
2035
2036#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2038pub enum RootCapRefresh {
2039 V0(RootCapRefreshV0),
2040}
2041
2042#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2053pub struct BranchCapRefreshV0 {
2054 pub refresh_ref: ObjectRef,
2056}
2057
2058#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2060pub enum BranchCapRefresh {
2061 V0(BranchCapRefreshV0),
2062}
2063
2064#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2066pub struct BranchCapRefreshedV0 {
2067 pub continuation_of: ReadCap,
2069
2070 pub refresh: ObjectRef,
2072
2073 pub new_read_cap: ReadCap,
2075}
2076
2077#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2079pub enum BranchCapRefreshed {
2080 V0(BranchCapRefreshedV0),
2081}
2082
2083#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2085pub struct SignatureContentV0 {
2086 pub commits: Vec<ObjectId>,
2088}
2089
2090#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2092pub enum SignatureContent {
2093 V0(SignatureContentV0),
2094}
2095
2096impl fmt::Display for SignatureContent {
2097 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2098 match self {
2099 Self::V0(v0) => {
2100 writeln!(f, "V0 == Commits: {}", v0.commits.len())?;
2101 let mut i = 0;
2102 for block_id in &v0.commits {
2103 writeln!(f, "========== {:03}: {}", i, block_id)?;
2104 i += 1;
2105 }
2106 Ok(())
2107 }
2108 }
2109 }
2110}
2111
2112#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2114pub enum ThresholdSignatureV0 {
2115 PartialOrder(threshold_crypto::Signature),
2116 TotalOrder(threshold_crypto::Signature),
2117 Owners(threshold_crypto::Signature),
2118}
2119
2120impl fmt::Display for ThresholdSignatureV0 {
2121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2122 match self {
2123 Self::PartialOrder(_) => {
2124 writeln!(f, "PartialOrder")
2125 }
2126 Self::TotalOrder(_) => {
2127 writeln!(f, "TotalOrder")
2128 }
2129 Self::Owners(_) => {
2130 writeln!(f, "Owners")
2131 }
2132 }
2133 }
2134}
2135
2136#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2138pub struct SignatureV0 {
2139 pub content: SignatureContent,
2141
2142 pub threshold_sig: ThresholdSignatureV0,
2144
2145 pub certificate_ref: ObjectRef,
2147}
2148
2149impl fmt::Display for Signature {
2150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2151 match self {
2152 Self::V0(v0) => {
2153 writeln!(f, "V0")?;
2154 writeln!(f, "content: {}", v0.content)?;
2155 writeln!(f, "threshold_sig: {}", v0.threshold_sig)?;
2156 writeln!(f, "certificate_ref:{}", v0.certificate_ref)?;
2157 Ok(())
2158 }
2159 }
2160 }
2161}
2162
2163#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2165pub enum Signature {
2166 V0(SignatureV0),
2167}
2168
2169#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2176pub enum OrdersPublicKeySetsV0 {
2177 Store(ObjectRef),
2178 Repo(
2179 (
2180 threshold_crypto::PublicKeySet,
2181 Option<threshold_crypto::PublicKey>,
2182 ),
2183 ),
2184 None, }
2186
2187#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2189pub struct CertificateContentV0 {
2190 pub previous: ObjectRef,
2192
2193 pub readcap_id: ObjectId,
2196
2197 pub owners_pk_set: threshold_crypto::PublicKey,
2199
2200 pub orders_pk_sets: OrdersPublicKeySetsV0,
2202}
2203
2204#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2206pub enum CertificateSignatureV0 {
2207 Repo(Sig),
2209 TotalOrder(threshold_crypto::Signature),
2211 Owners(threshold_crypto::Signature),
2218 Store,
2221}
2222
2223#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2225pub struct CertificateV0 {
2226 pub content: CertificateContentV0,
2228
2229 pub sig: CertificateSignatureV0,
2231}
2232
2233#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2235pub enum Certificate {
2236 V0(CertificateV0),
2237}
2238
2239#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2241pub enum CommitBodyV0 {
2242 Repository(Repository), RootBranch(RootBranch), UpdateRootBranch(RootBranch), RootCapRefresh(RootCapRefresh), AddMember(AddMember), RemoveMember(RemoveMember), AddPermission(AddPermission),
2252 RemovePermission(RemovePermission),
2253 AddBranch(AddBranch),
2254 RemoveBranch(RemoveBranch),
2255 AddName(AddName),
2256 RemoveName(RemoveName),
2257 Delete(()), Branch(Branch), BranchCapRefresh(BranchCapRefresh), UpdateBranch(Branch), Snapshot(Snapshot), AsyncTransaction(Transaction), SyncTransaction(Transaction), AddFile(AddFile),
2271 RemoveFile(RemoveFile),
2272 Compact(Compact), AsyncSignature(AsyncSignature),
2276
2277 CapRefreshed(BranchCapRefreshed), SyncSignature(SyncSignature),
2282
2283 AddRepo(AddRepo),
2287 RemoveRepo(RemoveRepo),
2288
2289 AddLink(AddLink),
2293 RemoveLink(RemoveLink),
2294 AddSignerCap(AddSignerCap),
2295 RemoveSignerCap(RemoveSignerCap),
2296 WalletUpdate(WalletUpdate),
2297 StoreUpdate(StoreUpdate),
2298}
2299
2300#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2302pub enum CommitBody {
2303 V0(CommitBodyV0),
2304}
2305
2306#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2307pub enum QuorumType {
2308 NoSigning,
2309 PartialOrder,
2310 TotalOrder,
2311 Owners,
2312 IamTheSignature,
2313}
2314
2315#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2317pub struct CommitContentV0 {
2318 pub author: Digest,
2325
2326 pub branch: BranchId,
2330
2331 pub perms: Vec<ObjectId>,
2333
2334 pub header_keys: Option<CommitHeaderKeys>,
2336
2337 pub quorum: QuorumType,
2339
2340 #[serde(with = "serde_bytes")]
2342 pub metadata: Vec<u8>,
2343
2344 pub body: ObjectRef,
2347}
2348
2349#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2351pub enum CommitContent {
2352 V0(CommitContentV0),
2353}
2354
2355impl CommitContent {
2356 pub fn header_keys(&self) -> &Option<CommitHeaderKeys> {
2357 match self {
2358 CommitContent::V0(v0) => &v0.header_keys,
2359 }
2360 }
2361 pub fn author(&self) -> &Digest {
2362 match self {
2363 CommitContent::V0(v0) => &v0.author,
2364 }
2365 }
2366 pub fn branch(&self) -> &BranchId {
2367 match self {
2368 CommitContent::V0(v0) => &v0.branch,
2369 }
2370 }
2371
2372 pub fn author_digest(author: &UserId, overlay: OverlayId) -> Digest {
2373 let author_id = serde_bare::to_vec(author).unwrap();
2374 let overlay_id = serde_bare::to_vec(&overlay).unwrap();
2375 let mut key: [u8; 32] = blake3::derive_key(
2376 "NextGraph UserId Hash Overlay Id for Commit BLAKE3 key",
2377 overlay_id.as_slice(),
2378 );
2379 let key_hash = blake3::keyed_hash(&key, &author_id);
2380 key.zeroize();
2381 Digest::from_slice(*key_hash.as_bytes())
2382 }
2383}
2384
2385#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2389pub struct CommitV0 {
2390 #[serde(skip)]
2392 pub id: Option<ObjectId>,
2393
2394 #[serde(skip)]
2396 pub key: Option<SymKey>,
2397
2398 #[serde(skip)]
2400 pub header: Option<CommitHeader>,
2401
2402 #[serde(skip)]
2404 pub body: OnceCell<CommitBody>,
2405
2406 #[serde(skip)]
2408 pub blocks: Vec<BlockId>,
2409
2410 pub content: CommitContent,
2412
2413 pub sig: Sig,
2415}
2416
2417#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2419pub enum Commit {
2420 V0(CommitV0),
2421}
2422
2423#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2425pub struct SmallFileV0 {
2426 pub content_type: String,
2427
2428 #[serde(with = "serde_bytes")]
2429 pub metadata: Vec<u8>,
2430
2431 #[serde(with = "serde_bytes")]
2432 pub content: Vec<u8>,
2433}
2434
2435#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2437pub enum SmallFile {
2438 V0(SmallFileV0),
2439}
2440
2441#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2443pub struct RandomAccessFileMetaV0 {
2444 pub content_type: String,
2445
2446 #[serde(with = "serde_bytes")]
2447 pub metadata: Vec<u8>,
2448
2449 pub total_size: u64,
2450
2451 pub chunk_size: u32,
2452
2453 pub arity: u16,
2454
2455 pub depth: u8,
2456}
2457
2458#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2460pub enum RandomAccessFileMeta {
2461 V0(RandomAccessFileMetaV0),
2462}
2463
2464impl RandomAccessFileMeta {
2465 pub fn arity(&self) -> u16 {
2466 match self {
2467 Self::V0(v0) => v0.arity,
2468 }
2469 }
2470
2471 pub fn depth(&self) -> u8 {
2472 match self {
2473 Self::V0(v0) => v0.depth,
2474 }
2475 }
2476
2477 pub fn set_depth(&mut self, depth: u8) {
2478 match self {
2479 Self::V0(v0) => {
2480 v0.depth = depth;
2481 }
2482 }
2483 }
2484
2485 pub fn chunk_size(&self) -> u32 {
2486 match self {
2487 Self::V0(v0) => v0.chunk_size,
2488 }
2489 }
2490
2491 pub fn total_size(&self) -> u64 {
2492 match self {
2493 Self::V0(v0) => v0.total_size,
2494 }
2495 }
2496
2497 pub fn set_total_size(&mut self, size: u64) {
2498 match self {
2499 Self::V0(v0) => {
2500 v0.total_size = size;
2501 }
2502 }
2503 }
2504
2505 pub fn metadata(&self) -> &Vec<u8> {
2506 match self {
2507 Self::V0(v0) => &v0.metadata,
2508 }
2509 }
2510
2511 pub fn content_type(&self) -> &String {
2512 match self {
2513 Self::V0(v0) => &v0.content_type,
2514 }
2515 }
2516}
2517
2518#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2520pub enum ObjectContentV0 {
2521 Commit(Commit),
2522 CommitBody(CommitBody),
2523 CommitHeader(CommitHeader),
2524 Quorum(Quorum),
2525 Signature(Signature),
2526 Certificate(Certificate),
2527 SmallFile(SmallFile),
2528 RandomAccessFileMeta(RandomAccessFileMeta),
2529 RefreshCap(RefreshCap),
2530}
2531
2532#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2534pub enum ObjectContent {
2535 V0(ObjectContentV0),
2536}
2537
2538pub trait IObject {
2543 fn block_ids(&self) -> Vec<BlockId>;
2544
2545 fn id(&self) -> Option<ObjectId>;
2546
2547 fn key(&self) -> Option<SymKey>;
2548}
2549
2550pub type DirectPeerId = PubKey;
2551
2552pub type ForwardedPeerId = PubKey;
2553
2554#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
2556pub enum PeerId {
2557 Direct(DirectPeerId),
2558 Forwarded(ForwardedPeerId),
2559 ForwardedObfuscated(Digest),
2562}
2563
2564impl fmt::Display for PeerId {
2565 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2566 match self {
2567 Self::Direct(p) => {
2568 write!(f, "Direct : {}", p)
2569 }
2570 Self::Forwarded(p) => {
2571 write!(f, "Forwarded : {}", p)
2572 }
2573 Self::ForwardedObfuscated(p) => {
2574 write!(f, "ForwardedObfuscated : {}", p)
2575 }
2576 }
2577 }
2578}
2579
2580impl PeerId {
2581 pub fn get_pub_key(&self) -> PubKey {
2582 match self {
2583 Self::Direct(pk) | Self::Forwarded(pk) => pk.clone(),
2584 _ => panic!("cannot get a pubkey for ForwardedObfuscated"),
2585 }
2586 }
2587}
2588
2589#[derive(Clone, Debug, Serialize, Deserialize)]
2594pub struct EventContentV0 {
2595 pub topic: TopicId,
2597
2598 pub publisher: PeerId,
2601
2602 pub seq: u64,
2604
2605 pub blocks: Vec<Block>,
2613
2614 pub file_ids: Vec<BlockId>,
2617
2618 #[serde(with = "serde_bytes")]
2633 pub key: Vec<u8>,
2634}
2635
2636#[derive(Clone, Debug, Serialize, Deserialize)]
2640pub struct EventV0 {
2641 pub content: EventContentV0,
2642
2643 pub topic_sig: Sig,
2645
2646 pub peer_sig: Sig,
2648}
2649
2650#[derive(Clone, Debug, Serialize, Deserialize)]
2652pub enum Event {
2653 V0(EventV0),
2654}