trust-tasks-rs 0.21.3

Reference Rust library for the Trust Tasks framework — transport-agnostic, JSON-based descriptions of verifiable work between parties.
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
//! Generated by `trust-tasks-codegen` — do not edit by hand.
//!
//! Spec slug: `vta/backup/put-chunk`. Version: `1.0`.
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
/// Error types.
pub mod error {
    /// Error from a `TryFrom` or `FromStr` implementation.
    pub struct ConversionError(::std::borrow::Cow<'static, str>);
    impl ::std::error::Error for ConversionError {}
    impl ::std::fmt::Display for ConversionError {
        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
            ::std::fmt::Display::fmt(&self.0, f)
        }
    }
    impl ::std::fmt::Debug for ConversionError {
        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
            ::std::fmt::Debug::fmt(&self.0, f)
        }
    }
    impl From<&'static str> for ConversionError {
        fn from(value: &'static str) -> Self {
            Self(value.into())
        }
    }
    impl From<String> for ConversionError {
        fn from(value: String) -> Self {
            Self(value.into())
        }
    }
}
///Handle for a bundle across its whole lifecycle. Recipient-generated and unguessable, which is what lets an unauthorized reference be answered as not-found without confirming existence. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "BundleId",
///  "description": "Handle for a bundle across its whole lifecycle. Recipient-generated and unguessable, which is what lets an unauthorized reference be answered as not-found without confirming existence. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.",
///  "type": "string",
///  "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct BundleId(::std::string::String);
impl ::std::ops::Deref for BundleId {
    type Target = ::std::string::String;
    fn deref(&self) -> &::std::string::String {
        &self.0
    }
}
impl ::std::convert::From<BundleId> for ::std::string::String {
    fn from(value: BundleId) -> Self {
        value.0
    }
}
impl ::std::str::FromStr for BundleId {
    type Err = self::error::ConversionError;
    fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        static PATTERN: ::std::sync::LazyLock<::regress::Regex> =
            ::std::sync::LazyLock::new(|| {
                ::regress::Regex::new(
                    "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
                )
                .unwrap()
            });
        if PATTERN.find(value).is_none() {
            return Err(
                "doesn't match pattern \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\""
                    .into(),
            );
        }
        Ok(Self(value.to_string()))
    }
}
impl ::std::convert::TryFrom<&str> for BundleId {
    type Error = self::error::ConversionError;
    fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<&::std::string::String> for BundleId {
    type Error = self::error::ConversionError;
    fn try_from(
        value: &::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<::std::string::String> for BundleId {
    type Error = self::error::ConversionError;
    fn try_from(
        value: ::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl<'de> ::serde::Deserialize<'de> for BundleId {
    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        ::std::string::String::deserialize(deserializer)?
            .parse()
            .map_err(|e: self::error::ConversionError| {
                <D::Error as ::serde::de::Error>::custom(e.to_string())
            })
    }
}
///The chunk's bytes, base64url-encoded without padding (RFC 4648 §5). Bounded at 349526 characters, the unpadded encoding of a 262144-byte chunk. These are bytes of the encrypted bundle, so a chunk read in isolation reveals nothing of the agent's state — but a complete set of chunks is the export, and is to be handled as such.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "ChunkData",
///  "description": "The chunk's bytes, base64url-encoded without padding (RFC 4648 §5). Bounded at 349526 characters, the unpadded encoding of a 262144-byte chunk. These are bytes of the encrypted bundle, so a chunk read in isolation reveals nothing of the agent's state — but a complete set of chunks is the export, and is to be handled as such.",
///  "type": "string",
///  "maxLength": 349526,
///  "minLength": 2,
///  "pattern": "^[A-Za-z0-9_-]+$"
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct ChunkData(::std::string::String);
impl ::std::ops::Deref for ChunkData {
    type Target = ::std::string::String;
    fn deref(&self) -> &::std::string::String {
        &self.0
    }
}
impl ::std::convert::From<ChunkData> for ::std::string::String {
    fn from(value: ChunkData) -> Self {
        value.0
    }
}
impl ::std::str::FromStr for ChunkData {
    type Err = self::error::ConversionError;
    fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        if value.chars().count() > 349526usize {
            return Err("longer than 349526 characters".into());
        }
        if value.chars().count() < 2usize {
            return Err("shorter than 2 characters".into());
        }
        static PATTERN: ::std::sync::LazyLock<::regress::Regex> =
            ::std::sync::LazyLock::new(|| ::regress::Regex::new("^[A-Za-z0-9_-]+$").unwrap());
        if PATTERN.find(value).is_none() {
            return Err("doesn't match pattern \"^[A-Za-z0-9_-]+$\"".into());
        }
        Ok(Self(value.to_string()))
    }
}
impl ::std::convert::TryFrom<&str> for ChunkData {
    type Error = self::error::ConversionError;
    fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<&::std::string::String> for ChunkData {
    type Error = self::error::ConversionError;
    fn try_from(
        value: &::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<::std::string::String> for ChunkData {
    type Error = self::error::ConversionError;
    fn try_from(
        value: ::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl<'de> ::serde::Deserialize<'de> for ChunkData {
    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        ::std::string::String::deserialize(deserializer)?
            .parse()
            .map_err(|e: self::error::ConversionError| {
                <D::Error as ::serde::de::Error>::custom(e.to_string())
            })
    }
}
///Zero-based position of a chunk within its bundle. Valid values are 0 to chunkCount − 1; an index outside that range is refused with chunkOutOfRange rather than validated here, because the bound depends on the bundle.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "ChunkIndex",
///  "description": "Zero-based position of a chunk within its bundle. Valid values are 0 to chunkCount − 1; an index outside that range is refused with chunkOutOfRange rather than validated here, because the bound depends on the bundle.",
///  "type": "integer",
///  "maximum": 4095.0,
///  "minimum": 0.0
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct ChunkIndex(pub i64);
impl ::std::ops::Deref for ChunkIndex {
    type Target = i64;
    fn deref(&self) -> &i64 {
        &self.0
    }
}
impl ::std::convert::From<ChunkIndex> for i64 {
    fn from(value: ChunkIndex) -> Self {
        value.0
    }
}
impl ::std::convert::From<i64> for ChunkIndex {
    fn from(value: i64) -> Self {
        Self(value)
    }
}
impl ::std::str::FromStr for ChunkIndex {
    type Err = <i64 as ::std::str::FromStr>::Err;
    fn from_str(value: &str) -> ::std::result::Result<Self, Self::Err> {
        Ok(Self(value.parse()?))
    }
}
impl ::std::convert::TryFrom<&str> for ChunkIndex {
    type Error = <i64 as ::std::str::FromStr>::Err;
    fn try_from(value: &str) -> ::std::result::Result<Self, Self::Error> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<String> for ChunkIndex {
    type Error = <i64 as ::std::str::FromStr>::Err;
    fn try_from(value: String) -> ::std::result::Result<Self, Self::Error> {
        value.parse()
    }
}
impl ::std::fmt::Display for ChunkIndex {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        self.0.fmt(f)
    }
}
/**
A cryptographic digest as a multibase-encoded multihash — the encoding the W3C Verifiable Credentials Data Model 2.0 defines for `digestMultibase`, and the one `did:webvh` uses for its SCID and entry hashes.

Multihash carries the hash algorithm in-band, so the value is self-describing and the wire format survives an algorithm change without a schema revision; multibase does the same for the base encoding, so a verifier never infers base58 from base64url by context. A bare hex string or a `sha-256:`-style prefix hard-codes one algorithm into the wire contract and is non-conforming here.

This definition constrains the *encoding only*. What the digest is computed over is stated by each referencing field, because it differs legitimately: a digest over a JSON document is taken over its RFC 8785 (JCS) canonicalization, while a digest over an opaque artifact is taken over its bytes. A field whose input is a JSON document and which does not name a canonicalization is not reproducible.

Restricted to the two multibase headers W3C Controlled Identifiers 1.0 §2.4 normatively requires — `z` (base58btc) and `u` (base64url-no-pad). CID permits others but states that "interoperability is not guaranteed between implementations using such values", and a registry whose purpose is interoperability should not mint digests a conforming verifier may be unable to read. The alphabets are enforced rather than assumed: base58btc excludes 0, O, I and l, and an earlier permissive pattern let three published examples carry digests that were not valid base58 at all. base58btc is RECOMMENDED, for consistency with `did:key` and `did:webvh`.*/
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "DigestMultibase",
///  "description": "\nA cryptographic digest as a multibase-encoded multihash — the encoding the W3C Verifiable Credentials Data Model 2.0 defines for `digestMultibase`, and the one `did:webvh` uses for its SCID and entry hashes.\n\nMultihash carries the hash algorithm in-band, so the value is self-describing and the wire format survives an algorithm change without a schema revision; multibase does the same for the base encoding, so a verifier never infers base58 from base64url by context. A bare hex string or a `sha-256:`-style prefix hard-codes one algorithm into the wire contract and is non-conforming here.\n\nThis definition constrains the *encoding only*. What the digest is computed over is stated by each referencing field, because it differs legitimately: a digest over a JSON document is taken over its RFC 8785 (JCS) canonicalization, while a digest over an opaque artifact is taken over its bytes. A field whose input is a JSON document and which does not name a canonicalization is not reproducible.\n\nRestricted to the two multibase headers W3C Controlled Identifiers 1.0 §2.4 normatively requires — `z` (base58btc) and `u` (base64url-no-pad). CID permits others but states that \"interoperability is not guaranteed between implementations using such values\", and a registry whose purpose is interoperability should not mint digests a conforming verifier may be unable to read. The alphabets are enforced rather than assumed: base58btc excludes 0, O, I and l, and an earlier permissive pattern let three published examples carry digests that were not valid base58 at all. base58btc is RECOMMENDED, for consistency with `did:key` and `did:webvh`.",
///  "examples": [
///    "zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"
///  ],
///  "type": "string",
///  "minLength": 16,
///  "pattern": "^(z[1-9A-HJ-NP-Za-km-z]+|u[A-Za-z0-9_-]+)$"
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct DigestMultibase(::std::string::String);
impl ::std::ops::Deref for DigestMultibase {
    type Target = ::std::string::String;
    fn deref(&self) -> &::std::string::String {
        &self.0
    }
}
impl ::std::convert::From<DigestMultibase> for ::std::string::String {
    fn from(value: DigestMultibase) -> Self {
        value.0
    }
}
impl ::std::str::FromStr for DigestMultibase {
    type Err = self::error::ConversionError;
    fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        if value.chars().count() < 16usize {
            return Err("shorter than 16 characters".into());
        }
        static PATTERN: ::std::sync::LazyLock<::regress::Regex> =
            ::std::sync::LazyLock::new(|| {
                ::regress::Regex::new("^(z[1-9A-HJ-NP-Za-km-z]+|u[A-Za-z0-9_-]+)$").unwrap()
            });
        if PATTERN.find(value).is_none() {
            return Err(
                "doesn't match pattern \"^(z[1-9A-HJ-NP-Za-km-z]+|u[A-Za-z0-9_-]+)$\"".into(),
            );
        }
        Ok(Self(value.to_string()))
    }
}
impl ::std::convert::TryFrom<&str> for DigestMultibase {
    type Error = self::error::ConversionError;
    fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<&::std::string::String> for DigestMultibase {
    type Error = self::error::ConversionError;
    fn try_from(
        value: &::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<::std::string::String> for DigestMultibase {
    type Error = self::error::ConversionError;
    fn try_from(
        value: ::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl<'de> ::serde::Deserialize<'de> for DigestMultibase {
    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        ::std::string::String::deserialize(deserializer)?
            .parse()
            .map_err(|e: self::error::ConversionError| {
                <D::Error as ::serde::de::Error>::custom(e.to_string())
            })
    }
}
///After which the bundle is collected: staged bytes discarded, tokens and chunk requests refused. Short by design. For a chunked transfer a recipient may move it later as chunks are exchanged, never past its own ceiling — each chunk response reports the current value.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "ExpiresAt",
///  "description": "After which the bundle is collected: staged bytes discarded, tokens and chunk requests refused. Short by design. For a chunked transfer a recipient may move it later as chunks are exchanged, never past its own ceiling — each chunk response reports the current value.",
///  "type": "string",
///  "format": "date-time"
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct ExpiresAt(pub ::chrono::DateTime<::chrono::offset::Utc>);
impl ::std::ops::Deref for ExpiresAt {
    type Target = ::chrono::DateTime<::chrono::offset::Utc>;
    fn deref(&self) -> &::chrono::DateTime<::chrono::offset::Utc> {
        &self.0
    }
}
impl ::std::convert::From<ExpiresAt> for ::chrono::DateTime<::chrono::offset::Utc> {
    fn from(value: ExpiresAt) -> Self {
        value.0
    }
}
impl ::std::convert::From<::chrono::DateTime<::chrono::offset::Utc>> for ExpiresAt {
    fn from(value: ::chrono::DateTime<::chrono::offset::Utc>) -> Self {
        Self(value)
    }
}
impl ::std::str::FromStr for ExpiresAt {
    type Err = <::chrono::DateTime<::chrono::offset::Utc> as ::std::str::FromStr>::Err;
    fn from_str(value: &str) -> ::std::result::Result<Self, Self::Err> {
        Ok(Self(value.parse()?))
    }
}
impl ::std::convert::TryFrom<&str> for ExpiresAt {
    type Error = <::chrono::DateTime<::chrono::offset::Utc> as ::std::str::FromStr>::Err;
    fn try_from(value: &str) -> ::std::result::Result<Self, Self::Error> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<String> for ExpiresAt {
    type Error = <::chrono::DateTime<::chrono::offset::Utc> as ::std::str::FromStr>::Err;
    fn try_from(value: String) -> ::std::result::Result<Self, Self::Error> {
        value.parse()
    }
}
impl ::std::fmt::Display for ExpiresAt {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        self.0.fmt(f)
    }
}
///Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "Ext",
///  "description": "Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.",
///  "type": "object",
///  "minProperties": 1,
///  "additionalProperties": true,
///  "propertyNames": {
///    "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"
///  }
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct Ext(pub ::std::collections::HashMap<ExtKey, ::serde_json::Value>);
impl ::std::ops::Deref for Ext {
    type Target = ::std::collections::HashMap<ExtKey, ::serde_json::Value>;
    fn deref(&self) -> &::std::collections::HashMap<ExtKey, ::serde_json::Value> {
        &self.0
    }
}
impl ::std::convert::From<Ext> for ::std::collections::HashMap<ExtKey, ::serde_json::Value> {
    fn from(value: Ext) -> Self {
        value.0
    }
}
impl ::std::convert::From<::std::collections::HashMap<ExtKey, ::serde_json::Value>> for Ext {
    fn from(value: ::std::collections::HashMap<ExtKey, ::serde_json::Value>) -> Self {
        Self(value)
    }
}
///`ExtKey`
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "type": "string",
///  "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct ExtKey(::std::string::String);
impl ::std::ops::Deref for ExtKey {
    type Target = ::std::string::String;
    fn deref(&self) -> &::std::string::String {
        &self.0
    }
}
impl ::std::convert::From<ExtKey> for ::std::string::String {
    fn from(value: ExtKey) -> Self {
        value.0
    }
}
impl ::std::str::FromStr for ExtKey {
    type Err = self::error::ConversionError;
    fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        static PATTERN: ::std::sync::LazyLock<::regress::Regex> =
            ::std::sync::LazyLock::new(|| {
                ::regress::Regex::new("^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$").unwrap()
            });
        if PATTERN.find(value).is_none() {
            return Err("doesn't match pattern \"^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$\"".into());
        }
        Ok(Self(value.to_string()))
    }
}
impl ::std::convert::TryFrom<&str> for ExtKey {
    type Error = self::error::ConversionError;
    fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<&::std::string::String> for ExtKey {
    type Error = self::error::ConversionError;
    fn try_from(
        value: &::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl ::std::convert::TryFrom<::std::string::String> for ExtKey {
    type Error = self::error::ConversionError;
    fn try_from(
        value: ::std::string::String,
    ) -> ::std::result::Result<Self, self::error::ConversionError> {
        value.parse()
    }
}
impl<'de> ::serde::Deserialize<'de> for ExtKey {
    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        ::std::string::String::deserialize(deserializer)?
            .parse()
            .map_err(|e: self::error::ConversionError| {
                <D::Error as ::serde::de::Error>::custom(e.to_string())
            })
    }
}
///Writes one chunk of a `chunkedTrustTask` import bundle, by index, into a slot opened by initiate-import. Idempotent for identical bytes; bytes that do not match the pre-committed manifest are refused. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "$id": "https://trusttasks.org/spec/vta/backup/put-chunk/1.0",
///  "title": "Payload",
///  "description": "Writes one chunk of a `chunkedTrustTask` import bundle, by index, into a slot opened by initiate-import. Idempotent for identical bytes; bytes that do not match the pre-committed manifest are refused. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.",
///  "type": "object",
///  "required": [
///    "bundleId",
///    "data",
///    "digestMultibase",
///    "index"
///  ],
///  "properties": {
///    "bundleId": {
///      "description": "Handle from the initiate-import descriptor. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.",
///      "$ref": "#/definitions/BundleId"
///    },
///    "data": {
///      "$ref": "#/definitions/ChunkData"
///    },
///    "digestMultibase": {
///      "description": "Digest of this chunk's raw bytes, restating the manifest entry for `index`. Restated so that a chunk sent to the wrong index is refused as a mismatch against the manifest at the index it names, rather than surviving until reassembly — the recipient checks this member against the manifest and `data` against both.",
///      "$ref": "#/definitions/DigestMultibase"
///    },
///    "ext": {
///      "description": "Ecosystem-defined extension members per SPEC.md §4.5.1.",
///      "$ref": "#/definitions/Ext"
///    },
///    "index": {
///      "description": "Which chunk. Zero-based, below the manifest's chunkCount.",
///      "$ref": "#/definitions/ChunkIndex"
///    }
///  },
///  "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Payload {
    ///Handle from the initiate-import descriptor. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.
    #[serde(rename = "bundleId")]
    pub bundle_id: BundleId,
    pub data: ChunkData,
    ///Digest of this chunk's raw bytes, restating the manifest entry for `index`. Restated so that a chunk sent to the wrong index is refused as a mismatch against the manifest at the index it names, rather than surviving until reassembly — the recipient checks this member against the manifest and `data` against both.
    #[serde(rename = "digestMultibase")]
    pub digest_multibase: DigestMultibase,
    ///Ecosystem-defined extension members per SPEC.md §4.5.1.
    #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
    pub ext: ::std::option::Option<Ext>,
    ///Which chunk. Zero-based, below the manifest's chunkCount.
    pub index: ChunkIndex,
}
impl Payload {
    pub fn builder() -> builder::Payload {
        Default::default()
    }
}
///`Response`
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
///  "title": "Response",
///  "type": "object",
///  "required": [
///    "bundleId",
///    "expiresAt",
///    "index",
///    "remainingCount",
///    "stored"
///  ],
///  "properties": {
///    "bundleId": {
///      "description": "Echoed so the response stands alone as the acknowledgement of one write.",
///      "$ref": "#/definitions/BundleId"
///    },
///    "expiresAt": {
///      "description": "The slot's current expiry, after any extension this write earned.",
///      "$ref": "#/definitions/ExpiresAt"
///    },
///    "ext": {
///      "description": "Ecosystem-defined extension members per SPEC.md §4.5.1.",
///      "$ref": "#/definitions/Ext"
///    },
///    "index": {
///      "description": "Echoed, so an acknowledgement arriving out of order is attributable to its write.",
///      "$ref": "#/definitions/ChunkIndex"
///    },
///    "remainingCount": {
///      "description": "How many indices the slot still lacks after this write. Zero means the upload is complete and finalize-import can be sent.",
///      "type": "integer",
///      "maximum": 4095.0,
///      "minimum": 0.0
///    },
///    "stored": {
///      "description": "Whether this request is what stored the chunk. False means the recipient already held identical bytes at this index — a success, not a failure, and the reason a write can be retried safely. Required rather than optional: an absent member on an idempotent repeat would be indistinguishable from a first write.",
///      "type": "boolean"
///    }
///  },
///  "additionalProperties": false,
///  "$anchor": "response"
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Response {
    ///Echoed so the response stands alone as the acknowledgement of one write.
    #[serde(rename = "bundleId")]
    pub bundle_id: BundleId,
    ///The slot's current expiry, after any extension this write earned.
    #[serde(rename = "expiresAt")]
    pub expires_at: ExpiresAt,
    ///Ecosystem-defined extension members per SPEC.md §4.5.1.
    #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
    pub ext: ::std::option::Option<Ext>,
    ///Echoed, so an acknowledgement arriving out of order is attributable to its write.
    pub index: ChunkIndex,
    ///How many indices the slot still lacks after this write. Zero means the upload is complete and finalize-import can be sent.
    #[serde(rename = "remainingCount")]
    pub remaining_count: i64,
    ///Whether this request is what stored the chunk. False means the recipient already held identical bytes at this index — a success, not a failure, and the reason a write can be retried safely. Required rather than optional: an absent member on an idempotent repeat would be indistinguishable from a first write.
    pub stored: bool,
}
impl Response {
    pub fn builder() -> builder::Response {
        Default::default()
    }
}
/// Types for composing complex structures.
pub mod builder {
    #[derive(Clone, Debug)]
    pub struct Payload {
        bundle_id: ::std::result::Result<super::BundleId, ::std::string::String>,
        data: ::std::result::Result<super::ChunkData, ::std::string::String>,
        digest_multibase: ::std::result::Result<super::DigestMultibase, ::std::string::String>,
        ext: ::std::result::Result<::std::option::Option<super::Ext>, ::std::string::String>,
        index: ::std::result::Result<super::ChunkIndex, ::std::string::String>,
    }
    impl ::std::default::Default for Payload {
        fn default() -> Self {
            Self {
                bundle_id: Err("no value supplied for bundle_id".to_string()),
                data: Err("no value supplied for data".to_string()),
                digest_multibase: Err("no value supplied for digest_multibase".to_string()),
                ext: Ok(Default::default()),
                index: Err("no value supplied for index".to_string()),
            }
        }
    }
    impl Payload {
        pub fn bundle_id<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::BundleId>,
            T::Error: ::std::fmt::Display,
        {
            self.bundle_id = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for bundle_id: {e}"));
            self
        }
        pub fn data<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::ChunkData>,
            T::Error: ::std::fmt::Display,
        {
            self.data = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for data: {e}"));
            self
        }
        pub fn digest_multibase<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::DigestMultibase>,
            T::Error: ::std::fmt::Display,
        {
            self.digest_multibase = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for digest_multibase: {e}"));
            self
        }
        pub fn ext<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<::std::option::Option<super::Ext>>,
            T::Error: ::std::fmt::Display,
        {
            self.ext = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for ext: {e}"));
            self
        }
        pub fn index<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::ChunkIndex>,
            T::Error: ::std::fmt::Display,
        {
            self.index = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for index: {e}"));
            self
        }
    }
    impl ::std::convert::TryFrom<Payload> for super::Payload {
        type Error = super::error::ConversionError;
        fn try_from(value: Payload) -> ::std::result::Result<Self, super::error::ConversionError> {
            Ok(Self {
                bundle_id: value.bundle_id?,
                data: value.data?,
                digest_multibase: value.digest_multibase?,
                ext: value.ext?,
                index: value.index?,
            })
        }
    }
    impl ::std::convert::From<super::Payload> for Payload {
        fn from(value: super::Payload) -> Self {
            Self {
                bundle_id: Ok(value.bundle_id),
                data: Ok(value.data),
                digest_multibase: Ok(value.digest_multibase),
                ext: Ok(value.ext),
                index: Ok(value.index),
            }
        }
    }
    #[derive(Clone, Debug)]
    pub struct Response {
        bundle_id: ::std::result::Result<super::BundleId, ::std::string::String>,
        expires_at: ::std::result::Result<super::ExpiresAt, ::std::string::String>,
        ext: ::std::result::Result<::std::option::Option<super::Ext>, ::std::string::String>,
        index: ::std::result::Result<super::ChunkIndex, ::std::string::String>,
        remaining_count: ::std::result::Result<i64, ::std::string::String>,
        stored: ::std::result::Result<bool, ::std::string::String>,
    }
    impl ::std::default::Default for Response {
        fn default() -> Self {
            Self {
                bundle_id: Err("no value supplied for bundle_id".to_string()),
                expires_at: Err("no value supplied for expires_at".to_string()),
                ext: Ok(Default::default()),
                index: Err("no value supplied for index".to_string()),
                remaining_count: Err("no value supplied for remaining_count".to_string()),
                stored: Err("no value supplied for stored".to_string()),
            }
        }
    }
    impl Response {
        pub fn bundle_id<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::BundleId>,
            T::Error: ::std::fmt::Display,
        {
            self.bundle_id = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for bundle_id: {e}"));
            self
        }
        pub fn expires_at<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::ExpiresAt>,
            T::Error: ::std::fmt::Display,
        {
            self.expires_at = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for expires_at: {e}"));
            self
        }
        pub fn ext<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<::std::option::Option<super::Ext>>,
            T::Error: ::std::fmt::Display,
        {
            self.ext = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for ext: {e}"));
            self
        }
        pub fn index<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<super::ChunkIndex>,
            T::Error: ::std::fmt::Display,
        {
            self.index = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for index: {e}"));
            self
        }
        pub fn remaining_count<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<i64>,
            T::Error: ::std::fmt::Display,
        {
            self.remaining_count = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for remaining_count: {e}"));
            self
        }
        pub fn stored<T>(mut self, value: T) -> Self
        where
            T: ::std::convert::TryInto<bool>,
            T::Error: ::std::fmt::Display,
        {
            self.stored = value
                .try_into()
                .map_err(|e| format!("error converting supplied value for stored: {e}"));
            self
        }
    }
    impl ::std::convert::TryFrom<Response> for super::Response {
        type Error = super::error::ConversionError;
        fn try_from(value: Response) -> ::std::result::Result<Self, super::error::ConversionError> {
            Ok(Self {
                bundle_id: value.bundle_id?,
                expires_at: value.expires_at?,
                ext: value.ext?,
                index: value.index?,
                remaining_count: value.remaining_count?,
                stored: value.stored?,
            })
        }
    }
    impl ::std::convert::From<super::Response> for Response {
        fn from(value: super::Response) -> Self {
            Self {
                bundle_id: Ok(value.bundle_id),
                expires_at: Ok(value.expires_at),
                ext: Ok(value.ext),
                index: Ok(value.index),
                remaining_count: Ok(value.remaining_count),
                stored: Ok(value.stored),
            }
        }
    }
}
impl crate::Payload for Payload {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/vta/backup/put-chunk/1.0";
    const IS_PROOF_REQUIRED: bool = true;
    const IS_ISSUED_AT_REQUIRED: bool = true;
    const IS_RECIPIENT_REQUIRED: bool = true;
    const PAYLOAD_SCHEMA: Option<&'static str> = Some(
        "{\n  \"$defs\": {\n    \"BundleId\": {\n      \"description\": \"Handle for a bundle across its whole lifecycle. Recipient-generated and unguessable, which is what lets an unauthorized reference be answered as not-found without confirming existence. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.\",\n      \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n      \"title\": \"BundleId\",\n      \"type\": \"string\"\n    },\n    \"ChunkData\": {\n      \"description\": \"The chunk's bytes, base64url-encoded without padding (RFC 4648 §5). Bounded at 349526 characters, the unpadded encoding of a 262144-byte chunk. These are bytes of the encrypted bundle, so a chunk read in isolation reveals nothing of the agent's state — but a complete set of chunks is the export, and is to be handled as such.\",\n      \"maxLength\": 349526,\n      \"minLength\": 2,\n      \"pattern\": \"^[A-Za-z0-9_-]+$\",\n      \"title\": \"ChunkData\",\n      \"type\": \"string\"\n    },\n    \"ChunkIndex\": {\n      \"description\": \"Zero-based position of a chunk within its bundle. Valid values are 0 to chunkCount − 1; an index outside that range is refused with chunkOutOfRange rather than validated here, because the bound depends on the bundle.\",\n      \"maximum\": 4095,\n      \"minimum\": 0,\n      \"title\": \"ChunkIndex\",\n      \"type\": \"integer\"\n    },\n    \"DigestMultibase\": {\n      \"description\": \"A cryptographic digest as a multibase-encoded multihash — the encoding the W3C Verifiable Credentials Data Model 2.0 defines for `digestMultibase`, and the one `did:webvh` uses for its SCID and entry hashes.\\n\\nMultihash carries the hash algorithm in-band, so the value is self-describing and the wire format survives an algorithm change without a schema revision; multibase does the same for the base encoding, so a verifier never infers base58 from base64url by context. A bare hex string or a `sha-256:`-style prefix hard-codes one algorithm into the wire contract and is non-conforming here.\\n\\nThis definition constrains the *encoding only*. What the digest is computed over is stated by each referencing field, because it differs legitimately: a digest over a JSON document is taken over its RFC 8785 (JCS) canonicalization, while a digest over an opaque artifact is taken over its bytes. A field whose input is a JSON document and which does not name a canonicalization is not reproducible.\\n\\nRestricted to the two multibase headers W3C Controlled Identifiers 1.0 §2.4 normatively requires — `z` (base58btc) and `u` (base64url-no-pad). CID permits others but states that \\\"interoperability is not guaranteed between implementations using such values\\\", and a registry whose purpose is interoperability should not mint digests a conforming verifier may be unable to read. The alphabets are enforced rather than assumed: base58btc excludes 0, O, I and l, and an earlier permissive pattern let three published examples carry digests that were not valid base58 at all. base58btc is RECOMMENDED, for consistency with `did:key` and `did:webvh`.\",\n      \"examples\": [\n        \"zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR\"\n      ],\n      \"minLength\": 16,\n      \"pattern\": \"^(z[1-9A-HJ-NP-Za-km-z]+|u[A-Za-z0-9_-]+)$\",\n      \"title\": \"DigestMultibase\",\n      \"type\": \"string\"\n    },\n    \"ExpiresAt\": {\n      \"description\": \"After which the bundle is collected: staged bytes discarded, tokens and chunk requests refused. Short by design. For a chunked transfer a recipient may move it later as chunks are exchanged, never past its own ceiling — each chunk response reports the current value.\",\n      \"format\": \"date-time\",\n      \"title\": \"ExpiresAt\",\n      \"type\": \"string\"\n    },\n    \"Ext\": {\n      \"additionalProperties\": true,\n      \"description\": \"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.\",\n      \"minProperties\": 1,\n      \"propertyNames\": {\n        \"pattern\": \"^[a-z][a-z0-9-]*(\\\\.[a-z0-9-]+)+$\"\n      },\n      \"title\": \"Ext\",\n      \"type\": \"object\"\n    },\n    \"Response\": {\n      \"$anchor\": \"response\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bundleId\": {\n          \"$ref\": \"#/$defs/BundleId\",\n          \"description\": \"Echoed so the response stands alone as the acknowledgement of one write.\"\n        },\n        \"expiresAt\": {\n          \"$ref\": \"#/$defs/ExpiresAt\",\n          \"description\": \"The slot's current expiry, after any extension this write earned.\"\n        },\n        \"ext\": {\n          \"$ref\": \"#/$defs/Ext\",\n          \"description\": \"Ecosystem-defined extension members per SPEC.md §4.5.1.\"\n        },\n        \"index\": {\n          \"$ref\": \"#/$defs/ChunkIndex\",\n          \"description\": \"Echoed, so an acknowledgement arriving out of order is attributable to its write.\"\n        },\n        \"remainingCount\": {\n          \"description\": \"How many indices the slot still lacks after this write. Zero means the upload is complete and finalize-import can be sent.\",\n          \"maximum\": 4095,\n          \"minimum\": 0,\n          \"type\": \"integer\"\n        },\n        \"stored\": {\n          \"description\": \"Whether this request is what stored the chunk. False means the recipient already held identical bytes at this index — a success, not a failure, and the reason a write can be retried safely. Required rather than optional: an absent member on an idempotent repeat would be indistinguishable from a first write.\",\n          \"type\": \"boolean\"\n        }\n      },\n      \"required\": [\n        \"bundleId\",\n        \"index\",\n        \"stored\",\n        \"remainingCount\",\n        \"expiresAt\"\n      ],\n      \"title\": \"VTA Backup Put Chunk — response payload\",\n      \"type\": \"object\"\n    }\n  },\n  \"$id\": \"https://trusttasks.org/spec/vta/backup/put-chunk/1.0\",\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"additionalProperties\": false,\n  \"description\": \"Writes one chunk of a `chunkedTrustTask` import bundle, by index, into a slot opened by initiate-import. Idempotent for identical bytes; bytes that do not match the pre-committed manifest are refused. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.\",\n  \"properties\": {\n    \"bundleId\": {\n      \"$ref\": \"#/$defs/BundleId\",\n      \"description\": \"Handle from the initiate-import descriptor. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.\"\n    },\n    \"data\": {\n      \"$ref\": \"#/$defs/ChunkData\"\n    },\n    \"digestMultibase\": {\n      \"$ref\": \"#/$defs/DigestMultibase\",\n      \"description\": \"Digest of this chunk's raw bytes, restating the manifest entry for `index`. Restated so that a chunk sent to the wrong index is refused as a mismatch against the manifest at the index it names, rather than surviving until reassembly — the recipient checks this member against the manifest and `data` against both.\"\n    },\n    \"ext\": {\n      \"$ref\": \"#/$defs/Ext\",\n      \"description\": \"Ecosystem-defined extension members per SPEC.md §4.5.1.\"\n    },\n    \"index\": {\n      \"$ref\": \"#/$defs/ChunkIndex\",\n      \"description\": \"Which chunk. Zero-based, below the manifest's chunkCount.\"\n    }\n  },\n  \"required\": [\n    \"bundleId\",\n    \"index\",\n    \"digestMultibase\",\n    \"data\"\n  ],\n  \"title\": \"VTA Backup — Put Chunk — payload\",\n  \"type\": \"object\"\n}\n",
    );
}
impl crate::Payload for Response {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/vta/backup/put-chunk/1.0#response";
    const IS_ISSUED_AT_REQUIRED: bool = true;
    const IS_RECIPIENT_REQUIRED: bool = true;
    const PAYLOAD_SCHEMA: Option<&'static str> = Some(
        "{\n  \"$defs\": {\n    \"BundleId\": {\n      \"description\": \"Handle for a bundle across its whole lifecycle. Recipient-generated and unguessable, which is what lets an unauthorized reference be answered as not-found without confirming existence. Opaque: a producer quotes what it was given and must not derive, guess or enumerate one.\",\n      \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n      \"title\": \"BundleId\",\n      \"type\": \"string\"\n    },\n    \"ChunkData\": {\n      \"description\": \"The chunk's bytes, base64url-encoded without padding (RFC 4648 §5). Bounded at 349526 characters, the unpadded encoding of a 262144-byte chunk. These are bytes of the encrypted bundle, so a chunk read in isolation reveals nothing of the agent's state — but a complete set of chunks is the export, and is to be handled as such.\",\n      \"maxLength\": 349526,\n      \"minLength\": 2,\n      \"pattern\": \"^[A-Za-z0-9_-]+$\",\n      \"title\": \"ChunkData\",\n      \"type\": \"string\"\n    },\n    \"ChunkIndex\": {\n      \"description\": \"Zero-based position of a chunk within its bundle. Valid values are 0 to chunkCount − 1; an index outside that range is refused with chunkOutOfRange rather than validated here, because the bound depends on the bundle.\",\n      \"maximum\": 4095,\n      \"minimum\": 0,\n      \"title\": \"ChunkIndex\",\n      \"type\": \"integer\"\n    },\n    \"DigestMultibase\": {\n      \"description\": \"A cryptographic digest as a multibase-encoded multihash — the encoding the W3C Verifiable Credentials Data Model 2.0 defines for `digestMultibase`, and the one `did:webvh` uses for its SCID and entry hashes.\\n\\nMultihash carries the hash algorithm in-band, so the value is self-describing and the wire format survives an algorithm change without a schema revision; multibase does the same for the base encoding, so a verifier never infers base58 from base64url by context. A bare hex string or a `sha-256:`-style prefix hard-codes one algorithm into the wire contract and is non-conforming here.\\n\\nThis definition constrains the *encoding only*. What the digest is computed over is stated by each referencing field, because it differs legitimately: a digest over a JSON document is taken over its RFC 8785 (JCS) canonicalization, while a digest over an opaque artifact is taken over its bytes. A field whose input is a JSON document and which does not name a canonicalization is not reproducible.\\n\\nRestricted to the two multibase headers W3C Controlled Identifiers 1.0 §2.4 normatively requires — `z` (base58btc) and `u` (base64url-no-pad). CID permits others but states that \\\"interoperability is not guaranteed between implementations using such values\\\", and a registry whose purpose is interoperability should not mint digests a conforming verifier may be unable to read. The alphabets are enforced rather than assumed: base58btc excludes 0, O, I and l, and an earlier permissive pattern let three published examples carry digests that were not valid base58 at all. base58btc is RECOMMENDED, for consistency with `did:key` and `did:webvh`.\",\n      \"examples\": [\n        \"zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR\"\n      ],\n      \"minLength\": 16,\n      \"pattern\": \"^(z[1-9A-HJ-NP-Za-km-z]+|u[A-Za-z0-9_-]+)$\",\n      \"title\": \"DigestMultibase\",\n      \"type\": \"string\"\n    },\n    \"ExpiresAt\": {\n      \"description\": \"After which the bundle is collected: staged bytes discarded, tokens and chunk requests refused. Short by design. For a chunked transfer a recipient may move it later as chunks are exchanged, never past its own ceiling — each chunk response reports the current value.\",\n      \"format\": \"date-time\",\n      \"title\": \"ExpiresAt\",\n      \"type\": \"string\"\n    },\n    \"Ext\": {\n      \"additionalProperties\": true,\n      \"description\": \"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.\",\n      \"minProperties\": 1,\n      \"propertyNames\": {\n        \"pattern\": \"^[a-z][a-z0-9-]*(\\\\.[a-z0-9-]+)+$\"\n      },\n      \"title\": \"Ext\",\n      \"type\": \"object\"\n    },\n    \"Response\": {\n      \"$anchor\": \"response\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bundleId\": {\n          \"$ref\": \"#/$defs/BundleId\",\n          \"description\": \"Echoed so the response stands alone as the acknowledgement of one write.\"\n        },\n        \"expiresAt\": {\n          \"$ref\": \"#/$defs/ExpiresAt\",\n          \"description\": \"The slot's current expiry, after any extension this write earned.\"\n        },\n        \"ext\": {\n          \"$ref\": \"#/$defs/Ext\",\n          \"description\": \"Ecosystem-defined extension members per SPEC.md §4.5.1.\"\n        },\n        \"index\": {\n          \"$ref\": \"#/$defs/ChunkIndex\",\n          \"description\": \"Echoed, so an acknowledgement arriving out of order is attributable to its write.\"\n        },\n        \"remainingCount\": {\n          \"description\": \"How many indices the slot still lacks after this write. Zero means the upload is complete and finalize-import can be sent.\",\n          \"maximum\": 4095,\n          \"minimum\": 0,\n          \"type\": \"integer\"\n        },\n        \"stored\": {\n          \"description\": \"Whether this request is what stored the chunk. False means the recipient already held identical bytes at this index — a success, not a failure, and the reason a write can be retried safely. Required rather than optional: an absent member on an idempotent repeat would be indistinguishable from a first write.\",\n          \"type\": \"boolean\"\n        }\n      },\n      \"required\": [\n        \"bundleId\",\n        \"index\",\n        \"stored\",\n        \"remainingCount\",\n        \"expiresAt\"\n      ],\n      \"title\": \"VTA Backup Put Chunk — response payload\",\n      \"type\": \"object\"\n    }\n  },\n  \"$ref\": \"#/$defs/Response\",\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\"\n}\n",
    );
}
impl crate::RequestPayload for Payload {
    type Response = Response;
}
#[cfg(test)]
mod conformance {
    //! Round-trip tests harvested from the spec's `spec.md`,
    //! plus a `rejects_invalid_examples` test for any fixtures
    //! in `payload.invalid-examples.json` (validate feature).
    #[test]
    fn request_example_1() {
        const JSON: &str = "{\n  \"id\": \"urn:uuid:00000000-0000-4000-8000-000000000019\",\n  \"type\": \"https://trusttasks.org/spec/vta/backup/put-chunk/1.0#request\",\n  \"issuer\": \"did:example:operator\",\n  \"recipient\": \"did:example:agent\",\n  \"issuedAt\": \"2026-01-01T03:01:00Z\",\n  \"threadId\": \"urn:uuid:00000000-0000-4000-8000-0000000000fa\",\n  \"payload\": {\n    \"bundleId\": \"7e6d5c4b-3a29-4817-a6f5-e4d3c2b1a098\",\n    \"index\": 2,\n    \"digestMultibase\": \"zQmTcWLvAPe4Txz32vVqZe5jgX4nBPiaBsTTCp4bLXDMzTT\",\n    \"data\": \"YmFja3VwLXRhaWwh\"\n  }\n}\n";
        let doc: crate::TrustTask<super::Payload> =
            serde_json::from_str(JSON).expect("deserialize request example");
        let rendered = serde_json::to_value(&doc).expect("re-serialize");
        let expected: serde_json::Value = serde_json::from_str(JSON).expect("re-parse expected");
        assert_eq!(rendered, expected, "request example failed round-trip");
    }
    #[test]
    fn response_example_1() {
        const JSON: &str = "{\n  \"id\": \"urn:uuid:00000000-0000-4000-8000-00000000001a\",\n  \"type\": \"https://trusttasks.org/spec/vta/backup/put-chunk/1.0#response\",\n  \"issuer\": \"did:example:agent\",\n  \"recipient\": \"did:example:operator\",\n  \"issuedAt\": \"2026-01-01T03:01:01Z\",\n  \"threadId\": \"urn:uuid:00000000-0000-4000-8000-0000000000fa\",\n  \"payload\": {\n    \"bundleId\": \"7e6d5c4b-3a29-4817-a6f5-e4d3c2b1a098\",\n    \"index\": 2,\n    \"stored\": true,\n    \"remainingCount\": 0,\n    \"expiresAt\": \"2026-01-01T03:11:01Z\"\n  }\n}\n";
        let doc: crate::TrustTask<super::Response> =
            serde_json::from_str(JSON).expect("deserialize response example");
        let rendered = serde_json::to_value(&doc).expect("re-serialize");
        let expected: serde_json::Value = serde_json::from_str(JSON).expect("re-parse expected");
        assert_eq!(rendered, expected, "response example failed round-trip");
    }
    /// Each fixture in `payload.invalid-examples.json` MUST be
    /// rejected by at least one of: serde deserialization, or
    /// JSON-Schema validation under the `validate` feature. The
    /// fixture file documents the producer-side bug class that
    /// each payload exemplifies; this generated test pins it.
    #[cfg(feature = "validate")]
    #[test]
    fn rejects_invalid_examples() {
        use crate::validate::ValidatedPayload;
        let fixtures: &[(&str, &str)] = &[
            (
                "Missing `digestMultibase`. The producer restates the digest it pre-committed so that a chunk written to the wrong index is caught as a mismatch at the index, not only after reassembly.",
                "{\n  \"bundleId\": \"5b1f4a2e-7c3d-4e8f-9a6b-2d0c1e3f4a5b\",\n  \"data\": \"YmFja3VwLXRhaWwh\",\n  \"index\": 2\n}",
            ),
            (
                "Missing `data`. There is no empty chunk: a chunk holds at least one byte.",
                "{\n  \"bundleId\": \"5b1f4a2e-7c3d-4e8f-9a6b-2d0c1e3f4a5b\",\n  \"digestMultibase\": \"zQmTcWLvAPe4Txz32vVqZe5jgX4nBPiaBsTTCp4bLXDMzTT\",\n  \"index\": 2\n}",
            ),
            (
                "`data` in standard base64 with padding. The member is base64url without padding; accepting both alphabets makes the same chunk two different strings, and `+`, `/` and `=` are exactly what a lenient decoder silently drops.",
                "{\n  \"bundleId\": \"5b1f4a2e-7c3d-4e8f-9a6b-2d0c1e3f4a5b\",\n  \"data\": \"YmFja3VwLXRhaWwh+/==\",\n  \"digestMultibase\": \"zQmTcWLvAPe4Txz32vVqZe5jgX4nBPiaBsTTCp4bLXDMzTT\",\n  \"index\": 2\n}",
            ),
            (
                "Digest as bare hex. Chunk digests are DigestMultibase, so the hash algorithm travels with the value.",
                "{\n  \"bundleId\": \"5b1f4a2e-7c3d-4e8f-9a6b-2d0c1e3f4a5b\",\n  \"data\": \"YmFja3VwLXRhaWwh\",\n  \"digestMultibase\": \"20111c1d10631a5d6b2e9e06f558cd5c84e841d2bc5758bfda0d3b76bb4927f0\",\n  \"index\": 2\n}",
            ),
        ];
        for (i, (note, raw)) in fixtures.iter().enumerate() {
            let value: serde_json::Value = match serde_json::from_str(raw) {
                Ok(v) => v,
                Err(_) => continue,
            };
            let serde_ok = serde_json::from_value::<super::Payload>(value.clone()).is_ok();
            let schema_ok = super::Payload::validate_value(&value).is_ok();
            assert!(
                !(serde_ok && schema_ok),
                "invalid-example #{} ({:?}) was accepted by both serde and JSON Schema; \
                         the fixture's stated failure class is no longer caught:\n{}",
                i + 1,
                note,
                raw
            );
        }
    }
}