holochain_integrity_types 0.8.0-dev.0

Holochain integrity types
Documentation
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
use crate::entry_def::EntryVisibility;
use crate::genesis::MembraneProof;
use crate::link::{LinkTag, LinkType};
use holo_hash::{
    ActionHash, AgentPubKey, AnyLinkableHash, DnaHash, EntryHash, HashableContent,
    HashableContentBytes, HoloHashed,
};
use holochain_serialized_bytes::prelude::*;
use holochain_timestamp::Timestamp;
use std::borrow::Borrow;

pub mod conversions;

/// Any action with a action_seq less than this value is part of a record
/// created during genesis. Anything with this seq or higher was created
/// after genesis.
pub const POST_GENESIS_SEQ_THRESHOLD: u32 = 3;

/// this id is an internal reference, which also serves as a canonical ordering
/// for zome initialization.  The value should be auto-generated from the Zome Bundle def
// TODO: Check this can never be written to > 255
#[derive(
    Debug,
    Copy,
    Clone,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    SerializedBytes,
)]
pub struct ZomeIndex(pub u8);

impl ZomeIndex {
    pub fn new(u: u8) -> Self {
        Self(u)
    }
}

#[derive(
    Debug,
    Copy,
    Clone,
    Hash,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    SerializedBytes,
)]
pub struct EntryDefIndex(pub u8);

/// Description of how to find the previous or next CellId in a migration.
/// In a migration, of the two components of the CellId (dna and agent),
/// always one stays fixed while the other one changes.
/// This enum represents the component that changed.
///
/// When used in CloseChain, this contains the new DNA hash or Agent key.
/// When used in OpenChain, this contains the previous DNA hash or Agent key.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, SerializedBytes, Hash)]
pub enum MigrationTarget {
    /// Represents a DNA migration, and contains the new or previous DNA hash.
    Dna(DnaHash),
    /// Represents an Agent migration, and contains the new or previous Agent key.
    Agent(AgentPubKey),
}

impl From<DnaHash> for MigrationTarget {
    fn from(dna: DnaHash) -> Self {
        MigrationTarget::Dna(dna)
    }
}

impl From<AgentPubKey> for MigrationTarget {
    fn from(agent: AgentPubKey) -> Self {
        MigrationTarget::Agent(agent)
    }
}

/// Allows Actions which reference Entries to know what type of Entry it is
/// referencing. Useful for examining Actions without needing to fetch the
/// corresponding Entries.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, SerializedBytes, Hash)]
pub enum EntryType {
    /// An AgentPubKey
    AgentPubKey,
    /// An app-provided entry, along with its app-provided AppEntryDef
    App(AppEntryDef),
    /// A Capability claim
    CapClaim,
    /// A Capability grant.
    CapGrant,
}

impl EntryType {
    pub fn visibility(&self) -> &EntryVisibility {
        match self {
            EntryType::AgentPubKey => &EntryVisibility::Public,
            EntryType::App(app_entry_def) => app_entry_def.visibility(),
            EntryType::CapClaim => &EntryVisibility::Private,
            EntryType::CapGrant => &EntryVisibility::Private,
        }
    }
}

impl std::fmt::Display for EntryType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EntryType::AgentPubKey => write!(f, "AgentPubKey"),
            EntryType::App(app_entry_def) => write!(
                f,
                "App({:?}, {:?})",
                app_entry_def.entry_index(),
                app_entry_def.visibility()
            ),
            EntryType::CapClaim => write!(f, "CapClaim"),
            EntryType::CapGrant => write!(f, "CapGrant"),
        }
    }
}

/// Information about a class of Entries provided by the DNA
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, SerializedBytes, Hash)]
pub struct AppEntryDef {
    /// A unique u8 identifier within a zome for this
    /// entry type.
    pub entry_index: EntryDefIndex,
    /// The id of the zome that defines this entry type.
    pub zome_index: ZomeIndex,
    // @todo don't do this, use entry defs instead
    /// The visibility of this app entry.
    pub visibility: EntryVisibility,
}

