クイックスタート: Python 用 Microsoft Azure Confidential Ledger クライアント ライブラリ

Python 用 Microsoft Azure Confidential Ledger クライアント ライブラリを使ってみます。 この記事の手順に従ってパッケージをインストールし、基本タスクのコード例を試します。

Microsoft Azure Confidential Ledger は、機密データ レコードを管理するための、安全性の高い新しいサービスです。 Azure confidential ledger は、許可型ブロックチェーン モデルに基づき、不変性 (台帳を追加専用にする) や改ざん防止 (すべてのレコードをそのまま保持する) など、独自のデータ整合性の利点を提供します。

Azure サブスクリプションをお持ちでない場合は、開始する前に Azure 無料アカウントを作成してください。

API のリファレンスのドキュメント | ライブラリーのソース コード | パッケージ (Python Package Index) 管理ライブラリー| パッケージ (Python Package Index) クライアント ライブラリー

前提条件

設定

このクイックスタートでは、Azure ID ライブラリを Azure CLI または Azure PowerShell と共に使用して、Azure サービスに対するユーザーの認証を行います。 また、開発者は、Visual Studio または Visual Studio Code を使用して自分の呼び出しを認証することもできます。 詳細については、Azure ID クライアント ライブラリを使用したクライアントの認証に関するページを参照してください。

Azure へのサインイン

Azure CLI az login コマンドまたは Azure PowerShell Connect-AzAccount コマンドレットを使用して Azure にサインインします。

az login

CLI または PowerShell で既定のブラウザーを開くことができる場合、ブラウザが開き、Azure サインイン ページが読み込まれます。 そうでない場合は、https://aka.ms/devicelogin を開き、ターミナルに表示されている認証コードを入力します。

メッセージが表示されたら、ブラウザーでアカウントの資格情報を使用してサインインします。

パッケージのインストール

ターミナルまたはコマンド プロンプトで、適切なプロジェクト フォルダーを作成したら、「Python 仮想環境を使用する」で説明されているように、Python 仮想環境を作成し、アクティブ化します。

次の Microsoft Entra ID クライアント ライブラリ パッケージをインストールします。

pip install azure-identity

Azure Confidential Ledger コントロール プレーン クライアント ライブラリをインストールします。

pip install azure.mgmt.confidentialledger

Azure Confidential Ledger データ プレーン クライアント ライブラリをインストールします。

pip install azure.confidentialledger 

リソース グループを作成する

リソース グループとは、Azure リソースのデプロイと管理に使用する論理コンテナーです。 Azure CLI の az group create コマンド、または Azure PowerShell の New-AzResourceGroup コマンドレットを使用して、myResourceGroup という名前のリソース グループを eastus の場所に作成します。

az group create --name "myResourceGroup" -l "EastUS"

microsoft.ConfidentialLedger リソース プロバイダーを登録します

リソース プロバイダーは、Azure リソースを提供するサービスです。 Azure CLI の az provider register コマンドまたは Azure PowerShell の Register-AzResourceProvider コマンドレットを使用して、Azure confidential ledger リソース プロバイダー "microsoft.ConfidentialLedger" を登録します。

az provider register --namespace "microsoft.ConfidentialLedger"

登録が完了したことを確認するには、Azure CLI の az provider register コマンドまたは Azure PowerShell の Get-AzResourceProvider コマンドレットを使用します。

az provider show --namespace "microsoft.ConfidentialLedger"

Python アプリを作成する

初期化

これで、Python アプリケーションの作成を開始できます。 まず、必須のパッケージをインポートします。

# Import the Azure authentication library

from azure.identity import DefaultAzureCredential

## Import the control plane sdk

from azure.mgmt.confidentialledger import ConfidentialLedger as ConfidentialLedgerAPI
from azure.mgmt.confidentialledger.models import ConfidentialLedger

# import the data plane sdk

from azure.confidentialledger import ConfidentialLedgerClient
from azure.confidentialledger.certificate import ConfidentialLedgerCertificateClient

次に、DefaultAzureCredential クラスを使用してアプリを認証します。

credential = DefaultAzureCredential()

