概要
Encrypted ERC システムにおけるユーザーごとの残高をElGamal 暗号(EGCT)で管理し、残高履歴を追跡するための機能を提供するコントラクト。
ユーザーは自分の暗号化された残高を公開せずに、ゼロ知識証明で残高の正当性を示したり、不正な二重支出を防いだりできます。
コード
// (c) 2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
// SPDX-License-Identifier: Ecosystem
pragma solidity 0.8.27;
import {EncryptedBalance, EGCT, BalanceHistory, AmountPCT} from "./types/Types.sol";
import {InvalidProof} from "./errors/Errors.sol";
import {BabyJubJub} from "./libraries/BabyJubJub.sol";
/**
* @title EncryptedUserBalances
* @notice Contract for managing encrypted user balances in the privacy-preserving ERC system
* @dev This contract handles:
* 1. Storage and retrieval of encrypted balances
* 2. Balance history tracking for transaction validation
* 3. Cryptographic operations on encrypted balances
*
* The contract uses ElGamal encryption (EGCT) to store balances privately,
* allowing users to prove they have sufficient funds without revealing the actual amount.
*/
contract EncryptedUserBalances {
///////////////////////////////////////////////////
/// State Variables ///
///////////////////////////////////////////////////
/// @notice Mapping of user addresses to their encrypted balances for each token
/// @dev Structure: user => tokenId => EncryptedBalance
mapping(address user => mapping(uint256 tokenId => EncryptedBalance balance))
public balances;
///////////////////////////////////////////////////
/// External ///
///////////////////////////////////////////////////
/**
* @notice Returns the encrypted balance for a user's standalone token
* @param user The address of the user
* @return eGCT The ElGamal ciphertext representing the encrypted balance
* @return nonce The current nonce used for balance validation
* @return amountPCTs Array of amount PCT
* @return balancePCT The current balance PCT
* @return transactionIndex The current transaction index
* @dev Since in standalone mode, the tokenId is always 0
*/
function balanceOfStandalone(
address user
)
external
view
returns (
EGCT memory eGCT,
uint256 nonce,
AmountPCT[] memory amountPCTs,
uint256[7] memory balancePCT,
uint256 transactionIndex
)
{
return balanceOf(user, 0);
}
/**
* @notice Returns the encrypted balance for a user's specified token
* @param user The address of the user
* @param tokenId The ID of the token
* @return eGCT The ElGamal ciphertext representing the encrypted balance
* @return nonce The current nonce used for balance validation
* @return amountPCTs Array of amount PCT
* @return balancePCT The current balance PCT
* @return transactionIndex The current transaction index
*/
function balanceOf(
address user,
uint256 tokenId
)
public
view
returns (
EGCT memory eGCT,
uint256 nonce,
AmountPCT[] memory amountPCTs,
uint256[7] memory balancePCT,
uint256 transactionIndex
)
{
EncryptedBalance storage balance = balances[user][tokenId];
return (
balance.eGCT,
balance.nonce,
balance.amountPCTs,
balance.balancePCT,
balance.transactionIndex
);
}
///////////////////////////////////////////////////
/// Internal ///
///////////////////////////////////////////////////
/**
* @notice Adds an encrypted amount to a user's balance
* @param user The address of the user
* @param tokenId The ID of the token
* @param eGCT The ElGamal ciphertext representing the amount to add
* @param amountPCT The amount PCT for transaction history
* @dev This function:
* 1. Initializes the balance if it's the first transaction
* 2. Adds the encrypted amount to the existing balance
* 3. Updates the user history (by adding new amount PCT)
*/
function _addToUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT,
uint256[7] memory amountPCT
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
// if user balance is not initialized, initialize it
if (balance.eGCT.c1.x == 0 && balance.eGCT.c1.y == 0) {
balance.eGCT = eGCT;
} else {
// if user balance is already initialized, add the encrypted amount to the balance
balance.eGCT.c1 = BabyJubJub._add(balance.eGCT.c1, eGCT.c1);
balance.eGCT.c2 = BabyJubJub._add(balance.eGCT.c2, eGCT.c2);
}
// in all the case
_addToUserHistory(user, tokenId, amountPCT);
}
/**
* @notice Subtracts an encrypted amount from a user's balance
* @param user The address of the user
* @param tokenId The ID of the token
* @param eGCT The ElGamal ciphertext representing the amount to subtract
* @param balancePCT The new balance PCT after subtraction
* @param transactionIndex The transaction index to delete from history
* @dev This function:
* 1. Subtracts the encrypted amount from the balance
* 2. Updates the user history (by removing the specified transaction)
* 3. Updates the balance PCT for user
*/
function _subtractFromUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT,
uint256[7] memory balancePCT,
uint256 transactionIndex
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
balance.eGCT.c1 = BabyJubJub._sub(balance.eGCT.c1, eGCT.c1);
balance.eGCT.c2 = BabyJubJub._sub(balance.eGCT.c2, eGCT.c2);
// delete the amount pct from the balance
_deleteUserHistory(user, tokenId, transactionIndex);
// update balance pct
balance.balancePCT = balancePCT;
}
/**
* @notice Adds a transaction to the user's balance history
* @param user The address of the user
* @param tokenId The ID of the token
* @param amountPCT The amount PCT for the transaction
* @dev This function:
* 1. Calculates a unique hash for the current balance state
* 2. Marks this hash as valid in the balance history
* 3. Adds the amount PCT to the transaction history
* 4. Increments the transaction index
*
* The balance hash is unique for each transaction because it includes the nonce,
* which is incremented after each transaction. This ensures that each transaction
* can be uniquely identified and validated.
*/
function _addToUserHistory(
address user,
uint256 tokenId,
uint256[7] memory amountPCT
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
uint256 nonce = balance.nonce;
uint256 balanceHash = _hashEGCT(balance.eGCT);
balanceHash = uint256(keccak256(abi.encode(balanceHash, nonce)));
// mark the balance hash as valid
balance.balanceList[balanceHash] = BalanceHistory({
index: balance.transactionIndex,
isValid: true
});
// add the amount pct to the balance
balance.amountPCTs.push(
AmountPCT({pct: amountPCT, index: balance.transactionIndex})
);
balance.transactionIndex++;
}
/**
* @notice Commits the current balance state to the user's history
* @param user The address of the user
* @param tokenId The ID of the token
* @dev This function:
* 1. Calculates a unique hash for the current balance state
* 2. Marks this hash as valid in the balance history
* 3. Increments the transaction index
*
* This is used to create a checkpoint of the balance state after operations
* that don't change the balance amount but need to be recorded in history.
*/
function _commitUserBalance(address user, uint256 tokenId) internal {
EncryptedBalance storage balance = balances[user][tokenId];
uint256 nonce = balance.nonce;
uint256 balanceHash = _hashEGCT(balance.eGCT);
balanceHash = uint256(keccak256(abi.encode(balanceHash, nonce)));
balance.balanceList[balanceHash] = BalanceHistory({
index: balance.transactionIndex,
isValid: true
});
balance.transactionIndex++;
}
/**
* @notice Deletes transaction history up to a specific transaction index
* @param user The address of the user
* @param tokenId The ID of the token
* @param transactionIndex The transaction index to delete up to
* @dev This function:
* 1. Removes amount PCTs from the history up to the specified index
* 2. Increments the nonce (invalidate all previous balance hashes)
* 3. Commits the new balance state to history
*
* Instead of deleting individual history entries, this function uses the nonce
* to invalidate all previous balance hashes at once, which is more gas efficient.
*/
function _deleteUserHistory(
address user,
uint256 tokenId,
uint256 transactionIndex
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
for (uint256 i = balance.amountPCTs.length; i > 0; i--) {
uint256 index = i - 1;
if (balance.amountPCTs[index].index <= transactionIndex) {
balance.amountPCTs[index] = balance.amountPCTs[
balance.amountPCTs.length - 1
];
balance.amountPCTs.pop();
}
}
balance.nonce++;
_commitUserBalance(user, tokenId);
}
/**
* @notice Checks if a balance hash is valid for a user
* @param user The address of the user
* @param tokenId The ID of the token
* @param balanceHash The hash to validate
* @return isValid True if the hash is valid, false otherwise
* @return index The transaction index associated with the hash
* This is used to validate that a user is using a recent and valid balance
* in their transactions.
*/
function _isBalanceValid(
address user,
uint256 tokenId,
uint256 balanceHash
) internal view returns (bool, uint256) {
uint256 nonce = balances[user][tokenId].nonce;
uint256 hashWithNonce = uint256(
keccak256(abi.encode(balanceHash, nonce))
);
return (
balances[user][tokenId].balanceList[hashWithNonce].isValid,
balances[user][tokenId].balanceList[hashWithNonce].index
);
}
/**
* @notice Verifies a user's balance
* @param user The address of the user
* @param tokenId The ID of the token
* @param eGCT The ElGamal ciphertext representing the balance
* @return transactionIndex The transaction index associated with the balance
* @dev If balance is not valid, it reverts with InvalidProof error
*/
function _verifyUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT
) internal view returns (uint256) {
// hash the encrypted balance
uint256 balanceHash = _hashEGCT(eGCT);
(bool isValid, uint256 transactionIndex) = _isBalanceValid(
user,
tokenId,
balanceHash
);
if (!isValid) {
revert InvalidProof();
}
return transactionIndex;
}
/**
* @notice Calculates a hash of an ElGamal ciphertext
* @param eGCT The ElGamal ciphertext to hash
* @return The hash of the ciphertext
* @dev This function creates a unique identifier for an encrypted balance
* by hashing all components of the ElGamal ciphertext.
*/
function _hashEGCT(EGCT memory eGCT) internal pure returns (uint256) {
return
uint256(
keccak256(
abi.encode(eGCT.c1.x, eGCT.c1.y, eGCT.c2.x, eGCT.c2.y)
)
);
}
}State
mapping(address => mapping(uint256 => EncryptedBalance)) public balances;balances- ユーザーアドレス → トークン ID →
EncryptedBalanceを保持する二重マッピング。 EncryptedBalanceには以下が含まれます。EGCT eGCT- 現在のElGamal暗号文。
uint256 nonce- 履歴検証用カウンタ。
AmountPCT[] amountPCTs- 各トランザクションの
PCT情報リスト。
- 各トランザクションの
uint256[7] balancePCT- 現在の残高
PCT。
- 現在の残高
uint256 transactionIndex- トランザクション履歴のインデックス。
mapping(uint256 => BalanceHistory) balanceList- 残高ハッシュ → 履歴情報。
- ユーザーアドレス → トークン ID →
External Functions
balanceOfStandalone
function balanceOfStandalone(
address user
)
external
view
returns (
EGCT memory eGCT,
uint256 nonce,
AmountPCT[] memory amountPCTs,
uint256[7] memory balancePCT,
uint256 transactionIndex
)
{
return balanceOf(user, 0);
}Standaloneモード(tokenId = 0)におけるユーザーの暗号化残高を返す関数
内部で balanceOf(user, 0) を呼び、ElGamal暗号文・履歴データ一式を取得します。
引数
user(address)- 残高を確認したいユーザーのアドレス。
balanceOf
function balanceOf(
address user,
uint256 tokenId
)
public
view
returns (
EGCT memory eGCT,
uint256 nonce,
AmountPCT[] memory amountPCTs,
uint256[7] memory balancePCT,
uint256 transactionIndex
)
{
EncryptedBalance storage balance = balances[user][tokenId];
return (
balance.eGCT,
balance.nonce,
balance.amountPCTs,
balance.balancePCT,
balance.transactionIndex
);
}指定された tokenId のユーザーが保有している暗号化されたトークン残高と、履歴検証に必要な nonce・PCT 情報・トランザクションインデックスを返す関数。
引数
user(address)- 残高を確認したいユーザーのアドレス。
tokenId(uint256)- 対象のトークン識別子。
Internal Functions
_addToUserBalance
function _addToUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT,
uint256[7] memory amountPCT
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
// if user balance is not initialized, initialize it
if (balance.eGCT.c1.x == 0 && balance.eGCT.c1.y == 0) {
balance.eGCT = eGCT;
} else {
// if user balance is already initialized, add the encrypted amount to the balance
balance.eGCT.c1 = BabyJubJub._add(balance.eGCT.c1, eGCT.c1);
balance.eGCT.c2 = BabyJubJub._add(balance.eGCT.c2, eGCT.c2);
}
// in all the case
_addToUserHistory(user, tokenId, amountPCT);
}ユーザーが保有している暗号化されたトークン残高に新しい暗号化されたトークンを加算し、取引履歴を更新する関数。 初回は直接セットし、以降はBabyJubJub曲線の加算演算を使って既存残高に上乗せします。
引数
user(address)- 対象ユーザーのアドレス。
tokenId(uint256)- トークン識別子。
eGCT(EGCT memory)- 加算するElGamal暗号文。
amountPCT(uint256[7])- トランザクション履歴用
PCT情報。
- トランザクション履歴用
_subtractFromUserBalance
function _subtractFromUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT,
uint256[7] memory balancePCT,
uint256 transactionIndex
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
balance.eGCT.c1 = BabyJubJub._sub(balance.eGCT.c1, eGCT.c1);
balance.eGCT.c2 = BabyJubJub._sub(balance.eGCT.c2, eGCT.c2);
// delete the amount pct from the balance
_deleteUserHistory(user, tokenId, transactionIndex);
// update balance pct
balance.balancePCT = balancePCT;
}ユーザーが保有している暗号化されたトークン残高から指定の暗号化されたトークン量を引き、履歴から該当トランザクションを無効化(削除)し、新しい balancePCT を保存する関数。
引数
user(address)- 対象ユーザーのアドレス。
tokenId(uint256)- トークン識別子。
eGCT(EGCT memory)- 減算するElGamal暗号文。
balancePCT(uint256[7])- 更新後の残高
PCT。
- 更新後の残高
transactionIndex(uint256)- 削除基準となる履歴インデックス。
_addToUserHistory
function _addToUserHistory(
address user,
uint256 tokenId,
uint256[7] memory amountPCT
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
uint256 nonce = balance.nonce;
uint256 balanceHash = _hashEGCT(balance.eGCT);
balanceHash = uint256(keccak256(abi.encode(balanceHash, nonce)));
// mark the balance hash as valid
balance.balanceList[balanceHash] = BalanceHistory({
index: balance.transactionIndex,
isValid: true
});
// add the amount pct to the balance
balance.amountPCTs.push(
AmountPCT({pct: amountPCT, index: balance.transactionIndex})
);
balance.transactionIndex++;
}ユーザーごとの暗号化されたトークンの残高を一意のハッシュとして履歴に記録し、その取引で使われた PCT 情報を合わせて保存する関数。
これにより、後から証明の際に「この残高状態は正当である」ことを検証可能にします。
- 残高ハッシュの計算
現在の暗号化残高
balance.eGCTをハッシュ化し、さらにnonceを組み合わせて再度ハッシュを取り、現在の残高を一意に表現します。 - 履歴マップへの登録
そのハッシュ値をキーに
balance.balanceListにBalanceHistory{ index, isValid: true }を書き込み、残高データを有効とマークします。 - PCT情報の追加
この取引で生成された
amountPCT(各種比率データ)を、インデックス付きでbalance.amountPCTs配列に追加し、取引履歴として保存します。 - トランザクションインデックスの更新
balance.transactionIndexをインクリメントします。
user(address)- 対象ユーザーのアドレス。
tokenId(uint256)- トークン識別子。
amountPCT (uint256[7])- トランザクション履歴用
PCT情報。
- トランザクション履歴用
_commitUserBalance
function _commitUserBalance(address user, uint256 tokenId) internal {
EncryptedBalance storage balance = balances[user][tokenId];
uint256 nonce = balance.nonce;
uint256 balanceHash = _hashEGCT(balance.eGCT);
balanceHash = uint256(keccak256(abi.encode(balanceHash, nonce)));
balance.balanceList[balanceHash] = BalanceHistory({
index: balance.transactionIndex,
isValid: true
});
balance.transactionIndex++;
}残高そのものは変わらないが、操作の履歴(チェックポイント)として今の残高を履歴に記録してインデックスを進める関数。
- 残高ハッシュの生成
現在の暗号化残高
balance.eGCTを_hashEGCTでハッシュ化し、さらにnonceを合わせてもう一度ハッシュして一意のbalanceHashを作成。 - 履歴への登録
balanceHashをキーにbalance.balanceListへBalanceHistory{ index: balance.transactionIndex, isValid: true }を書き込み「有効」とマーク。 - インデックス更新
取引履歴のポインタである
balance.transactionIndexをインクリメント。
引数
user(address)- 履歴を記録するユーザーのアドレス。
tokenId(uint256)- 対象となるトークンのID。
_deleteUserHistory
function _deleteUserHistory(
address user,
uint256 tokenId,
uint256 transactionIndex
) internal {
EncryptedBalance storage balance = balances[user][tokenId];
for (uint256 i = balance.amountPCTs.length; i > 0; i--) {
uint256 idx = i - 1;
if (balance.amountPCTs[idx].index <= transactionIndex) {
balance.amountPCTs[idx] = balance.amountPCTs[
balance.amountPCTs.length - 1
];
balance.amountPCTs.pop();
}
}
balance.nonce++;
_commitUserBalance(user, tokenId);
}指定したインデックス以下の取引履歴をまとめて削除し、古いハッシュを一気に無効化してから新しい履歴をコミットする関数。
- 履歴エントリの削除
amountPCTs配列の末尾から順に走査し、index ≤ transactionIndexのものを配列最後尾の要素と置き換えてpop()。 - ノンスのインクリメント
balance.nonceを増やすことで、過去のハッシュ全体を一括で無効化。 - 新しいチェックポイントのコミット
_commitUserBalance関数を呼び出し、今の残高を履歴に記録。
引数
user(address)- 履歴を操作するユーザーのアドレス。
tokenId(uint256)- 対象トークンのID。
transactionIndex(uint256)- 削除対象とする履歴の最大インデックス。
_isBalanceValid
function _isBalanceValid(
address user,
uint256 tokenId,
uint256 balanceHash
) internal view returns (bool, uint256) {
uint256 nonce = balances[user][tokenId].nonce;
uint256 hashWithNonce = uint256(
keccak256(abi.encode(balanceHash, nonce))
);
BalanceHistory memory bh = balances[user][tokenId].balanceList[hashWithNonce];
return (bh.isValid, bh.index);
}与えられた残高ハッシュ(暗号文ハッシュ+ノンス)で、暗号化されたトークンの残高履歴から「有効フラグ」と「登録インデックス」を取得する関数。
- ハッシュとノンスの合成
受け取った
balanceHashに現在のnonceを合わせて再ハッシュし、保存キーを計算。。 - 暗号化されたトークンの残高履歴参照
balance.balanceList[hashWithNonce]からisValidとindexを返す。
引数
user(address)- 対象ユーザーのアドレス。
tokenId(uint256)- 対象トークンのID。
balanceHash(uint256)- 検証したい残高ハッシュ。
_verifyUserBalance
function _verifyUserBalance(
address user,
uint256 tokenId,
EGCT memory eGCT
) internal view returns (uint256) {
uint256 balanceHash = _hashEGCT(eGCT);
(bool ok, uint256 idx) = _isBalanceValid(user, tokenId, balanceHash);
if (!ok) revert InvalidProof();
return idx;
}ユーザーから渡された暗号化されたトークン残高が、コントラクトに記録されている有効な状態かを検証する関数。 これにより、ユーザーが古い状態の残高を使用して不正な操作を行うことを防ぎます。
- 暗号化残高のハッシュ化
引数で受け取った
eGCT(ElGamal暗号文で表現された残高)を_hashEGCT関数を用いてハッシュ化し、balanceHashを生成します。 これは、特定の残高状態を一意に識別する値です。 - 残高の有効性チェック
_isBalanceValid関数を呼び出します。 この関数は、balanceHashに現在のユーザーのnonceを組み合わせた最終的なハッシュ値を計算し、そのハッシュが過去の取引で有効なものとして記録(コミット)されているかをbalanceListマッピングで確認します。 - 検証結果の判定
_isBalanceValidから返されたisValidがfalseの場合、提供された残高は無効であると判断し、InvalidProofエラーを返します。 - トランザクションインデックスの返却
検証が成功した場合、その有効な残高状態に対応する
transactionIndexを関数の呼び出し元に返します。 このインデックスは、後続の処理(例:残高の更新)でどの履歴を操作すべきかを特定するために利用されます。
引数
user(address)- 検証対象のユーザーのアドレス。
tokenId(uint256)- 対象トークンID。
eGCT(EGCT memory)- 提出された暗号化されたトークンの残高。
_hashEGCT(EGCT memory eGCT)
function _hashEGCT(EGCT memory eGCT) internal pure returns (uint256) {
return uint256(
keccak256(
abi.encode(eGCT.c1.x, eGCT.c1.y, eGCT.c2.x, eGCT.c2.y)
)
);
}ElGamal 暗号文ペアの4座標をまとめてハッシュ化し、暗号化されたトークンの残高を一意に識別する値を返す関数。
- 座標のシリアライズ
c1.x, c1.y, c2.x, c2.yをabi.encodeに詰めます。 - Keccak256 ハッシュ
まとめたバイト列を
keccak256でハッシュし、uint256にキャストして返します。
引数
eGCT(EGCT memory)- ハッシュ化対象のElGamal暗号文のペア。