impl AppEntryDef {
    pub fn new(
        entry_index: EntryDefIndex,
        zome_index: ZomeIndex,
        visibility: EntryVisibility,
    ) -> Self {
        Self {
            entry_index,
            zome_index,
            visibility,
        }
    }

    pub fn entry_index(&self) -> EntryDefIndex {
        self.entry_index
    }
    pub fn zome_index(&self) -> ZomeIndex {
        self.zome_index
    }
    pub fn visibility(&self) -> &EntryVisibility {
        &self.visibility
    }
}

impl From<EntryDefIndex> for u8 {
    fn from(ei: EntryDefIndex) -> Self {
        ei.0
    }
}

impl ZomeIndex {
    /// Use as an index into a slice
    pub fn index(&self) -> usize {
        self.0 as usize
    }
}

impl std::ops::Deref for ZomeIndex {
    type Target = u8;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Borrow<u8> for ZomeIndex {
    fn borrow(&self) -> &u8 {
        &self.0
    }
}

pub trait ActionHashedContainer: ActionSequenceAndHash {
    fn action(&self) -> &Action;

    fn action_hash(&self) -> &ActionHash;
}

pub trait ActionSequenceAndHash {
    fn action_seq(&self) -> u32;
    fn address(&self) -> &ActionHash;
}

impl ActionSequenceAndHash for (u32, ActionHash) {
    fn action_seq(&self) -> u32 {
        self.0
    }

    fn address(&self) -> &ActionHash {
        &self.1
    }
}

/// Record-level validation outcome.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[repr(i64)]
pub enum RecordValidity {
    /// The record was accepted.
    Accepted = 1,
    /// The record was rejected.
    Rejected = 2,
}

/// Alias for the validation status of a DHT op (chain op or warrant).
///
/// Semantically identical to [`RecordValidity`] — `Accepted` or `Rejected` —
/// but named for ops rather than records to make call-site intent clearer.
pub type OpValidity = RecordValidity;

/// Maps [`RecordValidity`] onto the `record_validity` /
/// `sys_validation_status` / `app_validation_status` INTEGER columns
/// (`1 = Accepted`, `2 = Rejected`). `0` is reserved and never written.
/// `NULL` represents pending and is decoded at the column boundary, not
/// via this impl.
impl From<RecordValidity> for i64 {
    fn from(v: RecordValidity) -> Self {
        v as i64
    }
}

/// Inverse of [`From<RecordValidity> for i64`]. Returns `Err(v)` for any
/// value outside `1..=2` (including `0`).
impl TryFrom<i64> for RecordValidity {
    type Error = i64;
    fn try_from(v: i64) -> Result<Self, Self::Error> {
        match v {
            1 => Ok(RecordValidity::Accepted),
            2 => Ok(RecordValidity::Rejected),
            other => Err(other),
        }
    }
}

/// Action-type discriminant.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
#[repr(i64)]
pub enum ActionType {
    /// Genesis DNA action. Always `action_seq == 0` and `prev_action == None`.
    Dna = 1,
    /// Agent validation package (membership proof) action.
    AgentValidationPkg = 2,
    /// Marker action emitted once all init zomes have completed.
    InitZomesComplete = 3,
    /// Creates a new entry on the chain.
    Create = 4,
    /// Updates an existing entry with new content.
    Update = 5,
    /// Deletes an existing entry.
    Delete = 6,
    /// Creates a link between two linkable addresses.
    CreateLink = 7,
    /// Deletes an existing `CreateLink` action.
    DeleteLink = 8,
    /// Closes the source chain, optionally pointing at a migration target.
    CloseChain = 9,
    /// Opens a new source chain following a migration from a previous chain.
    OpenChain = 10,
}

/// Maps [`ActionType`] onto the schema `Action.action_type` INTEGER column
/// (`1..=10`). `0` is reserved and never written.
impl From<ActionType> for i64 {
    fn from(t: ActionType) -> Self {
        t as i64
    }
}

/// Inverse of [`From<ActionType> for i64`]. Returns `Err(v)` for any value
/// outside `1..=10` (including `0`).
impl TryFrom<i64> for ActionType {
    type Error = i64;
    fn try_from(v: i64) -> Result<Self, Self::Error> {
        use ActionType::*;
        match v {
            1 => Ok(Dna),
            2 => Ok(AgentValidationPkg),
            3 => Ok(InitZomesComplete),
            4 => Ok(Create),
            5 => Ok(Update),
            6 => Ok(Delete),
            7 => Ok(CreateLink),
            8 => Ok(DeleteLink),
            9 => Ok(CloseChain),
            10 => Ok(OpenChain),
            other => Err(other),
        }
    }
}

impl core::fmt::Display for ActionType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let name = match self {
            ActionType::Dna => "Dna",
            ActionType::AgentValidationPkg => "AgentValidationPkg",
            ActionType::InitZomesComplete => "InitZomesComplete",
            ActionType::Create => "Create",
            ActionType::Update => "Update",
            ActionType::Delete => "Delete",
            ActionType::CreateLink => "CreateLink",
            ActionType::DeleteLink => "DeleteLink",
            ActionType::CloseChain => "CloseChain",
            ActionType::OpenChain => "OpenChain",
        };
        f.write_str(name)
    }
}