アプリケーションで使用するいくつかの変数 (リソース グループ (myResourceGroup)、作成する台帳の名前、およびデータ プレーン クライアント ライブラリで使用される 2 つの URL) を設定して、セットアップを完了します。

重要

各台帳には、グローバルに一意の名前が必要です。 次の例では、<your-unique-ledger-name> を自分の台帳の名前に置き換えてください。

resource_group = "<azure-resource-group>"
ledger_name = "<your-unique-ledger-name>"
subscription_id = "<azure-subscription-id>"

identity_url = "https://identity.confidential-ledger.core.azure.com"
ledger_url = "https://" + ledger_name + ".confidential-ledger.azure.com"

コントロール プレーン クライアント ライブラリを使用する

コントロール プレーン クライアント ライブラリ (azure.mgmt.confidentialledger) を使用すると、台帳に対する操作 (作成、変更、削除、サブスクリプションに関連付けられている台帳の一覧表示、特定の台帳の詳細の取得など) が可能になります。

このコードでは、まず、コントロール プレーン クライアントを作成します。それには、ConfidentialLedgerAPI に資格情報変数と Azure サブスクリプション ID (両方とも上記で設定) を渡します。

confidential_ledger_mgmt = ConfidentialLedgerAPI(
    credential, subscription_id
)

これで、begin_create を使用して台帳を作成できるようになりました。 begin_create 関数には、3 つのパラメーター (リソース グループ、台帳の名前、"properties" オブジェクト) が必要です。

次のキーと値を使用して properties 辞書を作成し、それを変数に割り当てます。

properties = {
    "location": "eastus",
    "tags": {},
    "properties": {
        "ledgerType": "Public",
        "aadBasedSecurityPrincipals": [],
    },
}

ledger_properties = ConfidentialLedger(**properties)

次に、リソース グループ、台帳の名前、および properties オブジェクトを begin_create に渡します。

confidential_ledger_mgmt.ledger.begin_create(resource_group, ledger_name, ledger_properties)

台帳が正常に作成されたことを確認するには、get 関数を使用してその詳細を表示します。

myledger = confidential_ledger_mgmt.ledger.get(resource_group, ledger_name)

print("Here are the details of your newly created ledger:")
print (f"- Name: {myledger.name}")
print (f"- Location: {myledger.location}")
print (f"- ID: {myledger.id}")

データ プレーン クライアント ライブラリを使用する

台帳を用意できたので、データ プレーン クライアント ライブラリ (azure.confidentialledger) を使用して台帳を操作します。

まず、confidential ledger 証明書を生成して保存します。

identity_client = ConfidentialLedgerCertificateClient(identity_url)
network_identity = identity_client.get_ledger_identity(
     ledger_id=ledger_name
)

ledger_tls_cert_file_name = "networkcert.pem"
with open(ledger_tls_cert_file_name, "w") as cert_file:
    cert_file.write(network_identity['ledgerTlsCertificate'])

これで、ネットワーク証明書を台帳 URL および資格情報と共に使用して Confidential Ledger クライアントを作成できるようになります。

ledger_client = ConfidentialLedgerClient(
     endpoint=ledger_url, 
     credential=credential,
     ledger_certificate_path=ledger_tls_cert_file_name
)

台帳に書き込む準備ができました。 これを行うには、create_ledger_entry 関数を使用します。

sample_entry = {"contents": "Hello world!"}
append_result = ledger_client.create_ledger_entry(entry=sample_entry)
print(append_result['transactionId'])

print 関数により、台帳に対する書き込みのトランザクション ID が返されます。これを使用すると、台帳に書き込んだメッセージを取得できます。

entry = ledger_client.get_ledger_entry(transaction_id=append_result['transactionId'])['entry']
print(f"Entry (transaction id = {entry['transactionId']}) in collection {entry['collectionId']}: {entry['contents']}")

台帳にコミットされた最新のトランザクションが必要な場合は、get_current_ledger_entry 関数を使用できます。

latest_entry = ledger_client.get_current_ledger_entry()
print(f"Current entry (transaction id = {latest_entry['transactionId']}) in collection {latest_entry['collectionId']}: {latest_entry['contents']}")

print 関数では、トランザクション ID に対応する台帳内のメッセージであり、最新のトランザクションである "Hello world!" が返されます。

