Sidetree(ION)プロトコルリサーチ

###### tags: `DID`

# Sidetree / ION 

## Terminology

いくつかピックアップ。

| Term | Description |
| -------- | -------- |
| Anchoring System | A decentralized sequencing oracle (e.g. Bitcoin, Ethereum, distributed ledgers, witness-based approaches)|
| CAS | Content-addressable storage protocol/network (e.g. IPFS) |
| DID Suffix | The unique identifier string within a DID URI. e.g. The unique suffix of did:sidetree:123 would be 123. |
| Multihash | Protocol for differentiating outputs from common cryptographic hash functions, addressing size and encoding considerations: https://multiformats.io/multihash/ |
| DID Operation | Set of delta-based CRDT patches that modify a DID’s state data when applied. |
| Commitment | A cryptographic primative that allows one to commit to a chosen value, known as the commit value resulting in the generation of a commitment. A commitment can then be shared without revealing the commit value forming a proof of commitment where the possessor of the commit value can then later reveal the commit value proving the original commitment. |


## Multihash
https://multiformats.io/multihash/
Multihashは、様々な定評のあるハッシュ関数の出力を区別するためのプロトコルである。TLV(Type-Length_Value)フォーマットにより、ハッシュ値の管理がしやすくなる。

![](https://i.imgur.com/CwVr39L.png)

## Default Parameters



| Column 1 | Column 2 | Column 3 |
| -------- | -------- | -------- |
| HASH_ALGORITHM | Algorithm for generating hashes of protocol-related values. | SHA256 | 
| JSON_CANONICALIZATION_SCHEME | The scheme selected for canonicalizing JSON structures used throughout the specification. | [JCS](https://datatracker.ietf.org/doc/html/draft-rundgren-json-canonicalization-scheme-17) |
| CAS_PROTOCOL | The CAS network protocol used within an implementation. | IPFS |

## Common Functions

### Hashing Process

1. Generate a hash of the data value using the HASH_PROTOCOL with the HASH_ALGORITHM.
2. Encode the resulting output using the DATA_ENCODING_SCHEME.
3. Return the encoded hashing output.

```typescript=
let HashingOutput = Base64URL( Multihash(DATA, 0x12) );
```

## Network Topology

![](https://i.imgur.com/13UgXGw.png)
1. The underlying anchoring system that serves as the global anchoring and linear sequencing system for DID operations.
2. The Sidetree nodes themselves, which interact with the anchoring system to anchor operations, fetch and replicate data from the CAS network, and process operations in accordance with the protocol deterministic ruleset.
3. An integrated Content-Addressable Storage (CAS) network layer Sidetree nodes use to distribute and replicate DID operation files.

## File Structure
DIDオペレーションデータファイルを扱う。

![](https://i.imgur.com/OwLgaoP.png)



### Core Index File 

```json=
{
  "coreProofFileUri": CAS_URI,
  "provisionalIndexFileUri": CAS_URI,
  "writerLockId": OPTIONAL_LOCKING_VALUE,
  "operations": {
    "create": [
      {
        "suffixData": {
          "type": TYPE_STRING,
          "deltaHash": DELTA_HASH,
          "recoveryCommitment": COMMITMENT_HASH
        }
      },
      {...}
    ],
    "recover": [
      {
        "didSuffix": SUFFIX_STRING,
        "revealValue": MULTIHASH_OF_JWK
      },
      {...}
    ],
    "deactivate": [
      {
        "didSuffix": SUFFIX_STRING,
        "revealValue": MULTIHASH_OF_JWK
      },
      {...}
    ]
  }
}
```

### Core Proof File

Core Index Fileに紐づいた現在の、Recovery、Deactive操作における署名やハッシュなどの暗号学的な証明を含んだファイル。
```json=
{
  "operations": {
    "recover": [
      {
        "signedData": {
          "protected": {...},
          "payload": {
            "recoveryCommitment": COMMITMENT_HASH,
            "recoveryKey": JWK_OBJECT,
            "deltaHash": DELTA_HASH
          },
          "signature": SIGNATURE_STRING
        }
      },
      {...}
    ],
    "deactivate": [
      {
        "signedData": {
          "protected": {...},
          "payload": {
            "didSuffix": SUFFIX_STRING,
            "recoveryKey": JWK_OBJECT
          },
          "signature": SIGNATURE_STRING
        }
      },
      {...}
    ]
  }
}
```

### Provisional Index File

Update操作における署名やハッシュなどの暗号学的な証明を含んだファイル。
```json=
{
  "operations": {
    "update": [
      {
        "signedData": {
          "protected": {...},
          "payload": {
            "updateKey": JWK_OBJECT,
            "deltaHash": DELTA_HASH
          },
          "signature": SIGNATURE_STRING
        }
      },
      {...}
    ]
  }
}
```


### Chunk Files


```json=
{
  "deltas": [
       
    {
      "patches": PATCH_ARRAY,
      "updateCommitment": COMMITMENT_HASH
    },
    ...
  ]
}
```

## DID URI Composition


```
did:METHOD:<did-suffix>
```
Example:
```
did:sidetree:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A
```

## JSON Web Signatures

#### Signing

Sidetreeは、DID操作の認証と完全性の保護のためにJSON Web Signaturesに依存している。
```json=
{
  "kid": "did:example:123#_Qq0UL2Fq651Q0Fjd6TvnYE-faHiOpRlPVQcY_-tA4A",
  "alg": "EdDSA"
}
```

#### Verifying

一般的なJWSを検証するプロセスを用いる。

Operationの検証には各Operationに対応したキーペアを用いる。

## DID Operations

DID Operationを操作の単位として定義してる。

ほとんどのDID所有者はアンカリングを自ら行うわけではない。基本的にはOperationの値を外部ノードに送信しアンカリングするのが一般的。署名により偽造はできないのでこの方法は安全。しかし、アンカリングしない攻撃の可能性は残る。オーナーはブロックを監視することでこれを検知可能で、別のノードへ送信する、もしくは自分で行うことで解決できる。

### Create

1. Generate Update Key Pair
2. Generate Update Key Pair Commitment
```json=
{
  "patches": [ PATCH_1, PATCH_2, ... ],
  "updateCommitment": COMMITMENT_HASH
}
```
3. Generate Recovery Key Pair
4. Generate Recovery Key Pair Commitment
```json=
{
  "type": TYPE_STRING,
  "deltaHash": DELTA_HASH,
  "recoveryCommitment": COMMITMENT_HASH,
  "anchorOrigin": ANCHOR_ORIGIN
}
```

### Update

1. Retrieve the Update Reveal Value that matches the previously anchored Update Commitment.
```json=
{
  "patches": [ PATCH_1, PATCH_2, ... ],
  "updateCommitment": COMMITMENT_HASH
}
```
2. Update Keyを用いて署名を生成する。
```json=
{
  "protected": {...},
  "payload": {
    "updateKey": JWK_OBJECT,
    "deltaHash": DELTA_HASH
  },
  "signature": SIGNATURE_STRING
}
```

Recover, Deactiveも基本同じなので省略。

## DID State Patches

Patch Actionの標準的なフォーマットを規程している。

標準的なパッチアクションタイプは以下。
- `add-public-keys`
- `remove-public-keys`
- `add-services`
- `remove-services`
- `ietf-json-patch`
`-custom-action`を付けることでカスタムのpatchも定義できる。

### add-public-keys

鍵の追加のpatch。

```json=
{
  "action": "add-public-keys",
  "publicKeys": [
    {
      "id": "key1",
      "purposes": ["authentication"],
      "type": "EcdsaSecp256k1VerificationKey2019",
      "publicKeyJwk": {...}
    }
  ]
}
```

### remove-public-keys

DIDに関連する暗号鍵の削除を行う。
```json=
{
  "action": "remove-public-keys",
  "ids": ["key1", "key2"]
}
```

add-services, remove-servicesも同様なので省略。


## Transaction & Operation Processing

### Transaction Anchoring
コア・インデックス・ファイルへの参照をターゲット・アンカー・システム内に埋め込む

1. Generate a numerical string ('732') that represents the total number of operations present in the Core Index File and Provisional Index File, herein referred to as the Operation Count.
2.  generate a CID for the Core Index File, herein referred to as the Core Index File CAS URI.
3. Join the Operation Count and Core Index File CAS URI with a . as follows:
```
"10000" + "." + "QmWd5PH6vyRH5kMdzZRPBnf952dbR4av3Bd7B2wBqMaAcf"
```
4. 値をトランザクションに埋め込み手数料を付与したのちブロードキャストする

## DID Resolver Output


```json=
"didDocumentMetadata": {
  "deactivated": true,
  "canonicalId": "did:sidetree:EiDyOQbbZAa3aiRzeCkV7LOx3SERjjH93EXoIM3UoN4oWg",
  "equivalentId": ["did:sidetree:EiDyOQbbZAa3aiRzeCkV7LOx3SERjjH93EXoIM3UoN4oWg"],
  "method": {
    "published": true,
    "recoveryCommitment": "EiBfOZdMtU6OBw8Pk879QtZ-2J-9FbbjSZyoaA_bqD4zhA",
    "updateCommitment": "EiDOrcmPtfMHuwIWN6YoihdeIPxOKDHy3D6sdMXu_7CN0w"
  }
}
```
## Sidetree REST API
Document:
https://identity.foundation/sidetree/api/
Swagger:
https://identity.foundation/sidetree/swagger/#/Sidetree/writeSidetreeOperation

## ION

Create Operationの作成のためION唯一のCLI操作。
```
ion operation create
```
Recovery, 署名用の秘密鍵を生成し、create operationの雛形?を生成してくれる。
```
DID: did:ion:EiB5F_Xnq4kce4NrLcRyBka80j7pjv-6VOMLjvlD2akaZQ
Recovery private key saved as: EiB5F_Xnq4kce4NrLcRyBka80j7pjv-6VOMLjvlD2akaZQ-RecoveryPrivateKey.json
Siging private key saved as: EiB5F_Xnq4kce4NrLcRyBka80j7pjv-6VOMLjvlD2akaZQ-SigningPrivateKey.json
Create request body:
{
  "type": "create",
  "suffixData": {
    "deltaHash": "EiCxv8SvCSTAXLVUjxWBpA00SE5gC03Zy7sTVikwN-E1Mw",
    "recoveryCommitment": "EiC7c2OaUQzEwHl2yIzdM3Q7-KTa-Dz4KHVvMoqFwfAi9A"
  },
  "delta": {
    "updateCommitment": "EiAsgr1H9RC4Z6N7s7THsAiGJ_w2s0RddtSCLeu5aVH_jg",
    "patches": [
      {
        "action": "replace",
        "document": {
          "publicKeys": [
            {
              "id": "signingKey",
              "type": "EcdsaSecp256k1VerificationKey2019",
              "publicKeyJwk": {
                "kty": "EC",
                "crv": "secp256k1",
                "x": "9lyeJxTw308yrezgfwRIJpD0yThfHoWtrfzVtX_Uxvc",
                "y": "4whWUiYXhPSCNXYFAORqMZMC3hvLJMV0q_xV6tRqd5U"
              },
              "purposes": [
                "authentication",
                "assertionMethod",
                "capabilityInvocation",
                "capabilityDelegation",
                "keyAgreement"
              ]
            }
          ],
          "services": [
            {
              "id": "serviceId123",
              "type": "someType",
              "serviceEndpoint": "https://www.url.com"
            }
          ]
        }
      }
    ]
  }
}
Decoded suffix data:
{
  deltaHash: 'EiCxv8SvCSTAXLVUjxWBpA00SE5gC03Zy7sTVikwN-E1Mw',
  recoveryCommitment: 'EiC7c2OaUQzEwHl2yIzdM3Q7-KTa-Dz4KHVvMoqFwfAi9A'
}
Decoded delta:
{
  updateCommitment: 'EiAsgr1H9RC4Z6N7s7THsAiGJ_w2s0RddtSCLeu5aVH_jg',
  patches: [ { action: 'replace', document: [Object] } ]
}
```
これに編集を加え`POST /operations`すると[Operation Handler]()がdeltaをデコードしcreate処理を実行

- ファイルの生成・取得をREST APIではし難いから?
- 秘密鍵管理をカストディアルにしないための工夫?
- create Operation編集していい？
    - did suffix変わらない？

### その後の操作方法

[ION Tools](https://github.com/decentralized-identity/ion-tools#ionjs)
[ion-sdk](https://github.com/decentralized-identity/ion-sdk)


## その他の実装
Element
- Ethereum上に実現したSidetreeの実装
- Sidetree.jsを用いて実装されている


## 参考文献
https://identity.foundation/sidetree/spec/