/// Capability-grant access type.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[repr(i64)]
pub enum CapAccessType {
    /// No restrictions; any caller may invoke the granted function.
    Unrestricted = 0,
    /// Caller must present a matching secret token.
    Transferable = 1,
    /// Caller must be on the agent allow-list and present the secret.
    Assigned = 2,
}

/// Maps [`CapAccessType`] onto the `CapGrant.cap_access` INTEGER column
/// (`0..=2`). All three variants are valid, including `0`.
impl From<CapAccessType> for i64 {
    fn from(a: CapAccessType) -> Self {
        a as i64
    }
}

/// Inverse of [`From<CapAccess> for i64`]. Returns `Err(v)` for any value
/// outside `0..=2`.
impl TryFrom<i64> for CapAccessType {
    type Error = i64;
    fn try_from(v: i64) -> Result<Self, Self::Error> {
        match v {
            0 => Ok(CapAccessType::Unrestricted),
            1 => Ok(CapAccessType::Transferable),
            2 => Ok(CapAccessType::Assigned),
            other => Err(other),
        }
    }
}

/// Common header fields shared by every action variant.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct ActionHeader {
    /// The agent who authored this action.
    pub author: AgentPubKey,
    /// Microsecond timestamp at which the action was authored.
    pub timestamp: Timestamp,
    /// The action's position on the authoring agent's source chain.
    pub action_seq: u32,
    /// The preceding action's hash on the source chain.
    ///
    /// `None` only for the genesis [`ActionData::Dna`] action.
    pub prev_action: Option<ActionHash>,
}

/// Per-variant data for [`ActionType::Dna`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct DnaData {
    /// Hash of the DNA that this chain is an instance of.
    pub dna_hash: DnaHash,
}

/// Per-variant data for [`ActionType::AgentValidationPkg`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct AgentValidationPkgData {
    /// Optional membrane proof provided when joining the network.
    pub membrane_proof: Option<MembraneProof>,
}

/// Per-variant data for [`ActionType::InitZomesComplete`].
///
/// Carries no payload — the variant alone signals that all init zomes ran.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct InitZomesCompleteData {}

/// Per-variant data for [`ActionType::Create`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct CreateData {
    /// Application-defined entry type (including visibility).
    pub entry_type: EntryType,
    /// Hash of the entry content being created.
    pub entry_hash: EntryHash,
}

