簽章聲明是一種多功能工具,用於請求使用者使用其 DID 關聯的私鑰簽署任意資料。此加密簽章可作為使用者已查看並批准該資料的不可否認的證明,從而有效地證明其對數位身份的控制權。常見的使用案例包括簽署訊息、授權交易或確認委託。
對於錢包需要為交易提供輸入的更複雜支付場景,請考慮使用準備交易聲明。
運作原理
應用程式建構一個 signature 聲明,詳細說明需要簽署的內容。這包括資料本身(作為原始字串或預先計算的摘要)、資料類型(有助於錢包正確顯示)以及雜湊方法。DID 錢包接收此請求,將資訊呈現給使用者進行確認,並在批准後簽署資料並將簽章返回給應用程式進行驗證。
參數
signature 聲明物件接受以下參數:
| Parameter | Type | Description |
|---|---|---|
typeUrl | string | 必要。 指定資料類型。這有助於錢包正確地解釋和顯示內容。常見的值包括 mime:text/plain、mime:text/html、fg:t:transaction(用於 Forge 編碼的交易)或特定的交易類型,如 TransferV2Tx。 |
origin | string | 待簽署的原始資料,以 Base58 字串編碼。當您希望錢包看到並雜湊完整資料時使用。您應提供 origin 或 digest 其中之一。 |
digest | string | 資料的預先計算雜湊值。當原始資料太大而無法傳送,或您不需要錢包看到原始內容時使用。 |
method | string | 錢包在簽署前應對 origin 資料應用的雜湊演算法。預設為 sha3。如果設定為 'none',錢包將直接簽署 origin 資料,而不會先進行雜湊處理。 |
display | string | 一個 JSON 字串,用於在錢包中提供豐富的顯示,例如顯示格式化的訊息或連結。範例:JSON.stringify({ type: 'url', content: 'https://www.arcblock.io' })。 |
description | string | 一條方便使用者理解的訊息,解釋要求使用者簽署的內容。預設為「請簽署此交易或訊息以繼續」。 |
requirement | object | 一個可選物件,指定使用者必須滿足才能提供簽章的代幣或資產要求。 |
nonce | string | 一個可選的隨機字串,用於防止重放攻擊。 |
使用範例
以下是一些請求不同類型簽章的範例。
1. 簽署純文字訊息
這是最簡單的使用案例,您要求使用者簽署一個簡單的文字字串。
請求文字簽章
const claims = {
signature: {
typeUrl: 'mime:text/plain',
description: 'Please sign this message to verify your identity.',
data: 'I agree to the terms and conditions.',
},
};
// In your handler
const { authInfo } = await authenticator.sign({
claims,
// ... other params
});在此範例中,data 字串將被轉換為 Buffer,以 Base58 編碼,並作為 origin 欄位傳送到錢包。
2. 簽署交易(從原始資料)
對於鏈上操作,您可以要求使用者簽署一筆交易。您可以提供原始交易物件,DID Connect 將為您處理編碼。這需要在您的 WalletAuthenticator 實例中設定 chainInfo。
請求交易簽章
const claims = {
signature: {
// This is a specific transaction type known by @ocap/client
type: 'TransferV2Tx',
description: 'Please sign to confirm the transfer of 100 TBA.',
display: JSON.stringify({ type: 'html', content: '<div>Transfer <b>100 TBA</b> to recipient</div>' }),
// The raw transaction data object
data: {
itx: {
to: 'z123...',
tokens: [
{
address: 'z35nB2SA6xxBuoaiuUXUw6Gah2SNU3UzqdgEt',
value: '100',
},
],
},
},
// Optional: specify token requirements for the wallet
requirement: {
tokens: [
{
address: 'z35nB2SA6xxBuoaiuUXUw6Gah2SNU3UzqdgEt',
value: '100',
},
],
},
},
};在幕後,WalletAuthenticator 將使用 @ocap/client 將 data 物件編碼為交易緩衝區。傳送到錢包的 typeUrl 將自動設定為 fg:t:transaction,而 origin 將是 Base58 編碼的緩衝區。
3. 簽署交易(預先編碼)
如果您已在伺服器上編碼了交易緩衝區,可以直接傳送它。在這種情況下,您必須將 typeUrl 設定為 fg:t:transaction。
簽署預先編碼的交易
const { Client } = require('@ocap/client');
const { toBase58 } = require('@ocap/util');
// Assume client is an instance of @ocap/client
const { buffer: txBuffer } = await client.encodeTransferV2Tx({
// ... tx params
});
const claims = {
signature: {
typeUrl: 'fg:t:transaction',
description: 'Please confirm this pre-encoded transaction.',
// The `data` is the base58-encoded buffer
data: toBase58(txBuffer),
},
};這種方法讓您有更多的控制權,但需要您自己處理交易編碼。
透過利用簽章聲明,您可以與使用者建立安全且可驗證的互動。下一節將介紹用於支付場景的特殊類型交易聲明。
下一步:準備交易聲明
了解如何請求錢包完成並簽署部分建構的交易。