# DID 기반 신원 구조 구체 설계

## DID (Decentralized Identifier) 기본 구조

### 로빙 에이전트 DID 형식

```
did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b
│   │        │       │     └─ 고유 식별자 (16자리 hex)
│   │        │       └─────── 엔티티 타입 (agent/user/skill)
│   │        └─────────────── 네트워크 (mainnet/testnet)
│   └──────────────────────── 메소드 (robeing)
└──────────────────────────── DID 스키마
```

### DID Document 구조

```json
{
  "@context": [
    "https://www.w3.org/ns/did/v1",
    "https://robeing.ai/ns/did/v1"
  ],
  "id": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b",
  "created": "2025-08-18T10:00:00Z",
  "updated": "2025-08-18T14:30:00Z",
  
  "verificationMethod": [
    {
      "id": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b#keys-1",
      "type": "Ed25519VerificationKey2020",
      "controller": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b",
      "publicKeyMultibase": "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
    }
  ],
  
  "authentication": [
    "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b#keys-1"
  ],
  
  "assertionMethod": [
    "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b#keys-1"
  ],
  
  "service": [
    {
      "id": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b#api",
      "type": "AgentAPI",
      "serviceEndpoint": "https://api.robeing.ai/agents/8f4b2c3a9e1d7f6b"
    },
    {
      "id": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b#messaging",
      "type": "MessagingService",
      "serviceEndpoint": "wss://msg.robeing.ai/agents/8f4b2c3a9e1d7f6b"
    }
  ],
  
  "robeingMetadata": {
    "agentLevel": 15,
    "reputation": 0.92,
    "specializations": ["data_analysis", "communication"],
    "owner": "did:robeing:mainnet:user:1a2b3c4d5e6f7g8h"
  }
}
```

## DID 레지스트리 구현

### 블록체인 기반 레지스트리

```python
class DIDRegistry:
    def __init__(self):
        self.blockchain = BlockchainInterface()
        self.ipfs = IPFSInterface()
        
    async def register_did(self, agent_info):
        """새로운 DID 등록"""
        
        # 1. DID 생성
        did = self.generate_did(agent_info)
        
        # 2. 키 쌍 생성
        key_pair = self.generate_key_pair()
        
        # 3. DID Document 생성
        did_document = {
            "@context": ["https://www.w3.org/ns/did/v1"],
            "id": did,
            "created": datetime.now().isoformat(),
            "verificationMethod": [{
                "id": f"{did}#keys-1",
                "type": "Ed25519VerificationKey2020",
                "controller": did,
                "publicKeyMultibase": key_pair['public']
            }],
            "authentication": [f"{did}#keys-1"]
        }
        
        # 4. IPFS에 Document 저장
        ipfs_hash = await self.ipfs.add(did_document)
        
        # 5. 블록체인에 레지스트리 등록
        tx_hash = await self.blockchain.register_did(did, ipfs_hash)
        
        return {
            'did': did,
            'document_hash': ipfs_hash,
            'transaction': tx_hash,
            'private_key': key_pair['private']
        }
    
    async def resolve_did(self, did):
        """DID 해석"""
        
        # 1. 블록체인에서 IPFS 해시 조회
        ipfs_hash = await self.blockchain.get_did_hash(did)
        
        # 2. IPFS에서 Document 가져오기
        did_document = await self.ipfs.get(ipfs_hash)
        
        # 3. 유효성 검증
        if self.validate_did_document(did_document):
            return did_document
        else:
            raise ValueError("Invalid DID Document")
```

## Verifiable Credentials (VC)

### 에이전트 자격증명 시스템

```python
class VerifiableCredential:
    def __init__(self):
        self.credential_types = [
            'SkillCertification',
            'ReputationScore',
            'LevelAchievement',
            'TrustEndorsement'
        ]
    
    def issue_credential(self, subject_did, credential_type, claims):
        """자격증명 발급"""
        
        credential = {
            "@context": [
                "https://www.w3.org/2018/credentials/v1",
                "https://robeing.ai/credentials/v1"
            ],
            "id": f"urn:uuid:{uuid.uuid4()}",
            "type": ["VerifiableCredential", credential_type],
            "issuer": "did:robeing:mainnet:system:issuer",
            "issuanceDate": datetime.now().isoformat(),
            "credentialSubject": {
                "id": subject_did,
                **claims
            }
        }
        
        # 서명 추가
        proof = self.create_proof(credential)
        credential['proof'] = proof
        
        return credential
    
    def create_proof(self, credential):
        """증명 생성"""
        
        return {
            "type": "Ed25519Signature2020",
            "created": datetime.now().isoformat(),
            "verificationMethod": "did:robeing:mainnet:system:issuer#keys-1",
            "proofPurpose": "assertionMethod",
            "jws": self.sign_credential(credential)
        }
```

### 스킬 인증 VC 예시