/// Per-variant data for [`ActionType::Update`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct UpdateData {
    /// Hash of the action being updated.
    pub original_action_address: ActionHash,
    /// Hash of the original entry being updated.
    pub original_entry_address: EntryHash,
    /// Application-defined entry type of the new entry.
    pub entry_type: EntryType,
    /// Hash of the new entry content.
    pub entry_hash: EntryHash,
}

/// Per-variant data for [`ActionType::Delete`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct DeleteData {
    /// Hash of the action being deleted.
    pub deletes_address: ActionHash,
    /// Hash of the entry referenced by the deleted action.
    pub deletes_entry_address: EntryHash,
}

/// Per-variant data for [`ActionType::CreateLink`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct CreateLinkData {
    /// The hash the link points from.
    pub base_address: AnyLinkableHash,
    /// The hash the link points to.
    pub target_address: AnyLinkableHash,
    /// Index of the zome that defined this link type.
    pub zome_index: ZomeIndex,
    /// Link type identifier within the zome.
    pub link_type: LinkType,
    /// Opaque tag attached to the link.
    pub tag: LinkTag,
}

/// Per-variant data for [`ActionType::DeleteLink`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct DeleteLinkData {
    /// The base address of the link being removed.
    pub base_address: AnyLinkableHash,
    /// Hash of the `CreateLink` action being deleted.
    pub link_add_address: ActionHash,
}

/// Per-variant data for [`ActionType::CloseChain`].
///
/// The `author`, `timestamp`, `action_seq`, and `prev_action` fields live on
/// [`ActionHeader`]; only the chain-close-specific fields go here.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct CloseChainData {
    /// Optional migration target the chain closes towards.
    pub new_target: Option<crate::action::MigrationTarget>,
}

/// Per-variant data for [`ActionType::OpenChain`].
///
/// The `author`, `timestamp`, `action_seq`, and `prev_action` fields live on
/// [`ActionHeader`]; only the chain-open-specific fields go here.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct OpenChainData {
    /// The previous DNA hash or agent key this chain migrated from.
    pub prev_target: crate::action::MigrationTarget,
    /// Hash of the matching `CloseChain` action on the old chain.
    pub close_hash: ActionHash,
}

/// Per-variant action data, stored serialized in the `Action.action_data`
/// BLOB column.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
#[serde(tag = "type")]
pub enum ActionData {
    /// Genesis DNA action.
    Dna(DnaData),
    /// Agent validation package.
    AgentValidationPkg(AgentValidationPkgData),
    /// Signals that init zomes have completed.
    InitZomesComplete(InitZomesCompleteData),
    /// Creates a new entry.
    Create(CreateData),
    /// Updates an existing entry.
    Update(UpdateData),
    /// Deletes an existing entry.
    Delete(DeleteData),
    /// Creates a link between two addresses.
    CreateLink(CreateLinkData),
    /// Deletes a previously created link.
    DeleteLink(DeleteLinkData),
    /// Closes the source chain.
    CloseChain(CloseChainData),
    /// Opens a new chain following a migration.
    OpenChain(OpenChainData),
}

impl ActionData {
    /// The [`ActionType`] discriminant of this variant.
    pub fn action_type(&self) -> ActionType {
        match self {
            ActionData::Dna(_) => ActionType::Dna,
            ActionData::AgentValidationPkg(_) => ActionType::AgentValidationPkg,
            ActionData::InitZomesComplete(_) => ActionType::InitZomesComplete,
            ActionData::Create(_) => ActionType::Create,
            ActionData::Update(_) => ActionType::Update,
            ActionData::Delete(_) => ActionType::Delete,
            ActionData::CreateLink(_) => ActionType::CreateLink,
            ActionData::DeleteLink(_) => ActionType::DeleteLink,
            ActionData::CloseChain(_) => ActionType::CloseChain,
            ActionData::OpenChain(_) => ActionType::OpenChain,
        }
    }