完全なサンプル コード

import time
from azure.identity import DefaultAzureCredential

## Import control plane sdk

from azure.mgmt.confidentialledger import ConfidentialLedger as ConfidentialLedgerAPI
from azure.mgmt.confidentialledger.models import ConfidentialLedger

# import data plane sdk

from azure.confidentialledger import ConfidentialLedgerClient
from azure.confidentialledger.certificate import ConfidentialLedgerCertificateClient

# Set variables

resource_group = "<azure-resource-group>"
ledger_name = "<your-unique-ledger-name>"
subscription_id = "<azure-subscription-id>"

identity_url = "https://identity.confidential-ledger.core.azure.com"
ledger_url = "https://" + ledger_name + ".confidential-ledger.azure.com"

# Authentication

# Need to do az login to get default credential to work

credential = DefaultAzureCredential()

# Control plane (azure.mgmt.confidentialledger)
# 
# initialize endpoint with credential and subscription

confidential_ledger_mgmt = ConfidentialLedgerAPI(
    credential, "<subscription-id>"
)

# Create properties dictionary for begin_create call 

properties = {
    "location": "eastus",
    "tags": {},
    "properties": {
        "ledgerType": "Public",
        "aadBasedSecurityPrincipals": [],
    },
}

ledger_properties = ConfidentialLedger(**properties)

# Create a ledger

confidential_ledger_mgmt.ledger.begin_create(resource_group, ledger_name, ledger_properties)

# Get the details of the ledger you just created

print(f"{resource_group} / {ledger_name}")
 
print("Here are the details of your newly created ledger:")
myledger = confidential_ledger_mgmt.ledger.get(resource_group, ledger_name)

print (f"- Name: {myledger.name}")
print (f"- Location: {myledger.location}")
print (f"- ID: {myledger.id}")

# Data plane (azure.confidentialledger)
#
# Create a CL client

identity_client = ConfidentialLedgerCertificateClient(identity_url)
network_identity = identity_client.get_ledger_identity(
     ledger_id=ledger_name
)

ledger_tls_cert_file_name = "networkcert.pem"
with open(ledger_tls_cert_file_name, "w") as cert_file:
    cert_file.write(network_identity['ledgerTlsCertificate'])


ledger_client = ConfidentialLedgerClient(
     endpoint=ledger_url, 
     credential=credential,
     ledger_certificate_path=ledger_tls_cert_file_name
)

# Write to the ledger
sample_entry = {"contents": "Hello world!"}
ledger_client.create_ledger_entry(entry=sample_entry)
  
# Read from the ledger
latest_entry = ledger_client.get_current_ledger_entry()
print(f"Current entry (transaction id = {latest_entry['transactionId']}) in collection {latest_entry['collectionId']}: {latest_entry['contents']}")

ポーラー

書き込みトランザクションが台帳にコミットされるのを待つ場合は、begin_create_ledger_entry 関数を使用できます。 これにより、エントリが永続的にコミットされるまで待機するポーラーが返されます。

sample_entry = {"contents": "Hello world!"}
ledger_entry_poller = ledger_client.begin_create_ledger_entry( 
    entry=sample_entry
)
ledger_entry_result = ledger_entry_poller.result()

古い台帳エントリのクエリを実行するには、台帳がディスクからエントリを読み取って検証する必要があります。 begin_get_ledger_entry 関数を使用して、クエリ対象のエントリが表示可能な状態になるまで待機するポーラーを作成できます。

get_entry_poller = ledger_client.begin_get_ledger_entry(
    transaction_id=ledger_entry_result['transactionId']
)
entry = get_entry_poller.result()

リソースをクリーンアップする

Azure Confidential Ledger に関するその他の記事は、このクイックスタートに基づいている場合があります。 後続のクイック スタートおよびチュートリアルを引き続き実行する場合は、これらのリソースをそのまま残しておくことをお勧めします。

それ以外の場合は、この記事で作成したリソースの操作が完了したら、Azure CLI の az group delete コマンドを使用して、リソース グループとそれに含まれるすべてのリソースを削除します。

az group delete --resource-group myResourceGroup

次の手順