```json
{
  "@context": [
    "https://www.w3.org/2018/credentials/v1",
    "https://robeing.ai/credentials/v1"
  ],
  "id": "urn:uuid:3978344-8596-4c20-b6e1-7a7b8e9c3d2a",
  "type": ["VerifiableCredential", "SkillCertification"],
  "issuer": "did:robeing:mainnet:system:skill_authority",
  "issuanceDate": "2025-08-18T10:00:00Z",
  "expirationDate": "2026-08-18T10:00:00Z",
  
  "credentialSubject": {
    "id": "did:robeing:mainnet:agent:8f4b2c3a9e1d7f6b",
    "skill": {
      "name": "Advanced Data Analysis",
      "level": "Expert",
      "score": 95,
      "validatedBy": "automated_testing",
      "testResults": {
        "accuracy": 0.98,
        "speed": "2.3x baseline",
        "complexity": "handles nested datasets"
      }
    }
  },
  
  "proof": {
    "type": "Ed25519Signature2020",
    "created": "2025-08-18T10:00:00Z",
    "verificationMethod": "did:robeing:mainnet:system:skill_authority#keys-1",
    "proofPurpose": "assertionMethod",
    "jws": "eyJhbGciOiJFZERTQSIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..."
  }
}
```

## Zero-Knowledge Proofs

### 프라이버시 보호 신원 증명

```python
class ZeroKnowledgeIdentity:
    def __init__(self):
        self.zk_circuit = self.setup_circuit()
        
    def prove_attribute_without_revealing(self, attribute, threshold):
        """속성을 공개하지 않고 증명"""
        
        # 예: 레벨이 10 이상임을 레벨 값을 공개하지 않고 증명
        
        # 1. Commitment 생성
        commitment = self.create_commitment(attribute)
        
        # 2. ZK Proof 생성
        proof = self.generate_zk_proof(
            statement=f"level >= {threshold}",
            witness=attribute,
            commitment=commitment
        )
        
        return {
            'commitment': commitment,
            'proof': proof,
            'statement': f"attribute >= {threshold}"
        }
    
    def verify_zk_proof(self, commitment, proof, statement):
        """영지식 증명 검증"""
        
        return self.zk_circuit.verify(commitment, proof, statement)
```

## DID 기반 접근 제어

### 능력 기반 접근 제어 (ABAC)

```python
class DIDAccessControl:
    def __init__(self):
        self.policies = {}
        
    def create_access_policy(self, resource, requirements):
        """접근 정책 생성"""
        
        policy = {
            'resource': resource,
            'requirements': requirements,
            'created': datetime.now(),
            'rules': []
        }
        
        # DID 기반 규칙 추가
        for req in requirements:
            if req['type'] == 'credential':
                policy['rules'].append({
                    'type': 'require_credential',
                    'credential_type': req['credential_type'],
                    'minimum_value': req.get('minimum_value')
                })
            elif req['type'] == 'did_attribute':
                policy['rules'].append({
                    'type': 'check_did_attribute',
                    'attribute': req['attribute'],
                    'condition': req['condition']
                })
        
        return policy
    
    async def authorize_access(self, did, resource):
        """DID 기반 접근 권한 확인"""
        
        # 1. DID Document 조회
        did_doc = await self.resolve_did(did)
        
        # 2. Verifiable Credentials 조회
        credentials = await self.get_credentials(did)
        
        # 3. 정책 확인
        policy = self.policies.get(resource)
        
        if not policy:
            return False, "No policy defined"
        
        # 4. 규칙 평가
        for rule in policy['rules']:
            if not self.evaluate_rule(rule, did_doc, credentials):
                return False, f"Failed rule: {rule['type']}"
        
        return True, "Access granted"
```

## DID 복구 메커니즘

### 소셜 복구 시스템

```python
class DIDRecovery:
    def __init__(self):
        self.recovery_threshold = 3  # 3 of 5 가디언 필요
        
    def setup_recovery(self, did, guardians):
        """복구 설정"""
        
        recovery_config = {
            'did': did,
            'guardians': guardians,
            'threshold': self.recovery_threshold,
            'shares': []
        }
        
        # Shamir's Secret Sharing으로 키 분할
        private_key = self.get_private_key(did)
        shares = self.split_secret(private_key, len(guardians), self.recovery_threshold)
        
        # 각 가디언에게 share 전달
        for guardian, share in zip(guardians, shares):
            encrypted_share = self.encrypt_for_guardian(share, guardian)
            recovery_config['shares'].append({
                'guardian': guardian,
                'encrypted_share': encrypted_share
            })
        
        return recovery_config
    
    def recover_did(self, did, guardian_shares):
        """DID 복구"""
        
        if len(guardian_shares) < self.recovery_threshold:
            raise ValueError("Insufficient guardian shares")
        
        # 키 복원
        recovered_key = self.reconstruct_secret(guardian_shares)
        
        # 새로운 DID Document 생성
        new_did_doc = self.create_recovery_document(did, recovered_key)
        
        # 블록체인에 업데이트
        self.update_did_registry(did, new_did_doc)
        
        return new_did_doc
```

## DID 연합 (Federation)

### 크로스체인 DID 연동

```python
class DIDFederation:
    def __init__(self):
        self.supported_chains = ['ethereum', 'polygon', 'solana']
        
    async def federate_did(self, source_did, target_chain):
        """DID를 다른 체인으로 연합"""
        
        # 1. 소스 체인에서 DID Document 가져오기
        source_doc = await self.resolve_did(source_did)
        
        # 2. 타겟 체인용 DID 생성
        target_did = self.create_federated_did(source_did, target_chain)
        
        # 3. 연합 증명 생성
        federation_proof = {
            'source': source_did,
            'target': target_did,
            'timestamp': datetime.now().isoformat(),
            'signature': self.sign_federation(source_did, target_did)
        }
        
        # 4. 타겟 체인에 등록
        await self.register_on_chain(target_chain, target_did, federation_proof)
        
        return {
            'federated_did': target_did,
            'proof': federation_proof
        }
```