    /// The action's referenced entry hash, if any.
    pub fn entry_hash(&self) -> Option<&EntryHash> {
        match self {
            ActionData::Create(d) => Some(&d.entry_hash),
            ActionData::Update(d) => Some(&d.entry_hash),
            _ => None,
        }
    }
}

/// Full action content: header + per-variant data.
///
/// The hash is not stored on the struct — use [`holo_hash::HoloHashed<Action>`]
/// (or [`crate::record::SignedHashed<Action>`]) at call sites so the hash is
/// always derived from the content.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, SerializedBytes)]
pub struct Action {
    /// Header fields common to every action variant.
    pub header: ActionHeader,
    /// The per-variant payload.
    pub data: ActionData,
}

impl Action {
    /// The public key of the agent who "authored" this action.
    ///
    /// This is not necessarily the agent who signed the action; see
    /// [`Action::signer`].
    pub fn author(&self) -> &AgentPubKey {
        &self.header.author
    }

    /// The public key of the agent who signed this action.
    ///
    /// This is not necessarily the agent who "authored" the action: a
    /// `CloseChain` action during an agent-key migration is signed with the
    /// new key rather than the author key, because the new key must be
    /// known in order for the migration to be effective.
    pub fn signer(&self) -> &AgentPubKey {
        match &self.data {
            ActionData::CloseChain(CloseChainData {
                new_target: Some(crate::action::MigrationTarget::Agent(agent)),
            }) => agent,
            _ => self.author(),
        }
    }

    /// The microsecond timestamp at which this action was authored.
    pub fn timestamp(&self) -> Timestamp {
        self.header.timestamp
    }

    /// This action's position on the authoring agent's source chain.
    pub fn action_seq(&self) -> u32 {
        self.header.action_seq
    }

    /// The hash of the preceding action on the source chain.
    ///
    /// `None` only for the genesis `Dna` action.
    pub fn prev_action(&self) -> Option<&ActionHash> {
        self.header.prev_action.as_ref()
    }

    /// A mutable reference to the preceding action hash.
    ///
    /// `None` only for the genesis `Dna` action.
    pub fn prev_action_mut(&mut self) -> Option<&mut ActionHash> {
        self.header.prev_action.as_mut()
    }

    /// `true` if this action's sequence number falls within the genesis
    /// portion of the chain.
    pub fn is_genesis(&self) -> bool {
        self.action_seq() < crate::action::POST_GENESIS_SEQ_THRESHOLD
    }

    /// The [`ActionType`] discriminant of this action.
    pub fn action_type(&self) -> ActionType {
        self.data.action_type()
    }

    /// The hash of the entry this action references, if any.
    pub fn entry_hash(&self) -> Option<&EntryHash> {
        self.data.entry_hash()
    }

    /// The type of the entry this action references, if any.
    pub fn entry_type(&self) -> Option<&EntryType> {
        match &self.data {
            ActionData::Create(d) => Some(&d.entry_type),
            ActionData::Update(d) => Some(&d.entry_type),
            _ => None,
        }
    }

    /// A mutable reference to the type of the entry this action references,
    /// for the `Create` and `Update` variants.
    pub fn entry_type_mut(&mut self) -> Option<&mut EntryType> {
        match &mut self.data {
            ActionData::Create(d) => Some(&mut d.entry_type),
            ActionData::Update(d) => Some(&mut d.entry_type),
            _ => None,
        }
    }

    /// A mutable reference to the hash of the entry this action references,
    /// for the `Create` and `Update` variants.
    pub fn entry_hash_mut(&mut self) -> Option<&mut EntryHash> {
        match &mut self.data {
            ActionData::Create(d) => Some(&mut d.entry_hash),
            ActionData::Update(d) => Some(&mut d.entry_hash),
            _ => None,
        }
    }

