Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions sdk/src/binding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { createHash } from 'crypto';
import { StrKey } from '@stellar/stellar-base';
import { FIELD_MODULUS } from './zk_constants';

/**
* Address Binding Strategy (ZK-072)
*
* Implements a verifiable binding between a withdrawal recipient and the nullifier
* to prevent MITM and front-running attacks in the relayer network.
*
* Binding = Hash(nullifier_hash || recipient_address)
*/
export function computeAddressBinding(nullifierHash: string, recipientAddress: string): string {
if (!StrKey.isValidEd25519PublicKey(recipientAddress)) {
throw new Error(`Invalid Stellar address: ${recipientAddress}`);
}

const cleanNullifier = nullifierHash.startsWith('0x') ? nullifierHash.slice(2) : nullifierHash;

const input = Buffer.concat([
Buffer.from(cleanNullifier.padStart(64, '0'), 'hex'),
Buffer.from(recipientAddress, 'utf8')
]);

const digest = createHash('sha256').update(input).digest();
// Reduce modulo the BN254 field prime to ensure it's a valid circuit input
const fieldVal = BigInt('0x' + digest.toString('hex')) % FIELD_MODULUS;

return fieldVal.toString(16).padStart(64, '0');
}
11 changes: 8 additions & 3 deletions sdk/src/public_inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
* but not passed to the contract verifier.
*/

import { createHash } from 'crypto';
import { computeAddressBinding } from './binding';

// ... (rest of the imports)
import { FIELD_MODULUS, MERKLE_NODE_BYTE_LENGTH, NOTE_SCALAR_BYTE_LENGTH, NULLIFIER_DOMAIN_SEP_HEX } from './zk_constants';
import { StrKey } from '@stellar/stellar-base';
import { WitnessValidationError } from './errors';
Expand Down Expand Up @@ -297,6 +299,7 @@ export const WITHDRAWAL_PUBLIC_INPUT_SCHEMA = [
'pool_id',
'root',
'nullifier_hash',
'address_binding',
'recipient',
'amount',
'relayer',
Expand Down Expand Up @@ -450,16 +453,18 @@ export function packWithdrawalPublicInputs(
fee: bigint,
denomination: bigint
): string[] {
const addressBinding = computeAddressBinding(nullifierHash, recipient);
return serializeWithdrawalPublicInputs({
pool_id: poolId,
root,
nullifier_hash: nullifierHash,
address_binding: addressBinding,
recipient,
amount: encodeAmount(amount),
relayer,
fee: encodeFee(fee),
denomination: encodeDenomination(denomination),
}).fields;
denomination: denomination,
} as any).fields;
}

// ============================================================
Expand Down