-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPetDIDRegistry.sol
More file actions
454 lines (375 loc) · 13.3 KB
/
Copy pathPetDIDRegistry.sol
File metadata and controls
454 lines (375 loc) · 13.3 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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
/**
* @title PetDIDRegistry
* @notice Pet Digital Identity Registry with biometric-based DID
* @dev Optimized for Hyperledger Besu private network
* @author DogCatPaw Team
*/
contract PetDIDRegistry is AccessControl, ReentrancyGuard {
using ECDSA for bytes32;
using MessageHashUtils for bytes32;
// ==================== Roles ====================
bytes32 public constant MODEL_SERVER_ROLE = keccak256("MODEL_SERVER_ROLE");
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
bytes32 public constant SHELTER_ROLE = keccak256("SHELTER_ROLE");
// ==================== Structs ====================
struct DIDDocument {
address biometricOwner;
address controller;
uint48 created;
uint48 updated;
bool exists;
}
struct BiometricData {
bytes32 featureVectorHash;
string modelServerReference;
uint8 sampleCount;
uint48 registrationTime;
}
struct VerificationRecord {
address verifier;
uint48 timestamp;
uint8 similarity;
uint8 purpose;
}
struct CredentialMetadata {
bytes32 credentialHash;
address issuer;
address subject;
uint48 issuanceDate;
uint48 expirationDate;
bool revoked;
}
// ==================== Storage ====================
mapping(bytes32 => DIDDocument) private identities;
mapping(bytes32 => BiometricData) private biometricData;
mapping(bytes32 => VerificationRecord[]) private verificationHistory;
mapping(bytes32 => CredentialMetadata) public credentials;
mapping(string => bytes32) private didToIdentity;
mapping(bytes32 => string) private identityToDID;
mapping(address => string[]) private controllerPets;
uint256 private totalPets;
// ==================== Events ====================
event DIDCreated(
string indexed petDID,
bytes32 indexed identity,
address indexed biometricOwner,
address controller
);
event BiometricVerified(
string indexed petDID,
address indexed verifier,
uint8 similarity,
uint8 purpose
);
event CredentialIssued(
bytes32 indexed credentialHash,
string credentialType,
address indexed issuer,
address indexed subject
);
event CredentialRevoked(
bytes32 indexed credentialHash,
address indexed revoker
);
event ControllerChanged(
string indexed petDID,
address indexed oldController,
address indexed newController
);
event EmergencyAccessed(
string indexed petDID,
address indexed accessor,
string location
);
// ==================== Errors ====================
error InvalidDIDFormat();
error DIDAlreadyExists();
error DIDNotFound();
error Unauthorized();
error InvalidSimilarity();
error InvalidServerSignature();
error CredentialAlreadyExists();
error CredentialNotFound();
error CredentialAlreadyRevoked();
error InvalidHexCharacter();
// ==================== Constructor ====================
constructor() {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
// ==================== Core Functions ====================
function registerPetDID(
string calldata _petDID,
bytes32 _featureVectorHash,
string calldata _modelServerReference,
uint8 _sampleCount,
string calldata _species,
string calldata _metadataURI
) external nonReentrant {
if (bytes(_petDID).length == 0) revert InvalidDIDFormat();
if (didToIdentity[_petDID] != bytes32(0)) revert DIDAlreadyExists();
if (_sampleCount < 1 || _sampleCount > 2) revert InvalidSimilarity();
address biometricAddress = extractBiometricAddress(_petDID);
bytes32 identity = keccak256(abi.encodePacked(biometricAddress));
identities[identity] = DIDDocument({
biometricOwner: biometricAddress,
controller: msg.sender,
created: uint48(block.timestamp),
updated: uint48(block.timestamp),
exists: true
});
biometricData[identity] = BiometricData({
featureVectorHash: _featureVectorHash,
modelServerReference: _modelServerReference,
sampleCount: _sampleCount,
registrationTime: uint48(block.timestamp)
});
didToIdentity[_petDID] = identity;
identityToDID[identity] = _petDID;
controllerPets[msg.sender].push(_petDID);
unchecked {
++totalPets;
}
emit DIDCreated(_petDID, identity, biometricAddress, msg.sender);
}
function verifyBiometric(
string calldata _petDID,
uint8 _similarity,
uint8 _purpose,
bytes calldata _modelServerSignature
) external returns (bool) {
bytes32 identity = didToIdentity[_petDID];
if (identity == bytes32(0)) revert DIDNotFound();
if (_similarity < 85 || _similarity > 100) revert InvalidSimilarity();
bytes32 messageHash = keccak256(
abi.encodePacked(_petDID, _similarity, _purpose, block.timestamp)
);
address signer = messageHash.toEthSignedMessageHash().recover(_modelServerSignature);
if (!hasRole(MODEL_SERVER_ROLE, signer)) revert InvalidServerSignature();
verificationHistory[identity].push(VerificationRecord({
verifier: msg.sender,
timestamp: uint48(block.timestamp),
similarity: _similarity,
purpose: _purpose
}));
emit BiometricVerified(_petDID, msg.sender, _similarity, _purpose);
return true;
}
function registerCredential(
bytes32 _credentialHash,
string calldata _credentialType,
address _subject,
uint48 _expirationDate
) external {
if (credentials[_credentialHash].issuanceDate != 0) {
revert CredentialAlreadyExists();
}
credentials[_credentialHash] = CredentialMetadata({
credentialHash: _credentialHash,
issuer: msg.sender,
subject: _subject,
issuanceDate: uint48(block.timestamp),
expirationDate: _expirationDate,
revoked: false
});
emit CredentialIssued(_credentialHash, _credentialType, msg.sender, _subject);
}
function revokeCredential(bytes32 _credentialHash) external {
CredentialMetadata storage cred = credentials[_credentialHash];
if (cred.issuanceDate == 0) revert CredentialNotFound();
if (cred.issuer != msg.sender) revert Unauthorized();
if (cred.revoked) revert CredentialAlreadyRevoked();
cred.revoked = true;
emit CredentialRevoked(_credentialHash, msg.sender);
}
function changeController(
string calldata _petDID,
address _newController
) external {
bytes32 identity = didToIdentity[_petDID];
DIDDocument storage doc = identities[identity];
if (!doc.exists) revert DIDNotFound();
if (doc.controller != msg.sender) revert Unauthorized();
address oldController = doc.controller;
doc.controller = _newController;
doc.updated = uint48(block.timestamp);
removePetFromController(oldController, _petDID);
controllerPets[_newController].push(_petDID);
emit ControllerChanged(_petDID, oldController, _newController);
}
function logEmergencyAccess(
string calldata _petDID,
string calldata _location
) external {
bytes32 identity = didToIdentity[_petDID];
if (identity == bytes32(0)) revert DIDNotFound();
emit EmergencyAccessed(_petDID, msg.sender, _location);
}
// ==================== View Functions ====================
function getDIDDocument(string calldata _petDID)
external
view
returns (
address biometricOwner,
address controller,
uint48 created,
uint48 updated,
bool exists
)
{
bytes32 identity = didToIdentity[_petDID];
DIDDocument storage doc = identities[identity];
return (
doc.biometricOwner,
doc.controller,
doc.created,
doc.updated,
doc.exists
);
}
function getBiometricData(string calldata _petDID)
external
view
returns (
bytes32 featureVectorHash,
string memory modelServerReference,
uint8 sampleCount,
uint48 registrationTime
)
{
bytes32 identity = didToIdentity[_petDID];
BiometricData storage data = biometricData[identity];
return (
data.featureVectorHash,
data.modelServerReference,
data.sampleCount,
data.registrationTime
);
}
function getVerificationHistory(string calldata _petDID)
external
view
returns (VerificationRecord[] memory)
{
bytes32 identity = didToIdentity[_petDID];
return verificationHistory[identity];
}
function isCredentialValid(bytes32 _credentialHash)
external
view
returns (bool)
{
CredentialMetadata storage cred = credentials[_credentialHash];
if (cred.issuanceDate == 0) return false;
if (cred.revoked) return false;
if (cred.expirationDate > 0 && block.timestamp > cred.expirationDate) {
return false;
}
return true;
}
function isAuthorizedGuardian(string calldata _petDID, address _guardian)
external
view
returns (bool)
{
bytes32 identity = didToIdentity[_petDID];
return identities[identity].controller == _guardian;
}
function getPetsByController(address _controller)
external
view
returns (string[] memory)
{
return controllerPets[_controller];
}
function getTotalPets() external view returns (uint256) {
return totalPets;
}
function getIdentityFromDID(string calldata _petDID)
external
view
returns (bytes32)
{
return didToIdentity[_petDID];
}
function getDIDFromIdentity(bytes32 _identity)
external
view
returns (string memory)
{
return identityToDID[_identity];
}
// ==================== Internal Functions ====================
function extractBiometricAddress(string calldata _did)
internal
pure
returns (address)
{
bytes memory didBytes = bytes(_did);
if (didBytes.length < 56) revert InvalidDIDFormat();
bytes memory hexStr = new bytes(40);
uint256 startIdx = 16;
for (uint256 i = 0; i < 40; i++) {
hexStr[i] = didBytes[startIdx + i];
}
return hexStringToAddress(string(hexStr));
}
function hexStringToAddress(string memory _hexStr)
internal
pure
returns (address)
{
bytes memory hexBytes = bytes(_hexStr);
if (hexBytes.length != 40) revert InvalidDIDFormat();
uint160 result = 0;
for (uint256 i = 0; i < 40; i++) {
result = result * 16 + hexCharToUint8(hexBytes[i]);
}
return address(result);
}
function hexCharToUint8(bytes1 _char) internal pure returns (uint8) {
uint8 c = uint8(_char);
if (c >= 48 && c <= 57) return c - 48;
if (c >= 65 && c <= 70) return c - 55;
if (c >= 97 && c <= 102) return c - 87;
revert InvalidHexCharacter();
}
function removePetFromController(address _controller, string calldata _petDID)
internal
{
string[] storage pets = controllerPets[_controller];
uint256 length = pets.length;
for (uint256 i = 0; i < length; ) {
if (keccak256(bytes(pets[i])) == keccak256(bytes(_petDID))) {
pets[i] = pets[length - 1];
pets.pop();
break;
}
unchecked { ++i; }
}
}
// ==================== Admin Functions ====================
function grantModelServerRole(address _server)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_grantRole(MODEL_SERVER_ROLE, _server);
}
function grantGuardianRole(address _guardian)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_grantRole(GUARDIAN_ROLE, _guardian);
}
function grantShelterRole(address _shelter)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_grantRole(SHELTER_ROLE, _shelter);
}
}