    /// The [`AppEntryDef`] of the entry this action references, if it is an
    /// application-defined entry.
    pub fn app_entry_def(&self) -> Option<&AppEntryDef> {
        match self.entry_type()? {
            EntryType::App(app_entry_def) => Some(app_entry_def),
            _ => None,
        }
    }

    /// The hash and type of the entry this action references, if any.
    pub fn entry_data(&self) -> Option<(&EntryHash, &EntryType)> {
        match &self.data {
            ActionData::Create(d) => Some((&d.entry_hash, &d.entry_type)),
            ActionData::Update(d) => Some((&d.entry_hash, &d.entry_type)),
            _ => None,
        }
    }

    /// Pulls the entry hash and type out of this action by value, if any.
    pub fn into_entry_data(self) -> Option<(EntryHash, EntryType)> {
        match self.data {
            ActionData::Create(d) => Some((d.entry_hash, d.entry_type)),
            ActionData::Update(d) => Some((d.entry_hash, d.entry_type)),
            _ => None,
        }
    }

    /// The visibility of the entry this action references, if any.
    pub fn entry_visibility(&self) -> Option<&EntryVisibility> {
        self.entry_type().map(|entry_type| entry_type.visibility())
    }
}

impl HashableContent for Action {
    type HashType = holo_hash::hash_type::Action;

    fn hash_type(&self) -> Self::HashType {
        use holo_hash::PrimitiveHashType;
        Self::HashType::new()
    }

    fn hashable_content(&self) -> HashableContentBytes {
        HashableContentBytes::Content(
            SerializedBytes::try_from(self).expect("Could not serialize Action"),
        )
    }
}

/// An [`Action`] paired with its [`ActionHash`].
///
/// The agent-activity traits
/// [`ActionSequenceAndHash`] and
/// [`ActionHashedContainer`] are
/// implemented for it.
pub type ActionHashed = HoloHashed<Action>;

/// An [`Action`] that is both hashed and signed.
pub type SignedActionHashed = crate::record::SignedHashed<Action>;

impl SignedActionHashed {
    /// The action content.
    pub fn action(&self) -> &Action {
        &self.hashed.content
    }

    /// The action hash.
    pub fn action_address(&self) -> &ActionHash {
        &self.hashed.hash
    }
}

impl crate::action::ActionSequenceAndHash for ActionHashed {
    fn action_seq(&self) -> u32 {
        self.content.action_seq()
    }

    fn address(&self) -> &ActionHash {
        &self.hash
    }
}

impl crate::action::ActionHashedContainer for ActionHashed {
    fn action(&self) -> &Action {
        &self.content
    }

