forked from AtomicIP/AtomicIP-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
7240 lines (6302 loc) · 264 KB
/
Copy pathlib.rs
File metadata and controls
7240 lines (6302 loc) · 264 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![no_std]
#![allow(deprecated)]
#[cfg(test)]
extern crate std;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, panic_with_error, symbol_short, Address,
Bytes, BytesN, Env, Error, Symbol, Vec,
};
mod validation;
use validation::*;
mod types;
use types::*;
mod zk_commitment;
#[cfg(test)]
mod test;
// #817: benchmarks.rs fixed and extended with zk_commitment benchmarks.
#[cfg(test)]
mod benchmarks;
#[cfg(test)]
mod mutation_tests;
#[cfg(test)]
mod snapshot_tests;
#[cfg(test)]
mod differential_tests;
// FIXME: invariant_tests.rs has pre-existing compilation errors from a merge conflict
// #[cfg(test)]
// mod invariant_tests;
#[cfg(test)]
mod upgrade_tests;
// ── Error Codes ────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum ContractError {
IpNotFound = 1,
ZeroCommitmentHash = 2,
CommitmentAlreadyRegistered = 3,
IpAlreadyRevoked = 4,
UnauthorizedUpgrade = 5,
Unauthorized = 6,
IpExpired = 7,
MetadataTooLarge = 8,
LicenseeNotFound = 9,
InsufficientPoW = 10,
InvalidExpiry = 11,
IpInDispute = 12,
/// #348: Co-owner not found in ownership list.
CoOwnerNotFound = 13,
/// #348: Invalid ownership percentage (must be 0-100).
InvalidOwnershipPercentage = 14,
/// #348: Only owner can manage co-owners.
OnlyOwnerCanManageCoOwners = 15,
DisputeNotFound = 16,
DisputeAlreadyResolved = 17,
StakeNotFound = 18,
AlreadyStaked = 19,
StakeAlreadySlashed = 20,
ArbitrationNotFound = 21,
ArbitrationAlreadyFinalized = 22,
NotAnArbitrator = 23,
/// #454: Threshold not yet met.
ThresholdNotMet = 24,
/// #454: Signer not in authorized list.
SignerNotAuthorized = 25,
/// #454: Signer already submitted a signature.
AlreadySigned = 26,
/// #455: Batch metadata too large.
BatchMetadataTooLarge = 27,
/// #457: Encrypted data too large.
EncryptedDataTooLarge = 28,
/// #465: Escrow not found.
EscrowNotFound = 29,
/// #465: Escrow already released or cancelled.
EscrowNotActive = 30,
/// #465: Timeout not reached for cancellation.
EscrowTimeoutNotReached = 31,
/// #459: Category hash is invalid (all zeros).
InvalidCategoryHash = 32,
/// #459: Category depth exceeds maximum allowed.
InvalidCategoryDepth = 33,
/// #459: Category not registered.
CategoryNotFound = 34,
/// Batch operation size mismatch.
BatchSizeMismatch = 35,
/// #790: Contract has not been initialized with a real admin address yet.
NotInitialized = 36,
/// #790: `initialize` was called on a contract that already has an admin.
AlreadyInitialized = 37,
/// #791: candidate upgrade WASM's manifest is missing an exported function,
/// storage key, or error code that the current contract relies on, or it
/// reassigns an existing error code to a different meaning.
IncompatibleUpgrade = 38,
}
// ── TTL ───────────────────────────────────────────────────────────────────────
/// Minimum ledger TTL bump applied to every persistent storage write.
/// ~1 year at ~5s per ledger: 365 * 24 * 3600 / 5 ≈ 6_307_200 ledgers.
pub const LEDGER_BUMP: u32 = 6_307_200;
/// Issue #811: Default TTL for ownership challenges, in seconds (24 hours).
/// Can be overridden via `set_challenge_ttl`.
pub const DEFAULT_CHALLENGE_TTL_SECONDS: u64 = 86_400;
/// Maximum metadata size: 1 KB
pub const MAX_METADATA_BYTES: u32 = 1024;
/// Trusted notary public key for timestamp notarization (Issue #345)
/// This is a placeholder - should be set during contract initialization
pub const NOTARY_PUBLIC_KEY: &[u8] = b"notary_public_key_placeholder";
/// Issue #437: Number of storage shards for commitment distribution.
pub const NUM_SHARDS: u32 = 16;
/// Issue #785: Maximum number of IP IDs held in a single shard sub-index
/// vector. Once a sub-index reaches this size, further writes roll over to
/// a fresh sub-index instead of growing the vector, so every shard write
/// touches a bounded amount of storage regardless of how many commitments
/// have ever landed in that shard.
pub const SUB_SHARD_CAPACITY: u32 = 512;
/// Issue #785: Maximum number of legacy (pre-sub-sharding) entries migrated
/// into the bounded layout per call. Keeps migration cost bounded per
/// transaction instead of requiring a one-shot admin migration.
const SHARD_MIGRATION_BATCH: u32 = 64;
/// Issue #459: Maximum allowed category hierarchy depth.
/// Supports paths like "Software/Cryptography/ZK-Proofs/DLV/AXIOM" (depth 5).
pub const MAX_CATEGORY_DEPTH: u32 = 10;
// ── Storage Keys ────────────────────────────────────────────────────────────
#[contracttype]
#[derive(Debug, PartialEq)]
pub enum DataKey {
IpRecord(u64),
OwnerIps(Address),
NextId,
CommitmentOwner(BytesN<32>), // tracks which owner already holds a commitment hash
/// Maps commitment hash -> blinded owner identifier for anonymous commits
AnonymousOwner(BytesN<32>),
/// #464: Tracks blinded_owner values that have already been used for replay protection
UsedBlindedOwner(BytesN<32>),
Admin,
PartialDisclosure(u64), // stores partial_hash for a given ip_id after reveal
IpLicenses(u64), // stores license entries for a given ip_id
CategoryIps(BytesN<32>), // maps category hash -> Vec<u64> of IP IDs
PowDifficulty, // stores the current PoW difficulty (leading zero bits required)
IpVersions(u64), // stores Vec<u64> of all version IDs for a given IP
SuggestedPrice(u64), // stores suggested price for an IP
IpCommitmentChecksum, // Issue #346: stores hash of all commitments for rollback protection
IpAccessGrants(u64), // Issue #344: stores Vec of (grantee, access_level) for tiered access
NotarySignature(u64), // Issue #345: stores notary signature for timestamp notarization
IpVersionChain(u64), // stores Vec<u64> of the full version chain rooted at a given IP
OwnershipChallenge(u64), // Issue #433: stores OwnershipChallenge for a given challenge_id
NextChallengeId, // Issue #433: monotonic challenge ID counter
EncryptionKeyRotation(u64), // Issue #434: stores rotation history for a given ip_id
NotaryPublicKey, // Issue #428: stores the trusted notary Ed25519 public key (32 bytes)
CommitmentHashes, // Issue #429: stores Vec<BytesN<32>> of all commitment hashes for rollback protection
IpPowDifficulty(u64), // stores the pow_difficulty used at commit time for strength scoring
// Previously missing variants (used in existing code)
ShardIps(u32), // Issue #437: legacy unbounded shard vector; Issue #785 migrates entries out of this lazily
/// Issue #785: maps (shard_id, sub_index) -> bounded Vec<u64> of IP IDs (capacity SUB_SHARD_CAPACITY)
ShardSubIps(u32, u32),
/// Issue #785: maps shard_id -> sub_index currently being appended to
ShardHead(u32),
IpAuditTrail(u64), // Issue #436: stores Vec<AuditEntry> for a given ip_id
RenewalCount(u64), // stores renewal count for a given ip_id
Delegates(Address), // stores Vec<DelegationRecord> for a given owner
DelegateDepth(Address), // stores delegation depth for a given delegate
IpDisputes(u64), // stores DisputeRecord for a given dispute_id
NextDisputeId, // monotonic dispute ID counter
IpStake(u64), // Issue #447: stores StakeRecord for a given ip_id
OwnerReputation(Address), // Issue #448: stores ReputationRecord for a given owner
ArbitrationCase(u64), // Issue #449: stores ArbitrationRecord for a given arbitration_id
NextArbitrationId, // Issue #449: monotonic arbitration ID counter
ArbitratorPool, // Issue #449: stores Vec<Address> of registered arbitrators
CompressedCommitment(u64), // Issue #438: stores compressed commitment bytes for a given ip_id
// Issue #458: Batch verification result cache
BatchVerifyResult(BytesN<32>), // maps batch_proof_id -> BatchVerifyResult
// Issue #456: Compression algorithm selection
CompressionSelection(u64), // maps ip_id -> CompressionSelection
// Issue #459: Hierarchical storage
HierarchyNode(Address, BytesN<32>), // maps (owner, category_hash) -> Vec<u64> of IP IDs
OwnerCategories(Address), // maps owner -> Vec<BytesN<32>> of category hashes
CategoryDepth(BytesN<32>), // maps category_hash -> u32 depth
// Issue #454: Threshold signatures
ThresholdConfig(u64),
ThresholdSignatures(u64),
// Issue #455: Batch metadata
BatchMetadata(u64),
// Issue #457: Encrypted commitment
EncryptedCommitment(u64),
// Issue #465: Batch escrow — keyed by escrow_id (sha256 of ip_ids + timestamp)
BatchEscrow(BytesN<32>),
// Issue #811: TTL (in seconds) for ownership challenges
ChallengeTtl,
// Issue #812: Cached Merkle root for an owner's commitment set; None = stale
MerkleRoot(Address),
// Issue #812: Flag indicating the cached Merkle root for an owner is stale
MerkleRootStale(Address),
}
// ── Upgrade Compatibility Manifest (#791) ───────────────────────────────────
/// A single (error name, error code) pair, part of an `UpgradeManifest`.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ManifestErrorCode {
pub name: Symbol,
pub code: u32,
}
/// Describes a candidate contract WASM's public interface for compatibility
/// checking in `validate_upgrade`. A Soroban contract cannot introspect an
/// arbitrary WASM blob from within itself, so off-chain tooling that built the
/// candidate WASM supplies this manifest alongside its hash.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct UpgradeManifest {
/// Names of every function the candidate contract exports.
pub functions: Vec<Symbol>,
/// Names of every `DataKey` storage-key variant the candidate contract uses.
pub storage_keys: Vec<Symbol>,
/// Every (error name, error code) pair the candidate contract defines.
pub error_codes: Vec<ManifestErrorCode>,
}
/// Names of every function exported by the currently deployed contract.
/// Used as the compatibility baseline in `validate_upgrade`.
const CURRENT_FUNCTIONS: &[&str] = &[
"add_co_owner", "add_threshold_signature", "assign_ip_to_category", "batch_commit_ip",
"batch_commit_ip_anonymous", "batch_delegate_commitment", "batch_escrow_commitments", "batch_renew_ip",
"batch_stake_commitments", "batch_update_reputation", "batch_verify_commitments", "cancel_batch_escrow",
"check_expiration_warning", "check_ip_access", "cleanup_expired_ips", "commit_ip",
"commit_ip_delegated", "commit_ip_version", "compute_ip_merkle_root", "create_ip_version",
"delegate_commitment_authority", "encrypt_commitment", "finalize_arbitration", "find_duplicate_commitment",
"generate_merkle_proof", "get_anonymous_owner", "get_arbitration", "get_batch_escrow",
"get_batch_metadata", "get_blinded_owner_batch", "get_commitment_compression", "get_commitment_shard",
"get_compressed_bytes", "get_compressed_commitment", "get_dispute", "get_encrypted_commitment",
"get_ip", "get_ip_access_grants", "get_ip_audit_trail", "get_ip_lineage",
"get_ip_notary_signature", "get_ip_strength", "get_ip_suggested_price", "get_ip_version_chain",
"get_ip_versions", "get_key_rotation_history", "get_licenses", "get_ownership_challenge",
"get_partial_disclosure", "get_pow_difficulty", "get_renewal_count", "get_reputation",
"get_stake", "get_threshold_config", "get_threshold_signatures", "grant_ip_access",
"grant_license", "initialize", "initiate_dispute", "is_delegate",
"is_ip_owner", "issue_ownership_challenge", "list_ip_by_category", "list_ip_by_owner",
"list_ip_by_shard", "list_owner_categories", "merge_duplicate_commitment", "nominate_arbitrator",
"notarize_ip_timestamp", "open_arbitration", "register_category_path", "release_batch_escrow",
"remove_co_owner", "renew_ip", "renew_ip_commitment", "require_threshold_signatures",
"resolve_dispute", "respond_to_ownership_challenge", "reveal_and_verify_commitments", "reveal_partial",
"revoke_delegation", "revoke_ip", "revoke_ip_access", "revoke_license",
"rotate_commitment_key", "set_admin", "set_batch_metadata", "set_commitment_compression",
"set_ip_expiry", "set_ip_suggested_price", "set_notary_public_key", "slash_stake",
"stake_commitment", "submit_dispute_evidence", "transfer_ip", "transfer_ip_ownership",
"unstake", "update_reputation", "upgrade", "validate_category",
"validate_upgrade", "verify_batch_proof", "verify_commitment", "verify_commitment_integrity",
"verify_commitment_pow", "verify_ip_merkle_proof", "verify_ownership_challenge", "verify_threshold_signatures",
"vote_on_dispute",
];
/// Names of every `DataKey` storage-key variant the currently deployed
/// contract reads or writes. Used as the compatibility baseline in
/// `validate_upgrade`.
const CURRENT_STORAGE_KEYS: &[&str] = &[
"IpRecord", "OwnerIps", "NextId", "CommitmentOwner", "AnonymousOwner", "UsedBlindedOwner",
"Admin", "PartialDisclosure", "IpLicenses", "CategoryIps", "PowDifficulty", "IpVersions",
"SuggestedPrice", "IpCommitmentChecksum", "IpAccessGrants", "NotarySignature", "IpVersionChain",
"OwnershipChallenge", "NextChallengeId", "EncryptionKeyRotation", "NotaryPublicKey",
"CommitmentHashes", "IpPowDifficulty", "ShardIps", "ShardSubIps", "ShardHead", "IpAuditTrail",
"RenewalCount", "Delegates", "DelegateDepth", "IpDisputes", "NextDisputeId", "IpStake",
"OwnerReputation", "ArbitrationCase", "NextArbitrationId", "ArbitratorPool",
"CompressedCommitment", "BatchVerifyResult", "CompressionSelection", "HierarchyNode",
"OwnerCategories", "CategoryDepth", "ThresholdConfig", "ThresholdSignatures", "BatchMetadata",
"EncryptedCommitment", "BatchEscrow",
];
/// (error name, error code) pairs defined by the currently deployed contract.
/// Used as the compatibility baseline in `validate_upgrade`.
const CURRENT_ERROR_CODES: &[(&str, u32)] = &[
("IpNotFound", 1),
("ZeroCommitmentHash", 2),
("CommitmentAlreadyRegistered", 3),
("IpAlreadyRevoked", 4),
("UnauthorizedUpgrade", 5),
("Unauthorized", 6),
("IpExpired", 7),
("MetadataTooLarge", 8),
("LicenseeNotFound", 9),
("InsufficientPoW", 10),
("InvalidExpiry", 11),
("IpInDispute", 12),
("CoOwnerNotFound", 13),
("InvalidOwnershipPercentage", 14),
("OnlyOwnerCanManageCoOwners", 15),
("DisputeNotFound", 16),
("DisputeAlreadyResolved", 17),
("StakeNotFound", 18),
("AlreadyStaked", 19),
("StakeAlreadySlashed", 20),
("ArbitrationNotFound", 21),
("ArbitrationAlreadyFinalized", 22),
("NotAnArbitrator", 23),
("ThresholdNotMet", 24),
("SignerNotAuthorized", 25),
("AlreadySigned", 26),
("BatchMetadataTooLarge", 27),
("EncryptedDataTooLarge", 28),
("EscrowNotFound", 29),
("EscrowNotActive", 30),
("EscrowTimeoutNotReached", 31),
("InvalidCategoryHash", 32),
("InvalidCategoryDepth", 33),
("CategoryNotFound", 34),
("BatchSizeMismatch", 35),
("NotInitialized", 36),
("AlreadyInitialized", 37),
("IncompatibleUpgrade", 38),
];
// ── Types ────────────────────────────────────────────────────────────────────
/// Delegation chain record: tracks a delegate and the depth at which they were granted authority.
/// Depth 0 = direct delegate of the owner; depth 1 = delegate of a delegate, etc.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DelegationRecord {
pub delegate: Address,
pub depth: u32,
}
/// Maximum delegation chain depth to prevent unbounded chains.
pub const MAX_DELEGATION_DEPTH: u32 = 5;
/// Issue #436: A single immutable audit entry for an IP record.
/// Entries are append-only and can never be modified or removed.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct AuditEntry {
pub action: soroban_sdk::Symbol, // e.g. "committed", "revoked", "transferred"
pub actor: Address,
pub timestamp: u64,
}
#[contracttype]
#[derive(Clone)]
pub struct LicenseEntry {
pub licensee: Address,
pub terms_hash: BytesN<32>,
}
#[contracttype]
#[derive(Clone)]
pub struct IpDispute {
pub ip_id: u64,
pub claimant: Address,
pub evidence_hash: BytesN<32>,
pub timestamp: u64,
pub resolved: bool,
}
#[contracttype]
#[derive(Clone)]
pub struct Attestation {
pub attestor: Address,
pub attestation_data: Bytes,
pub timestamp: u64,
}
#[contracttype]
#[derive(Clone)]
pub struct IpChallenge {
pub challenger: Address,
pub reason: Bytes,
pub timestamp: u64,
pub resolved: bool,
pub resolution: Bytes,
}
#[contracttype]
#[derive(Clone)]
pub struct DisputeRecord {
pub dispute_id: u64,
pub ip_id: u64,
pub challenger: Address,
pub evidence_hash: BytesN<32>,
pub timestamp: u64,
pub resolved: bool,
pub winner: Option<Address>,
}
/// Issue #447: Stake record for an IP commitment.
#[contracttype]
#[derive(Clone)]
pub struct StakeRecord {
pub ip_id: u64,
pub owner: Address,
pub amount: i128,
pub slashed: bool,
}
/// Issue #448: Reputation record for an IP owner.
#[contracttype]
#[derive(Clone)]
pub struct ReputationRecord {
pub owner: Address,
pub score: i64, // can go negative after slashing
pub commitments: u64, // total successful commitments
pub disputes_lost: u64,
}
/// Issue #449: Arbitration case for a dispute.
#[contracttype]
#[derive(Clone)]
pub struct ArbitrationRecord {
pub arbitration_id: u64,
pub dispute_id: u64,
pub arbitrators: soroban_sdk::Vec<Address>,
pub votes_owner: u32,
pub votes_challenger: u32,
pub finalized: bool,
pub winner: Option<Address>,
}
// ── Issue #454: Threshold Signatures ─────────────────────────────────────────
/// Configuration for M-of-N threshold signature verification.
#[contracttype]
#[derive(Clone)]
pub struct ThresholdConfig {
pub ip_id: u64,
pub threshold: u32, // M: minimum signatures required
pub total: u32, // N: total authorized signers
pub signers: soroban_sdk::Vec<Address>,
}
/// A single threshold signature entry.
#[contracttype]
#[derive(Clone)]
pub struct ThresholdSignature {
pub signer: Address,
pub signature_hash: BytesN<32>, // sha256(commitment_hash || signer_address_bytes)
pub timestamp: u64,
}
// ── Issue #455: Batch Metadata ────────────────────────────────────────────────
/// Metadata attached to a batch commitment.
#[contracttype]
#[derive(Clone)]
pub struct BatchMetadata {
pub ip_id: u64,
pub batch_id: BytesN<32>, // identifier for the batch this IP belongs to
pub description: Bytes, // arbitrary metadata (max 1 KB)
pub timestamp: u64,
}
// ── Issue #456: Compression Algorithm Selection ───────────────────────────────
/// Supported compression algorithms for commitment storage.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum CompressionAlgo {
None = 0,
Truncate16 = 1, // first 16 bytes (existing default)
Xor8 = 2, // XOR fold to 8 bytes
}
/// Per-IP compression algorithm selection.
#[contracttype]
#[derive(Clone)]
pub struct CompressionSelection {
pub ip_id: u64,
pub algorithm: CompressionAlgo,
}
// ── Issue #457: Commitment Encryption ────────────────────────────────────────
/// Encrypted commitment data stored at rest.
#[contracttype]
#[derive(Clone)]
pub struct EncryptedCommitmentRecord {
pub ip_id: u64,
pub encrypted_hash: Bytes, // commitment hash encrypted with owner's key
pub key_hint: BytesN<32>, // public key hint (e.g. sha256 of owner's public key)
pub timestamp: u64,
}
// ── Issue #465: Batch Escrow ─────────────────────────────────────────────────
/// Escrow status for batch commitment escrow.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
#[repr(u32)]
pub enum EscrowStatus {
Active = 0,
Released = 1,
Cancelled = 2,
}
/// Escrow record for multiple commitments held in trust.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct EscrowRecord {
pub escrow_id: BytesN<32>,
pub depositor: Address,
pub ip_ids: soroban_sdk::Vec<u64>,
pub release_to: Address,
pub timeout: u64,
pub status: EscrowStatus,
pub timestamp: u64,
}
// ── Issue #458: Batch Verification with ZK Proofs ────────────────────────────
/// A single verification request in a batch.
#[contracttype]
#[derive(Clone)]
pub struct VerifyRequest {
pub ip_id: u64,
pub secret: BytesN<32>,
pub blinding_factor: BytesN<32>,
}
/// Result of a single commitment verification within a batch.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VerifyResult {
pub ip_id: u64,
pub valid: bool,
}
/// A non-interactive Schnorr proof of knowledge of a Pedersen commitment's
/// opening `(secret, blinding_factor)`, made non-interactive via
/// Fiat-Shamir. Never contains `secret` or `blinding_factor` themselves.
/// See `zk_commitment` for the verification math.
#[contracttype]
#[derive(Clone)]
pub struct HidingCommitmentProof {
/// Compressed Ristretto255 point `R = k_secret·G + k_blinding·H`.
pub r: BytesN<32>,
/// Response scalar `s_secret = k_secret + e·secret` (mod L).
pub s_secret: BytesN<32>,
/// Response scalar `s_blinding = k_blinding + e·blinding_factor` (mod L).
pub s_blinding: BytesN<32>,
}
/// A single hiding-verification request in a batch: which IP's commitment to
/// check, and the zero-knowledge proof of its opening.
#[contracttype]
#[derive(Clone)]
pub struct HidingVerifyRequest {
pub ip_id: u64,
pub proof: HidingCommitmentProof,
}
/// Stored result of a completed batch verification, keyed by the aggregate proof hash.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct BatchVerifyResultStorage {
pub aggregate_proof: BytesN<32>,
pub total_count: u32,
pub valid_count: u32,
}
// ── Issue #459: Hierarchical Storage ─────────────────────────────────────────
/// A node in the hierarchical commitment tree.
/// Organises IPs under owner → category → ip_ids for O(1) category lookups.
#[contracttype]
#[derive(Clone)]
pub struct HierarchyNode {
pub owner: Address,
pub category_hash: BytesN<32>, // sha256 of the category label
pub ip_ids: soroban_sdk::Vec<u64>,
}
/// Metadata for a registered category path.
#[contracttype]
#[derive(Clone, Debug)]
pub struct CategoryInfo {
pub path: soroban_sdk::Bytes, // full category path e.g. "Software/Cryptography/ZK-Proofs"
pub depth: u32, // number of segments (3 for the example above)
}
// ── Helpers ──────────────────────────────────────────────────────────────────
/// Constant-time comparison of two 32-byte arrays.
/// Returns `true` if all 32 bytes match, `false` otherwise.
/// Every code path performs exactly 32 XOR+OR operations regardless of input,
/// preventing timing side-channel attacks.
fn constant_time_bytes_32_eq(a: &BytesN<32>, b: &BytesN<32>) -> bool {
let a_arr = a.to_array();
let b_arr = b.to_array();
let mut diff: u8 = 0;
for i in 0..32 {
diff |= a_arr[i] ^ b_arr[i];
}
diff == 0
}
/// Deterministically aggregate multiple commitment hashes into a single proof
/// using incremental SHA-256 hashing.
///
/// Starting from an all-zeros seed, each verified commitment hash is folded in:
/// `proof ← sha256(proof || commitment_hash)`
///
/// This produces a deterministic, order-dependent aggregate proof that can be
/// used to efficiently validate the entire batch.
fn aggregate_batch_proof(env: &Env, commitment_hashes: &Vec<BytesN<32>>) -> BytesN<32> {
let mut proof = BytesN::from_array(env, &[0u8; 32]);
for hash in commitment_hashes.iter() {
let mut input = Bytes::new(env);
input.append(&proof.into());
input.append(&hash.into());
proof = env.crypto().sha256(&input).into();
}
proof
}
// ── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct IpRegistry;
#[contractimpl]
impl IpRegistry {
/// Initialize the contract with a real, externally-controlled admin address.
///
/// Must be called exactly once, before any admin-gated function is usable.
/// Requires the auth of the `admin` address being set, so a caller cannot
/// install an admin they do not control.
///
/// # Panics
///
/// Panics if the contract has already been initialized.
pub fn initialize(env: Env, admin: Address) {
admin.require_auth();
if env.storage().persistent().has(&DataKey::Admin) {
env.panic_with_error(Error::from_contract_error(
ContractError::AlreadyInitialized as u32,
));
}
env.storage().persistent().set(&DataKey::Admin, &admin);
env.storage()
.persistent()
.extend_ttl(&DataKey::Admin, LEDGER_BUMP, LEDGER_BUMP);
}
/// Rotate the admin address. Only the current admin may do this.
///
/// # Panics
///
/// Panics if the contract has not been initialized or the caller is not
/// the current admin.
pub fn set_admin(env: Env, new_admin: Address) {
let admin = Self::require_admin(&env);
admin.require_auth();
env.storage().persistent().set(&DataKey::Admin, &new_admin);
env.storage()
.persistent()
.extend_ttl(&DataKey::Admin, LEDGER_BUMP, LEDGER_BUMP);
}
/// Fetch the stored admin address, panicking if the contract has not been
/// initialized yet.
fn require_admin(env: &Env) -> Address {
env.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, ContractError::NotInitialized))
}
/// Timestamp a new IP commitment. Returns the assigned IP ID.
///
/// This function creates a new IP record with a cryptographic commitment hash,
/// establishing a verifiable timestamp on the blockchain. The commitment hash
/// should be constructed using the Pedersen commitment scheme: sha256(secret || blinding_factor).
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `owner` - The address that owns the IP. This address must authorize the transaction.
/// * `commitment_hash` - A 32-byte cryptographic hash of the IP secret and blinding factor.
/// Must not be all zeros and must be unique across all registered IPs.
///
/// # Returns
///
/// The unique IP ID assigned to this commitment. IDs start at 1 and are monotonically increasing,
/// persisting across contract upgrades. ID 0 is reserved and never assigned.
///
/// # Panics
///
/// Panics if:
/// * The `owner` does not authorize the transaction (auth error)
/// * The `commitment_hash` is all zeros (ZeroCommitmentHash error)
/// * The `commitment_hash` is already registered (duplicate commitment error)
///
/// # Auth Model
///
/// `owner.require_auth()` is the correct Soroban idiom for "only this address
/// may call this function". The Soroban host enforces it at the protocol level:
/// the transaction must carry a valid signature (or delegated sub-auth) for
/// `owner`. No caller can satisfy this check for an address they do not
/// legitimately control — the host will panic with an auth error.
///
/// The one exception is test environments that call `env.mock_all_auths()`,
/// which intentionally bypasses all auth checks. Production transactions on
/// the Stellar network cannot use this mechanism; it is a test-only helper.
///
/// Therefore: a caller cannot forge `owner` in production. They can only
/// commit IP under an address for which they hold a valid private key or
/// delegated authorization.
pub fn commit_ip(
env: Env,
owner: Address,
commitment_hash: BytesN<32>,
pow_difficulty: u32,
) -> u64 {
// Enforced by the Soroban host: panics if the transaction does not carry
// a valid authorization for `owner`. This is the correct auth pattern.
owner.require_auth();
// Reject zero-byte commitment hash (Issue #40)
require_non_zero_commitment(&env, &commitment_hash);
// Reject duplicate commitment hash globally
require_unique_commitment(&env, &commitment_hash);
// Validate proof-of-work: commitment_hash must have `pow_difficulty` leading zero bits
require_pow(&env, &commitment_hash, pow_difficulty);
// NextId lives in persistent storage so it survives contract upgrades.
// Instance storage is wiped on upgrade, which would reset the counter
// and cause ID collisions with existing IP records.
// Initialize to 1 so the first IP ID is 1, not 0 (0 is ambiguous with "not found").
let id: u64 = env
.storage()
.persistent()
.get(&DataKey::NextId)
.unwrap_or(1);
let record = IpRecord {
ip_id: id,
owner: owner.clone(),
commitment_hash: commitment_hash.clone(),
timestamp: env.ledger().timestamp(),
revoked: false,
co_owners: Vec::new(&env),
parent_ip_id: None,
notary_signature: None,
expiry_timestamp: 0,
grace_period_seconds: 0,
};
env.storage()
.persistent()
.set(&DataKey::IpRecord(id), &record);
env.storage()
.persistent()
.extend_ttl(&DataKey::IpRecord(id), LEDGER_BUMP, LEDGER_BUMP);
// Store pow_difficulty for strength scoring (Issue: entropy/complexity scoring)
env.storage()
.persistent()
.set(&DataKey::IpPowDifficulty(id), &pow_difficulty);
env.storage().persistent().extend_ttl(
&DataKey::IpPowDifficulty(id),
LEDGER_BUMP,
LEDGER_BUMP,
);
// Append to owner index
let mut ids: Vec<u64> = env
.storage()
.persistent()
.get(&DataKey::OwnerIps(owner.clone()))
.unwrap_or(Vec::new(&env));
ids.push_back(id);
env.storage()
.persistent()
.set(&DataKey::OwnerIps(owner.clone()), &ids);
env.storage().persistent().extend_ttl(
&DataKey::OwnerIps(owner.clone()),
LEDGER_BUMP,
LEDGER_BUMP,
);
// Track commitment hash ownership and extend TTL
env.storage()
.persistent()
.set(&DataKey::CommitmentOwner(commitment_hash.clone()), &owner);
env.storage().persistent().extend_ttl(
&DataKey::CommitmentOwner(commitment_hash.clone()),
50000,
50000,
);
env.storage().persistent().set(&DataKey::NextId, &(id + 1));
env.storage()
.persistent()
.extend_ttl(&DataKey::NextId, LEDGER_BUMP, LEDGER_BUMP);
// Track commitment → owner mapping (for duplicate detection and transfer)
env.storage()
.persistent()
.set(&DataKey::CommitmentOwner(commitment_hash.clone()), &owner);
env.storage().persistent().extend_ttl(
&DataKey::CommitmentOwner(commitment_hash.clone()),
LEDGER_BUMP,
LEDGER_BUMP,
);
env.events().publish(
(symbol_short!("ip_commit"), owner.clone()),
(id, record.timestamp),
);
// Issue #436: Record immutable audit entry for commitment creation
Self::append_audit_entry(&env, id, symbol_short!("committed"), owner.clone());
// Issue #437: Assign IP to its shard
Self::assign_to_shard(&env, id, &commitment_hash);
// Issue #438: Store compressed commitment
Self::store_compressed_commitment(&env, id, &commitment_hash);
// Issue #346: Update commitment checksum for rollback protection
Self::update_commitment_checksum(&env);
// Adjust PoW difficulty based on daily commit volume
Self::adjust_pow_difficulty(&env);
// Issue #812: Mark cached Merkle root stale for this owner
Self::mark_merkle_root_stale(&env, &owner);
id
}
/// Commit multiple IP commitments in a single transaction.
///
/// This function allows batching multiple IP commitments, reducing gas costs
/// for users with multiple designs. Returns the assigned IP IDs in order.
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `owner` - The address that owns all the IPs. This address must authorize the transaction.
/// * `commitment_hashes` - A vector of 32-byte cryptographic hashes for the IP commitments.
/// Each must not be all zeros and must be unique across all registered IPs.
///
/// # Returns
///
/// A vector of unique IP IDs assigned to the commitments, in the same order as the input hashes.
///
/// # Panics
///
/// Panics if:
/// * The `owner` does not authorize the transaction (auth error)
/// * Any `commitment_hash` is all zeros (ZeroCommitmentHash error)
/// * Any `commitment_hash` is already registered (CommitmentAlreadyRegistered error)
///
/// # Auth Model
///
/// `owner.require_auth()` is called once for the batch operation.
pub fn batch_commit_ip(
env: Env,
owner: Address,
commitment_hashes: Vec<BytesN<32>>,
) -> Vec<u64> {
owner.require_auth();
let mut ids = Vec::new(&env);
let timestamp = env.ledger().timestamp();
for commitment_hash in commitment_hashes.iter() {
// Reject zero-byte commitment hash
require_non_zero_commitment(&env, &commitment_hash);
// Reject duplicate commitment hash globally
require_unique_commitment(&env, &commitment_hash);
// NextId lives in persistent storage so it survives contract upgrades.
let id: u64 = env
.storage()
.persistent()
.get(&DataKey::NextId)
.unwrap_or(1);
let record = IpRecord {
ip_id: id,
owner: owner.clone(),
commitment_hash: commitment_hash.clone(),
timestamp,
revoked: false,
co_owners: Vec::new(&env),
parent_ip_id: None,
notary_signature: None,
expiry_timestamp: 0,
grace_period_seconds: 0,
};
env.storage()
.persistent()
.set(&DataKey::IpRecord(id), &record);
env.storage()
.persistent()
.extend_ttl(&DataKey::IpRecord(id), LEDGER_BUMP, LEDGER_BUMP);
// Append to owner index
let mut owner_ids: Vec<u64> = env
.storage()
.persistent()
.get(&DataKey::OwnerIps(owner.clone()))
.unwrap_or(Vec::new(&env));
owner_ids.push_back(id);
env.storage()
.persistent()
.set(&DataKey::OwnerIps(owner.clone()), &owner_ids);
env.storage().persistent().extend_ttl(
&DataKey::OwnerIps(owner.clone()),
LEDGER_BUMP,
LEDGER_BUMP,
);
// Track commitment hash ownership
env.storage()
.persistent()
.set(&DataKey::CommitmentOwner(commitment_hash.clone()), &owner);
env.storage().persistent().extend_ttl(
&DataKey::CommitmentOwner(commitment_hash.clone()),
50000,
50000,
);
env.events()
.publish((symbol_short!("ip_commit"), owner.clone()), (id, timestamp));
ids.push_back(id);
env.storage().persistent().set(&DataKey::NextId, &(id + 1));
env.storage()
.persistent()
.extend_ttl(&DataKey::NextId, LEDGER_BUMP, LEDGER_BUMP);
}
// Issue #346: Update commitment checksum for rollback protection
Self::update_commitment_checksum(&env);
ids
}
/// Commit multiple IP commitments anonymously in a single transaction.
///
/// Stores a blinded owner identifier alongside each commitment so ownership
/// can be proven off-chain or revealed later without exposing the on-chain
/// owner address at commit time. The on-chain `IpRecord.owner` is set to
/// the contract address as a placeholder to avoid leaking the submitter.
///
/// # Arguments
///
/// * `env` - The Soroban environment
/// * `blinded_owner` - A 32-byte blinded owner identifier (e.g. `sha256(owner || nonce)`).
/// Stored on-chain per commitment so ownership can be proved or revealed later.
/// * `commitment_hashes` - Non-empty vector of 32-byte commitment hashes to register.
/// Each must not be all zeros and must be globally unique.
///
/// # Returns
///
/// `Vec<u64>` — Assigned IP IDs in the same order as the input hashes.
///
/// # Panics
///
/// Panics if:
/// * `commitment_hashes` is empty (panics with `ZeroCommitmentHash` on the first iteration
/// — callers should not pass an empty vector)
/// * Any `commitment_hash` is all zeros (`ZeroCommitmentHash` error, code 2)
/// * Any `commitment_hash` is already registered (`CommitmentAlreadyRegistered` error, code 3)
///
/// # Auth Model
///
/// No caller authorization is required. The submitter's identity is intentionally
/// not recorded on-chain; only the `blinded_owner` identifier is stored.
///