    fn action_hash(&self) -> &ActionHash {
        &self.hash
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn record_validity_i64_roundtrip() {
        for v in [RecordValidity::Accepted, RecordValidity::Rejected] {
            let n: i64 = v.into();
            assert_eq!(RecordValidity::try_from(n).unwrap(), v);
        }
        assert!(RecordValidity::try_from(0).is_err());
        assert!(RecordValidity::try_from(3).is_err());
    }

    #[test]
    fn action_type_i64_roundtrip() {
        use ActionType::*;
        for v in [
            Dna,
            AgentValidationPkg,
            InitZomesComplete,
            Create,
            Update,
            Delete,
            CreateLink,
            DeleteLink,
            CloseChain,
            OpenChain,
        ] {
            let n: i64 = v.into();
            assert_eq!(ActionType::try_from(n).unwrap(), v);
        }
        assert!(ActionType::try_from(0).is_err());
        assert!(ActionType::try_from(11).is_err());
    }

    #[test]
    fn cap_access_i64_roundtrip() {
        for v in [
            CapAccessType::Unrestricted,
            CapAccessType::Transferable,
            CapAccessType::Assigned,
        ] {
            let n: i64 = v.into();
            assert_eq!(CapAccessType::try_from(n).unwrap(), v);
        }
        assert!(CapAccessType::try_from(-1).is_err());
        assert!(CapAccessType::try_from(3).is_err());
    }

    #[test]
    fn data_structs_construct() {
        // Sanity check that each struct has the expected shape by constructing one.
        let _ = DnaData {
            dna_hash: DnaHash::from_raw_36(vec![0u8; 36]),
        };
        let _ = InitZomesCompleteData {};
    }

    #[test]
    fn action_data_serde_roundtrip() {
        let cases: Vec<ActionData> = vec![
            ActionData::Dna(DnaData {
                dna_hash: DnaHash::from_raw_36(vec![1u8; 36]),
            }),
            ActionData::InitZomesComplete(InitZomesCompleteData {}),
            ActionData::Create(CreateData {
                entry_type: EntryType::AgentPubKey,
                entry_hash: EntryHash::from_raw_36(vec![2u8; 36]),
            }),
        ];
        for data in cases {
            let bytes = holochain_serialized_bytes::encode(&data).unwrap();
            let decoded: ActionData = holochain_serialized_bytes::decode(&bytes).unwrap();
            assert_eq!(decoded.action_type(), data.action_type());
        }
    }

    fn sample_action(data: ActionData) -> Action {
        Action {
            header: ActionHeader {
                author: AgentPubKey::from_raw_36(vec![1u8; 36]),
                timestamp: Timestamp::from_micros(42),
                action_seq: 5,
                prev_action: Some(ActionHash::from_raw_36(vec![2u8; 36])),
            },
            data,
        }
    }

    fn sample_create_data() -> ActionData {
        ActionData::Create(CreateData {
            entry_type: EntryType::AgentPubKey,
            entry_hash: EntryHash::from_raw_36(vec![3u8; 36]),
        })
    }

    #[test]
    fn action_accessors_read_header_fields() {
        let a = sample_action(sample_create_data());
        assert_eq!(a.author(), &AgentPubKey::from_raw_36(vec![1u8; 36]));
        assert_eq!(a.timestamp(), Timestamp::from_micros(42));
        assert_eq!(a.action_seq(), 5);
        assert_eq!(
            a.prev_action(),
            Some(&ActionHash::from_raw_36(vec![2u8; 36]))
        );
        assert_eq!(a.action_type(), ActionType::Create);
    }

    #[test]
    fn action_prev_action_mut_writes_through_the_header() {
        let mut a = sample_action(sample_create_data());
        let new_prev = ActionHash::from_raw_36(vec![9u8; 36]);
        *a.prev_action_mut().expect("has a prev action") = new_prev.clone();
        assert_eq!(a.prev_action(), Some(&new_prev));
    }

    #[test]
    fn action_entry_type_and_data_some_for_create_and_update() {
        let create = sample_action(sample_create_data());
        assert_eq!(create.entry_type(), Some(&EntryType::AgentPubKey));
        assert_eq!(
            create.entry_data(),
            Some((
                &EntryHash::from_raw_36(vec![3u8; 36]),
                &EntryType::AgentPubKey
            ))
        );
        assert_eq!(
            create.entry_hash(),
            Some(&EntryHash::from_raw_36(vec![3u8; 36]))
        );

        let update = sample_action(ActionData::Update(UpdateData {
            original_action_address: ActionHash::from_raw_36(vec![6u8; 36]),
            original_entry_address: EntryHash::from_raw_36(vec![7u8; 36]),
            entry_type: EntryType::CapClaim,
            entry_hash: EntryHash::from_raw_36(vec![8u8; 36]),
        }));
        assert_eq!(update.entry_type(), Some(&EntryType::CapClaim));
        assert_eq!(
            update.entry_data(),
            Some((&EntryHash::from_raw_36(vec![8u8; 36]), &EntryType::CapClaim))
        );
    }

    #[test]
    fn action_entry_type_and_data_none_for_non_entry_actions() {
        let dna = sample_action(ActionData::Dna(DnaData {
            dna_hash: DnaHash::from_raw_36(vec![5u8; 36]),
        }));
        assert_eq!(dna.entry_type(), None);
        assert_eq!(dna.entry_data(), None);
        assert_eq!(dna.entry_hash(), None);
        assert_eq!(dna.entry_visibility(), None);

        let delete = sample_action(ActionData::Delete(DeleteData {
            deletes_address: ActionHash::from_raw_36(vec![9u8; 36]),
            deletes_entry_address: EntryHash::from_raw_36(vec![10u8; 36]),
        }));
        assert!(delete.entry_data().is_none());
    }

    #[test]
    fn action_app_entry_def_some_for_app_entry_type() {
        let app_entry_def = AppEntryDef::new(
            crate::action::EntryDefIndex(1),
            crate::action::ZomeIndex(2),
            EntryVisibility::Public,
        );
        let create = sample_action(ActionData::Create(CreateData {
            entry_type: EntryType::App(app_entry_def.clone()),
            entry_hash: EntryHash::from_raw_36(vec![3u8; 36]),
        }));
        assert_eq!(create.app_entry_def(), Some(&app_entry_def));
    }

    #[test]
    fn action_app_entry_def_none_for_non_app_entry_type() {
        let create = sample_action(sample_create_data());
        assert_eq!(create.app_entry_def(), None);

        let dna = sample_action(ActionData::Dna(DnaData {
            dna_hash: DnaHash::from_raw_36(vec![5u8; 36]),
        }));
        assert_eq!(dna.app_entry_def(), None);
    }

    #[test]
    fn action_into_entry_data_moves_the_fields_out() {
        let create = sample_action(sample_create_data());
        let (hash, ty) = create.into_entry_data().expect("create has entry data");
        assert_eq!(hash, EntryHash::from_raw_36(vec![3u8; 36]));
        assert_eq!(ty, EntryType::AgentPubKey);

        let dna = sample_action(ActionData::Dna(DnaData {
            dna_hash: DnaHash::from_raw_36(vec![5u8; 36]),
        }));
        assert!(dna.into_entry_data().is_none());
    }

    #[test]
    fn action_entry_visibility_reads_through_entry_type() {
        let create = sample_action(sample_create_data());
        assert_eq!(create.entry_visibility(), Some(&EntryVisibility::Public));

        let cap_claim = sample_action(ActionData::Create(CreateData {
            entry_type: EntryType::CapClaim,
            entry_hash: EntryHash::from_raw_36(vec![3u8; 36]),
        }));
        assert_eq!(
            cap_claim.entry_visibility(),
            Some(&EntryVisibility::Private)
        );
    }

    #[test]
    fn action_is_genesis_below_threshold() {
        let mut a = sample_action(sample_create_data());
        a.header.action_seq = 0;
        assert!(a.is_genesis());
        a.header.action_seq = crate::action::POST_GENESIS_SEQ_THRESHOLD;
        assert!(!a.is_genesis());
    }

    #[test]
    fn action_signer_defaults_to_author() {
        let a = sample_action(sample_create_data());
        assert_eq!(a.signer(), a.author());
    }

    #[test]
    fn action_signer_uses_the_migration_agent_for_close_chain() {
        let new_agent = AgentPubKey::from_raw_36(vec![7u8; 36]);
        let a = sample_action(ActionData::CloseChain(CloseChainData {
            new_target: Some(crate::action::MigrationTarget::Agent(new_agent.clone())),
        }));
        assert_eq!(a.signer(), &new_agent);
        assert_ne!(a.signer(), a.author());
    }

    #[test]
    fn action_signer_uses_author_for_close_chain_without_agent_target() {
        let a = sample_action(ActionData::CloseChain(CloseChainData { new_target: None }));
        assert_eq!(a.signer(), a.author());
    }
}