Testnet · Mainnet coming soon

Build a passkey wallet

20 min read

View as Markdown
Contents

You build a user account rule that approves a PCASH payment signed with a passkey, the key a phone or laptop keeps for signing in to a website, instead of with an Ethereum key. The rule is one Noir circuit whose configuration commits the passkey's P-256 public key. You install it on an existing user account beside the account's default rules, and the app then pays through it after the device's fingerprint, face or PIN prompt. This is an example: unaudited and not for real funds.

How it works

  1. The app creates a passkey for its site and reads the passkey's public key. It installs the rule with an account update that the account's Ethereum key approves, and the rule's configuration commits the passkey's key, so the rule accepts no other signer.
  2. To pay, the app builds the transaction and computes its 32-byte payment digest, the same EIP-712 digest the default payment rule has an Ethereum wallet sign. The digest covers the recipient, the amount, the fees, the nullifiers of the spent notes and the deadline.
  3. The app asks the browser for a passkey signature with the digest as the challenge. The browser writes the challenge, in base64url, into a short JSON text called the client data, and the passkey signs its authenticator data followed by the SHA-256 of the client data.
  4. The app proves the rule as part of the transaction's proof. The circuit recomputes the digest from the transaction, checks that the client data carries it, rebuilds the signed bytes and verifies the P-256 signature under the configured key.
  5. The rule returns a commitment to the account and its configuration and a commitment to the exact action. The PCASH kernel accepts the proof only if they match the account's installed rule and the transaction being proved.

The circuit

The configuration holds the passkey's public key and the EIP-712 domain the digest is computed under. Its commitment also includes the account's nullifier-key commitment, as the default rules' does, so the nk_root the rule uses for change notes is the account's own.

pub struct PasskeyConfiguration {
    // The EIP-712 domain of the payment digest, as in the reference rules.
    pub domain: Configuration,
    // The passkey's P-256 public key: affine coordinates, 32-byte big-endian.
    pub key_x: [u8; 32],
    pub key_y: [u8; 32],
}

// configurationCommitment = poseidon(PASSKEY_CONFIGURATION_DOMAIN,
//     domainSeparatorHigh128, domainSeparatorLow128,
//     keyXHigh128, keyXLow128, keyYHigh128, keyYLow128, nullifierKeyCommitment)
pub fn configuration_commitment(
    configuration: PasskeyConfiguration,
    nullifier_key_commitment: Field,
) -> Field {
    let x = halves(configuration.key_x);
    let y = halves(configuration.key_y);
    pcash_hash([
        PASSKEY_CONFIGURATION_DOMAIN,
        configuration.domain.domain_separator_high,
        configuration.domain.domain_separator_low,
        x[0],
        x[1],
        y[0],
        y[1],
        nullifier_key_commitment,
    ])
}

A WebAuthn assertion is a set of byte strings of varying length. The circuit takes them padded to fixed bounds, with their real lengths and the offsets where the type and the challenge appear in the client data.

// One WebAuthn assertion (navigator.credentials.get). Each byte array is
// padded to its bound; only its first `*_length` bytes are hashed.
pub struct Assertion {
    pub authenticator_data: [u8; MAX_AUTHENTICATOR_DATA_LENGTH],
    pub authenticator_data_length: u32,
    pub client_data_json: [u8; MAX_CLIENT_DATA_JSON_LENGTH],
    pub client_data_json_length: u32,
    // Where `"type":"webauthn.get"` and `"challenge":"` start in the client data.
    pub type_offset: u32,
    pub challenge_offset: u32,
    // r ‖ s, with s in the lower half of the group order.
    pub signature: [u8; 64],
}

The payment checks are the default payment rule's. Slot 0 pays the recipient, slot 1 returns change to the account under a secret the owner can recompute, the last slot may pay a relayer, and every other slot is padding.

    for i in 0..S_OUTPUTS {
        let mut declaration = OutputDeclaration { recipient: 0, amount: 0, asset_id: 0 };
        let mut secret = 0;
        let mut change = 0;
        let mut unused = true;
        if i == 0 {
            if amount != 0 {
                declaration = OutputDeclaration { recipient, amount, asset_id: 0 };
                secret = recipient_note_secret;
                unused = false;
            }
        } else if i == 1 {
            change = native_change_amount;
            unused = change == 0;
        } else if i == S_OUTPUTS - 1 {
            unused = relay_fee_amount == 0;
        }
        if unused {
            assert(
                private_value.output_slot_classes[i] == SLOT_CLASS_DUMMY,
                "unused output slot must be a dummy",
            );
        }

The rule then computes the payment's EIP-712 digest from the opened transaction and the signed fields, exactly as the default payment rule does, and checks the passkey's assertion against it.

    let digest = burn_message_signing_hash(
        configuration.domain,
        PAYMENT_TYPE_HASH,
        PAYMENT_WITH_BURN_TYPE_HASH,
        [
            pcash_chain_id,
            recipient,
            amount,
            private_value.open_fee_amount,
            issuance_recipient,
            private_value.issuance_owner_commitment,
            relay_fee_amount,
            relay_fee_owner_commitment,
            private_value.account_creation_commitment,
            context,
            private_value.not_before_timestamp,
            private_value.valid_until_timestamp,
        ],
        3,
        private_value.native_burn_amount,
        native_burn,
    );
    verify_assertion(configuration, assertion, digest);

The assertion checks start with the bounds and the authenticator flags. The passkey must report that the user was present and was verified by fingerprint, face or PIN.

    let authenticator_data_length = assertion.authenticator_data_length;
    let client_data_json_length = assertion.client_data_json_length;
    // rpIdHash (32) ‖ flags (1) ‖ signCount (4) ‖ extensions.
    assert(
        (37 <= authenticator_data_length)
            & (authenticator_data_length <= MAX_AUTHENTICATOR_DATA_LENGTH),
        "authenticator data length out of range",
    );
    assert(
        client_data_json_length <= MAX_CLIENT_DATA_JSON_LENGTH,
        "client data length out of range",
    );
    // User present (bit 0) and user verified (bit 2).
    assert(
        (assertion.authenticator_data[32] & 0x05) == 0x05,
        "passkey must report user presence and verification",
    );

Next comes the client data. The circuit finds "type":"webauthn.get" at one offset, and "challenge":" followed by the 43-character base64url digest and a closing quote at another. Both must lie inside the hashed length, so the prover can't point at bytes the passkey didn't sign.

    assert(
        bytes_at(
            assertion.client_data_json,
            client_data_json_length,
            assertion.type_offset,
            "\"type\":\"webauthn.get\"".as_bytes(),
        ),
        "client data must be an assertion",
    );
    let prefix = "\"challenge\":\"".as_bytes();
    let encoded = base64url(digest);
    let mut challenge = [0x22; 57];
    for i in 0..13 {
        challenge[i] = prefix[i];
    }
    for i in 0..43 {
        challenge[13 + i] = encoded[i];
    }
    assert(
        bytes_at(
            assertion.client_data_json,
            client_data_json_length,
            assertion.challenge_offset,
            challenge,
        ),
        "client data challenge must be the payment digest",
    );

Last, it rebuilds what the passkey signed, the authenticator data followed by the SHA-256 of the client data, hashes it, and verifies the P-256 signature with Noir's standard library.

    let mut signed_data = [0; MAX_AUTHENTICATOR_DATA_LENGTH + 32];
    for i in 0..MAX_AUTHENTICATOR_DATA_LENGTH {
        signed_data[i] = assertion.authenticator_data[i];
    }
    let client_data_hash = sha256_var(assertion.client_data_json, client_data_json_length);
    for i in 0..32 {
        signed_data[authenticator_data_length + i] = client_data_hash[i];
    }
    let message_hash = sha256_var(signed_data, authenticator_data_length + 32);
    assert(
        std::ecdsa_secp256r1::verify_signature(
            configuration.key_x,
            configuration.key_y,
            assertion.signature,
            message_hash,
        ),
        "passkey signature must be valid",
    );

Noir's standard library has the SHA-256 compression function but no SHA-256 for messages of varying length, so the file pads the message itself: a 0x80 byte, zeros, and the bit length at the end of the last block.

fn sha256_var<let N: u32>(data: [u8; N], length: u32) -> [u8; 32] {
    let blocks = (length + 8) / 64 + 1;
    let mut padded = [0; ((N + 8) / 64 + 1) * 64];
    for i in 0..N {
        if i < length {
            padded[i] = data[i];
        }
    }
    padded[length] = 0x80;
    let bit_length: [u8; 8] = (length as Field * 8).to_be_bytes();
    for i in 0..8 {
        padded[blocks * 64 - 8 + i] = bit_length[i];
    }

The rule returns its statement. The kernel accepts it only from the account at address with this rule installed under this exact configuration, and only for the transaction being proved.

    // The kernel accepts this only from the account at `address` with this rule
    // installed under this exact configuration, so its passkey is the signer.
    let configuration_commitment =
        configuration_commitment(configuration, nullifier_key_commitment(nk_root));
    rule_statement(
        authorization_commitment(address, configuration_commitment),
        transfer_action_commitment(pcash_chain_id, private_value_commitment(private_value)),
        recent_pcash_block_hash,
        event_entry,
    )
The whole circuit
// Approves a native payment signed by a passkey (WebAuthn, P-256) instead of an Ethereum key.
// Example only: unaudited, not for real funds.
//
// The payment relation and its EIP-712 digest are the reference payment rule's
// (circuits/rules/payment). Only the signer changes: the WebAuthn challenge is
// that digest, and the passkey's P-256 key, committed in the configuration,
// must sign sha256(authenticatorData ‖ sha256(clientDataJSON)).

use pcash_protocol::authorization::statement::{
    authorization_commitment, rule_statement, RULE_STATEMENT_LENGTH, transfer_action_commitment,
};
use pcash_protocol::generated::private_value_profiles::{S_INPUTS, S_OUTPUTS, S_SHAPE_ID};
use pcash_protocol::ledger::note::nullifier_key_commitment;
use pcash_protocol::ledger::private_value::{
    private_value_commitment, SLOT_CLASS_DUMMY, SLOT_CLASS_NATIVE, SmallPrivateValue,
};
use pcash_protocol::primitives::hash::pcash_hash;
use pcash_protocol::primitives::range::assert_address;
use reference_rule_common::configuration::Configuration;
use reference_rule_common::issuance_opening::assert_owner_issuance_opening;
use reference_rule_common::message::{burn_message_signing_hash, NativeBurn};
use reference_rule_common::payout::transaction_context;
use reference_rule_common::value_rule::{assert_relay_terms, assert_value_output, OutputDeclaration};
use std::hash::sha256_compression;

// The reference payment rule's EIP-712 type hashes, base and WithBurn.
global PAYMENT_TYPE_HASH: [u8; 32] = [
    0x0e, 0x77, 0x26, 0x28, 0xa7, 0xe0, 0x2a, 0xcf, 0x10, 0x48, 0x96, 0x1e, 0x22, 0x11, 0x0b, 0x77,
    0x22, 0x9b, 0xd6, 0xf0, 0xe5, 0xeb, 0x1b, 0x59, 0x6a, 0x80, 0x61, 0x0e, 0xca, 0xb1, 0x7f, 0x94,
];
global PAYMENT_WITH_BURN_TYPE_HASH: [u8; 32] = [
    0x93, 0xe9, 0x7c, 0x40, 0xf0, 0x30, 0xad, 0xf2, 0x80, 0x2d, 0xec, 0x1e, 0xbb, 0x95, 0xc0, 0x30,
    0x91, 0x32, 0x63, 0x28, 0x52, 0xd6, 0x10, 0xb2, 0xb1, 0xf9, 0x72, 0x34, 0x14, 0x7f, 0x9e, 0x07,
];

// The domain tag (spec §2.5) of the context string `passkey_configuration`.
global PASSKEY_CONFIGURATION_DOMAIN: Field =
    0x2814978b3811c4faa584fd898d37fdbfe7de3a2f5ada8f09abc540acd5461162;

// Bounds on the hashed WebAuthn data. A typical passkey assertion has 37 bytes
// of authenticator data and under 260 bytes of client data.
global MAX_AUTHENTICATOR_DATA_LENGTH: u32 = 128;
global MAX_CLIENT_DATA_JSON_LENGTH: u32 = 320;

global SHA256_IV: [u32; 8] = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];

pub struct PasskeyConfiguration {
    // The EIP-712 domain of the payment digest, as in the reference rules.
    pub domain: Configuration,
    // The passkey's P-256 public key: affine coordinates, 32-byte big-endian.
    pub key_x: [u8; 32],
    pub key_y: [u8; 32],
}

// configurationCommitment = poseidon(PASSKEY_CONFIGURATION_DOMAIN,
//     domainSeparatorHigh128, domainSeparatorLow128,
//     keyXHigh128, keyXLow128, keyYHigh128, keyYLow128, nullifierKeyCommitment)
pub fn configuration_commitment(
    configuration: PasskeyConfiguration,
    nullifier_key_commitment: Field,
) -> Field {
    let x = halves(configuration.key_x);
    let y = halves(configuration.key_y);
    pcash_hash([
        PASSKEY_CONFIGURATION_DOMAIN,
        configuration.domain.domain_separator_high,
        configuration.domain.domain_separator_low,
        x[0],
        x[1],
        y[0],
        y[1],
        nullifier_key_commitment,
    ])
}

// One WebAuthn assertion (navigator.credentials.get). Each byte array is
// padded to its bound; only its first `*_length` bytes are hashed.
pub struct Assertion {
    pub authenticator_data: [u8; MAX_AUTHENTICATOR_DATA_LENGTH],
    pub authenticator_data_length: u32,
    pub client_data_json: [u8; MAX_CLIENT_DATA_JSON_LENGTH],
    pub client_data_json_length: u32,
    // Where `"type":"webauthn.get"` and `"challenge":"` start in the client data.
    pub type_offset: u32,
    pub challenge_offset: u32,
    // r ‖ s, with s in the lower half of the group order.
    pub signature: [u8; 64],
}

fn main(
    pcash_chain_id: Field,
    recent_pcash_block_hash: Field,
    address: Field,
    configuration: PasskeyConfiguration,
    nk_root: Field,
    assertion: Assertion,
    // The reference payment message's fields.
    recipient: Field,
    amount: Field,
    issuance_recipient: Field,
    relay_fee_amount: Field,
    relay_fee_owner_commitment: Field,
    native_burn: NativeBurn,
    // Private openings.
    native_change_amount: Field,
    private_value: SmallPrivateValue,
    issuance_note_secret: Field,
    recipient_note_secret: Field,
    event_entry: Field,
) -> return_data [Field; RULE_STATEMENT_LENGTH] {
    assert_payment(
        address,
        nk_root,
        recipient,
        amount,
        relay_fee_amount,
        relay_fee_owner_commitment,
        native_change_amount,
        private_value,
        recipient_note_secret,
    );
    let context = transaction_context::<S_INPUTS, S_OUTPUTS, S_SHAPE_ID>(
        pcash_chain_id,
        private_value.nullifiers,
    );
    assert_owner_issuance_opening(
        private_value,
        context,
        address,
        nk_root,
        issuance_recipient,
        issuance_note_secret,
    );
    let digest = burn_message_signing_hash(
        configuration.domain,
        PAYMENT_TYPE_HASH,
        PAYMENT_WITH_BURN_TYPE_HASH,
        [
            pcash_chain_id,
            recipient,
            amount,
            private_value.open_fee_amount,
            issuance_recipient,
            private_value.issuance_owner_commitment,
            relay_fee_amount,
            relay_fee_owner_commitment,
            private_value.account_creation_commitment,
            context,
            private_value.not_before_timestamp,
            private_value.valid_until_timestamp,
        ],
        3,
        private_value.native_burn_amount,
        native_burn,
    );
    verify_assertion(configuration, assertion, digest);

    // The kernel accepts this only from the account at `address` with this rule
    // installed under this exact configuration, so its passkey is the signer.
    let configuration_commitment =
        configuration_commitment(configuration, nullifier_key_commitment(nk_root));
    rule_statement(
        authorization_commitment(address, configuration_commitment),
        transfer_action_commitment(pcash_chain_id, private_value_commitment(private_value)),
        recent_pcash_block_hash,
        event_entry,
    )
}

// The reference payment relation with the account address as the owner: slot 0
// pays `recipient` (padding when `amount` is zero), slot 1 returns native change
// to the owner, the last slot may pay a private relayer, the rest is padding.
fn assert_payment(
    address: Field,
    nk_root: Field,
    recipient: Field,
    amount: Field,
    relay_fee_amount: Field,
    relay_fee_owner_commitment: Field,
    native_change_amount: Field,
    private_value: SmallPrivateValue,
    recipient_note_secret: Field,
) {
    for i in 0..S_INPUTS {
        let class = private_value.input_slot_classes[i];
        assert(
            (class == SLOT_CLASS_DUMMY) | (class == SLOT_CLASS_NATIVE),
            "payment input must be native or dummy",
        );
    }
    assert_address(recipient);
    assert(recipient != 0, "payment recipient must be nonzero");
    assert_relay_terms(private_value, relay_fee_amount, relay_fee_owner_commitment);
    for i in 0..S_OUTPUTS {
        let mut declaration = OutputDeclaration { recipient: 0, amount: 0, asset_id: 0 };
        let mut secret = 0;
        let mut change = 0;
        let mut unused = true;
        if i == 0 {
            if amount != 0 {
                declaration = OutputDeclaration { recipient, amount, asset_id: 0 };
                secret = recipient_note_secret;
                unused = false;
            }
        } else if i == 1 {
            change = native_change_amount;
            unused = change == 0;
        } else if i == S_OUTPUTS - 1 {
            unused = relay_fee_amount == 0;
        }
        if unused {
            assert(
                private_value.output_slot_classes[i] == SLOT_CLASS_DUMMY,
                "unused output slot must be a dummy",
            );
        }
        assert_value_output(
            private_value,
            i,
            address,
            nk_root,
            0,
            declaration,
            relay_fee_amount,
            relay_fee_owner_commitment,
            secret,
            change,
        );
    }
}

// A WebAuthn assertion by the configured passkey whose challenge is `digest`.
fn verify_assertion(configuration: PasskeyConfiguration, assertion: Assertion, digest: [u8; 32]) {
    let authenticator_data_length = assertion.authenticator_data_length;
    let client_data_json_length = assertion.client_data_json_length;
    // rpIdHash (32) ‖ flags (1) ‖ signCount (4) ‖ extensions.
    assert(
        (37 <= authenticator_data_length)
            & (authenticator_data_length <= MAX_AUTHENTICATOR_DATA_LENGTH),
        "authenticator data length out of range",
    );
    assert(
        client_data_json_length <= MAX_CLIENT_DATA_JSON_LENGTH,
        "client data length out of range",
    );
    // User present (bit 0) and user verified (bit 2).
    assert(
        (assertion.authenticator_data[32] & 0x05) == 0x05,
        "passkey must report user presence and verification",
    );

    assert(
        bytes_at(
            assertion.client_data_json,
            client_data_json_length,
            assertion.type_offset,
            "\"type\":\"webauthn.get\"".as_bytes(),
        ),
        "client data must be an assertion",
    );
    let prefix = "\"challenge\":\"".as_bytes();
    let encoded = base64url(digest);
    let mut challenge = [0x22; 57];
    for i in 0..13 {
        challenge[i] = prefix[i];
    }
    for i in 0..43 {
        challenge[13 + i] = encoded[i];
    }
    assert(
        bytes_at(
            assertion.client_data_json,
            client_data_json_length,
            assertion.challenge_offset,
            challenge,
        ),
        "client data challenge must be the payment digest",
    );

    let mut signed_data = [0; MAX_AUTHENTICATOR_DATA_LENGTH + 32];
    for i in 0..MAX_AUTHENTICATOR_DATA_LENGTH {
        signed_data[i] = assertion.authenticator_data[i];
    }
    let client_data_hash = sha256_var(assertion.client_data_json, client_data_json_length);
    for i in 0..32 {
        signed_data[authenticator_data_length + i] = client_data_hash[i];
    }
    let message_hash = sha256_var(signed_data, authenticator_data_length + 32);
    assert(
        std::ecdsa_secp256r1::verify_signature(
            configuration.key_x,
            configuration.key_y,
            assertion.signature,
            message_hash,
        ),
        "passkey signature must be valid",
    );
}

// Whether `expected` lies at `offset` within the first `length` bytes.
fn bytes_at<let N: u32, let K: u32>(
    bytes: [u8; N],
    length: u32,
    offset: u32,
    expected: [u8; K],
) -> bool {
    let mut matches = offset + K <= length;
    for i in 0..K {
        matches &= bytes[offset + i] == expected[i];
    }
    matches
}

// Unpadded base64url of 32 bytes: 43 characters, the last carrying 4 bits.
fn base64url(bytes: [u8; 32]) -> [u8; 43] {
    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".as_bytes();
    let mut sextets = [0; 43];
    for g in 0..10 {
        let b0 = bytes[3 * g];
        let b1 = bytes[3 * g + 1];
        let b2 = bytes[3 * g + 2];
        sextets[4 * g] = b0 / 4;
        sextets[4 * g + 1] = (b0 % 4) * 16 + b1 / 16;
        sextets[4 * g + 2] = (b1 % 16) * 4 + b2 / 64;
        sextets[4 * g + 3] = b2 % 64;
    }
    sextets[40] = bytes[30] / 4;
    sextets[41] = (bytes[30] % 4) * 16 + bytes[31] / 16;
    sextets[42] = (bytes[31] % 16) * 4;
    let mut encoded = [0; 43];
    for i in 0..43 {
        encoded[i] = alphabet[sextets[i] as u32];
    }
    encoded
}

// SHA-256 of the first `length <= N` bytes of `data`, built on the standard
// library's compression function. The padding (0x80, zeros, the 64-bit bit
// length) ends block `blocks - 1`; later blocks are computed and discarded.
fn sha256_var<let N: u32>(data: [u8; N], length: u32) -> [u8; 32] {
    let blocks = (length + 8) / 64 + 1;
    let mut padded = [0; ((N + 8) / 64 + 1) * 64];
    for i in 0..N {
        if i < length {
            padded[i] = data[i];
        }
    }
    padded[length] = 0x80;
    let bit_length: [u8; 8] = (length as Field * 8).to_be_bytes();
    for i in 0..8 {
        padded[blocks * 64 - 8 + i] = bit_length[i];
    }
    let mut state = SHA256_IV;
    for b in 0..(N + 8) / 64 + 1 {
        let mut block = [0; 16];
        for w in 0..16 {
            let mut word = 0;
            for i in 0..4 {
                word = word * 256 + padded[64 * b + 4 * w + i] as Field;
            }
            block[w] = word as u32;
        }
        let next = sha256_compression(block, state);
        if b < blocks {
            state = next;
        }
    }
    let mut digest = [0; 32];
    for w in 0..8 {
        let word: [u8; 4] = (state[w] as Field).to_be_bytes();
        for i in 0..4 {
            digest[4 * w + i] = word[i];
        }
    }
    digest
}

fn halves(bytes: [u8; 32]) -> [Field; 2] {
    let mut high = 0;
    let mut low = 0;
    for i in 0..16 {
        high = high * 256 + bytes[i] as Field;
        low = low * 256 + bytes[16 + i] as Field;
    }
    [high, low]
}

mod tests {
    use super::{
        Assertion, configuration_commitment, main, MAX_AUTHENTICATOR_DATA_LENGTH,
        MAX_CLIENT_DATA_JSON_LENGTH, PasskeyConfiguration,
    };
    use pcash_protocol::authorization::statement::{
        assert_rule_statement, authorization_commitment, RULE_STATEMENT_LENGTH,
        transfer_action_commitment,
    };
    use pcash_protocol::ledger::note::{
        note_body_commitment, nullifier_key_commitment, owner_commitment,
    };
    use pcash_protocol::ledger::private_value::{
        private_value_commitment, SLOT_CLASS_NATIVE, SmallPrivateValue,
    };
    use reference_rule_common::test_support::{
        NO_NATIVE_BURN, small_transaction, TEST_CONFIGURATION, TEST_NK_ROOT, TEST_PCASH_CHAIN_ID,
        TEST_RECENT_BLOCK, TEST_RECIPIENT, TEST_SIGNER,
    };

    // A P-256 key generated with WebCrypto; it made SIGNATURE below.
    global PASSKEY: PasskeyConfiguration = PasskeyConfiguration {
        domain: TEST_CONFIGURATION,
        key_x: [
            0x7d, 0xbd, 0x5c, 0x48, 0x0e, 0x2e, 0x42, 0xf3, 0xf2, 0x30, 0x42, 0xe0, 0x5d, 0x78,
            0x4e, 0xd2, 0xf4, 0xd6, 0xb0, 0x8f, 0xee, 0xe6, 0xda, 0x3b, 0x7d, 0xe3, 0xb2, 0x2f,
            0xbb, 0x44, 0x88, 0x3e,
        ],
        key_y: [
            0xb3, 0xb6, 0x09, 0x67, 0x02, 0x09, 0x7d, 0x52, 0xe5, 0xd7, 0xfc, 0xa2, 0xd4, 0x54,
            0xfe, 0x29, 0x9a, 0x85, 0xb1, 0xfd, 0x11, 0x59, 0xe0, 0x88, 0x04, 0x35, 0x2a, 0x9f,
            0x46, 0x08, 0xaf, 0x1d,
        ],
    };
    // Another WebCrypto P-256 key.
    global OTHER_PASSKEY: PasskeyConfiguration = PasskeyConfiguration {
        domain: TEST_CONFIGURATION,
        key_x: [
            0xb2, 0x1e, 0x53, 0x3b, 0xe5, 0x2d, 0x4d, 0xbb, 0x45, 0x0c, 0x23, 0xec, 0x81, 0x02,
            0x0e, 0x98, 0x5c, 0xcf, 0x7c, 0x3f, 0xed, 0x9e, 0x8c, 0x50, 0xff, 0xac, 0xc0, 0x84,
            0xf9, 0xb3, 0xae, 0x5e,
        ],
        key_y: [
            0x70, 0x5c, 0x20, 0x2f, 0xb4, 0xe8, 0x5c, 0x65, 0x39, 0x3b, 0x80, 0x87, 0xef, 0xca,
            0xc0, 0x32, 0x73, 0x90, 0xae, 0x7e, 0x80, 0xc5, 0xc2, 0x5e, 0x68, 0x7d, 0x11, 0x7a,
            0x3c, 0x35, 0xaf, 0xd2,
        ],
    };

    // sha256("wallet.example") ‖ flags UP|UV ‖ signCount 0.
    global AUTHENTICATOR_DATA: [u8; 37] = [
        0xf3, 0x4f, 0x7f, 0xb9, 0x9d, 0x0c, 0x0e, 0x35, 0xe4, 0xdc, 0xd9, 0xe3, 0x37, 0x70, 0x0b,
        0xbc, 0x66, 0xbb, 0xc6, 0x4e, 0xad, 0x5e, 0x3f, 0x67, 0x49, 0x68, 0xfe, 0xac, 0x21, 0x03,
        0x44, 0x55, 0x05, 0x00, 0x00, 0x00, 0x00,
    ];
    // The challenge is base64url of the EIP-712 digest of `payment(1000)`, which
    // the SDK's paymentTypedData and pcashSigningHash also produce.
    global CLIENT_DATA_JSON: str<135> = "{\"type\":\"webauthn.get\",\"challenge\":\"-4of8Yllm_WmMttqxjmwNLkmmF-gqdSpr3Icy7g1eus\",\"origin\":\"https://wallet.example\",\"crossOrigin\":false}";
    // The passkey's signature, s normalized to the lower half of the order.
    global SIGNATURE: [u8; 64] = [
        0x0f, 0xe3, 0x58, 0xa1, 0xcc, 0x99, 0x4c, 0x07, 0x54, 0xc8, 0xde, 0x52, 0x8d, 0x94, 0x93,
        0xff, 0xf0, 0xbf, 0xa3, 0xbe, 0xb5, 0x36, 0xb1, 0x74, 0xf0, 0x11, 0x48, 0x33, 0x32, 0x1b,
        0xa2, 0xfd, 0x6c, 0x18, 0x69, 0xae, 0x1b, 0x16, 0xbf, 0xf5, 0x69, 0x45, 0xb3, 0x7c, 0x55,
        0xd2, 0xe4, 0x50, 0x94, 0xfd, 0xdf, 0x1d, 0xc4, 0x78, 0x65, 0xcf, 0x61, 0xf9, 0xf7, 0x21,
        0x0f, 0x6f, 0x2c, 0x15,
    ];

    fn assertion() -> Assertion {
        let mut authenticator_data = [0; MAX_AUTHENTICATOR_DATA_LENGTH];
        for i in 0..37 {
            authenticator_data[i] = AUTHENTICATOR_DATA[i];
        }
        let json = CLIENT_DATA_JSON.as_bytes();
        let mut client_data_json = [0; MAX_CLIENT_DATA_JSON_LENGTH];
        for i in 0..135 {
            client_data_json[i] = json[i];
        }
        Assertion {
            authenticator_data,
            authenticator_data_length: 37,
            client_data_json,
            client_data_json_length: 135,
            type_offset: 1,
            challenge_offset: 23,
            signature: SIGNATURE,
        }
    }

    // TEST_SIGNER's account pays `amount` to TEST_RECIPIENT with an open fee of 5.
    fn payment(amount: Field) -> SmallPrivateValue {
        let mut tx = small_transaction(5, 2000000000);
        tx.input_slot_classes[0] = SLOT_CLASS_NATIVE;
        tx.input_commitments[0] = 0x71;
        tx.output_slot_classes[0] = SLOT_CLASS_NATIVE;
        tx.output_body_commitments[0] =
            note_body_commitment(owner_commitment(TEST_RECIPIENT, 0x5001), 0, amount);
        tx
    }

    fn run(
        configuration: PasskeyConfiguration,
        assertion: Assertion,
        amount: Field,
    ) -> [Field; RULE_STATEMENT_LENGTH] {
        main(
            TEST_PCASH_CHAIN_ID,
            TEST_RECENT_BLOCK,
            TEST_SIGNER,
            configuration,
            TEST_NK_ROOT,
            assertion,
            TEST_RECIPIENT,
            amount,
            0,
            0,
            0,
            NO_NATIVE_BURN,
            0,
            payment(amount),
            0,
            0x5001,
            0,
        )
    }

    #[test]
    fn accepts_the_passkey_signature() {
        let statement = run(PASSKEY, assertion(), 1000);
        // What the transfer kernel requires of the account with this rule installed.
        assert_rule_statement(
            statement,
            authorization_commitment(
                TEST_SIGNER,
                configuration_commitment(PASSKEY, nullifier_key_commitment(TEST_NK_ROOT)),
            ),
            transfer_action_commitment(
                TEST_PCASH_CHAIN_ID,
                private_value_commitment(payment(1000)),
            ),
            TEST_RECENT_BLOCK,
            0,
        );
    }

    #[test(should_fail_with = "passkey signature must be valid")]
    fn rejects_another_passkey() {
        let _ = run(OTHER_PASSKEY, assertion(), 1000);
    }

    // The assertion approves a payment of 1000, not 999.
    #[test(should_fail_with = "client data challenge must be the payment digest")]
    fn rejects_a_signature_over_another_payment() {
        let _ = run(PASSKEY, assertion(), 999);
    }

    // The signature covers the client data, not just its challenge.
    #[test(should_fail_with = "passkey signature must be valid")]
    fn rejects_altered_client_data() {
        let mut altered = assertion();
        altered.client_data_json[100] = 0x58;
        let _ = run(PASSKEY, altered, 1000);
    }

    // Authenticators return either s; the wallet replaces a high s with n - s.
    #[test(should_fail_with = "passkey signature must be valid")]
    fn rejects_a_high_s_signature() {
        let mut high = assertion();
        high.signature = [
            0x0f, 0xe3, 0x58, 0xa1, 0xcc, 0x99, 0x4c, 0x07, 0x54, 0xc8, 0xde, 0x52, 0x8d, 0x94,
            0x93, 0xff, 0xf0, 0xbf, 0xa3, 0xbe, 0xb5, 0x36, 0xb1, 0x74, 0xf0, 0x11, 0x48, 0x33,
            0x32, 0x1b, 0xa2, 0xfd, 0x93, 0xe7, 0x96, 0x50, 0xe4, 0xe9, 0x40, 0x0b, 0x96, 0xba,
            0x4c, 0x83, 0xaa, 0x2d, 0x1b, 0xaf, 0x27, 0xe9, 0x1b, 0x8f, 0xe2, 0x9f, 0x38, 0xb5,
            0x91, 0xbf, 0xd3, 0xa1, 0xec, 0xf3, 0xf9, 0x3c,
        ];
        let _ = run(PASSKEY, high, 1000);
    }
}

Use it from an app

passkeyRuleSet builds the account's new rule set, the default rules plus the passkey rule at entry 10, from the passkey's key and the compiled circuit's verification-key hash. installPasskeyRule sends the account update, which the account's Ethereum key signs through the default admin rule. payWithPasskey builds a payment that selects the passkey rule, gets the passkey's signature over the payment digest, converts the signature to the form the circuit takes and proves the transaction.

// Sketch: install the passkey rule on a user account, then pay with it.
// Example only: unaudited, not for real funds.
import { authorizeUserAccountUpdate, buildNativeTransfer, fm, prepareUserAccountUpdate, privateValueMap, type BuildNativeTransferParams, type BuildUserAccountUpdateParams } from "@pcash/sdk/builders";
import { domainTag, poseidon } from "@pcash/sdk/crypto";
import { pcashSigningHash } from "@pcash/sdk/eip712";
import { accountRuleEntryCommitment, buildAccountRuleSet, nullifierKeyCommitment, payoutTransactionContext, type NetworkConfigLike, type WalletProfile } from "@pcash/sdk/protocol";
import { proveTransferTransactionChonk, proveUserAccountUpdateChonk, type ChonkBackend, type ChonkCircuitResolver } from "@pcash/sdk/prover";
import { defaultUserAccountRuleSet, paymentTypedData, referenceDomainSeparatorHalves, type DefaultUserRuleSecrets } from "@pcash/sdk/rules";

/** From registration: the credential ID and the P-256 key, the last 64 bytes of `getPublicKey()`. */
export interface Passkey { credentialId: BufferSource; x: Uint8Array; y: Uint8Array }
export interface Prover { resolve: ChonkCircuitResolver; backend: ChonkBackend } // `resolve` also serves this package
type RuleSet = ReturnType<typeof passkeyRuleSet>;
const SLOT = 10; // entries 0-9 hold the default rules
const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; // P-256 group order
const big = (b: Uint8Array) => BigInt("0x0" + Array.from(b, (x) => x.toString(16).padStart(2, "0")).join(""));
const be32 = (v: bigint) => Array.from(v.toString(16).padStart(64, "0").match(/../g)!, (h) => parseInt(h, 16));
const u8 = (b: ArrayLike<number>, length = b.length) => Array.from({ length }, (_, i) => String(b[i] ?? 0));
/** The default rules plus the passkey rule. Keep `blinder`: every spend rebuilds the entry from it. */
export function passkeyRuleSet(p: { network: NetworkConfigLike; wallet: WalletProfile; secrets: DefaultUserRuleSecrets; passkey: Passkey; applicationVkHash: bigint; blinder: bigint }) {
  const defaults = defaultUserAccountRuleSet(p);
  const domain = referenceDomainSeparatorHalves(p.network);
  const { x, y } = p.passkey;
  const configurationCommitment = poseidon([domainTag("passkey_configuration"), domain.high, domain.low,
    big(x.subarray(0, 16)), big(x.subarray(16)), big(y.subarray(0, 16)), big(y.subarray(16)), nullifierKeyCommitment(p.wallet.nkRoot)]);
  const entry = { entryIndex: SLOT, accountRuleEntryCommitment: accountRuleEntryCommitment(p.applicationVkHash, configurationCommitment, p.blinder) };
  const set = buildAccountRuleSet([...defaults.entries, entry]);
  const rule = { configurationCommitment, commitmentBlinder: p.blinder, slot: SLOT, siblings: set.membership(SLOT).siblings };
  return { defaults, domain, ruleSetCommitment: set.accountRuleSetCommitment, rule };
}

/** Install: an account update approved by the default admin rule, so the account's Ethereum key signs it. */
export async function installPasskeyRule(update: Omit<BuildUserAccountUpdateParams, "proposed" | "rule" | "readableEcdsa">, ruleSet: RuleSet, ethereumSigner: Parameters<typeof authorizeUserAccountUpdate>[1], prover: Prover) {
  const build = await authorizeUserAccountUpdate(prepareUserAccountUpdate({
    ...update,
    proposed: { ruleSetCommitment: ruleSet.ruleSetCommitment, receiveKey: { operation: "keep" } },
    rule: ruleSet.defaults.accountAdminRule, readableEcdsa: { signerAddress: update.current.address },
  }), ethereumSigner);
  const proof = await proveUserAccountUpdateChonk({ ...prover, build, authorizationPackage: "account_rule_admin_ecdsa", authorizationWitnessMap: build.readableEcdsaWitnessMap! });
  return build.encodeTransaction(proof.proof);
}

// Pay through the passkey rule (open issuance route, no private relay). Spend at most three notes:
// with four real inputs the SDK gives change fresh entropy, and the rule requires the derived change secret.
export async function payWithPasskey(transfer: Omit<BuildNativeTransferParams, "ruleSetCommitment" | "rule" | "issuanceOwnerCommitment" | "designatedIssuanceOpening" | "privateRelayPayment">, network: NetworkConfigLike, ruleSet: RuleSet, passkey: Passkey, rpId: string, prover: Prover) {
  const build = buildNativeTransfer({ ...transfer, issuanceOwnerCommitment: 0n, ruleSetCommitment: ruleSet.ruleSetCommitment, rule: ruleSet.rule });
  const tx = build.transaction.global;
  // The challenge is the digest the reference payment rule's Ethereum key would sign.
  const challenge = new Uint8Array(pcashSigningHash(paymentTypedData(network, {
    pcashChainId: build.pcashChainId, recipient: transfer.recipientAddress, amount: transfer.paymentAmount,
    openFeeAmount: tx.openFeeAmount, issuanceRecipient: 0n, issuanceOwnerCommitment: 0n, relayFeeAmount: 0n, relayFeeOwnerCommitment: 0n,
    accountCreationCommitment: tx.accountCreationCommitment, notBefore: tx.notBeforeTimestamp, validUntil: tx.validUntilTimestamp,
    transactionContext: payoutTransactionContext(build.pcashChainId, build.transaction.inputs.map((input) => input.nullifier), build.shape),
  }, build.burn)));
  const credential = await navigator.credentials.get({ publicKey: { challenge, rpId, userVerification: "required", allowCredentials: [{ type: "public-key", id: passkey.credentialId }] } });
  const response = (credential as PublicKeyCredential).response as AuthenticatorAssertionResponse;
  const authenticatorData = new Uint8Array(response.authenticatorData);
  const clientData = new Uint8Array(response.clientDataJSON);
  const json = new TextDecoder().decode(clientData);
  // DER (0x30 len 0x02 rLen r 0x02 sLen s) to r ‖ s, with s below N / 2 as the circuit requires.
  const der = new Uint8Array(response.signature), rEnd = 4 + der[3]!;
  const s = big(der.subarray(rEnd + 2, rEnd + 2 + der[rEnd + 1]!));
  const signature = [...be32(big(der.subarray(4, rEnd))), ...be32(s > N / 2n ? N - s : s)];
  const witness = {
    pcash_chain_id: fm(build.pcashChainId), recent_pcash_block_hash: fm(build.recentPcashBlockHash), address: fm(build.address),
    configuration: { domain: { domain_separator_high: fm(ruleSet.domain.high), domain_separator_low: fm(ruleSet.domain.low) }, key_x: u8(passkey.x), key_y: u8(passkey.y) },
    nk_root: fm(transfer.wallet.nkRoot),
    assertion: {
      authenticator_data: u8(authenticatorData, 128), authenticator_data_length: fm(authenticatorData.length),
      client_data_json: u8(clientData, 320), client_data_json_length: fm(clientData.length),
      type_offset: fm(json.indexOf('"type":')), challenge_offset: fm(json.indexOf('"challenge":')), signature: u8(signature),
    },
    recipient: fm(transfer.recipientAddress), amount: fm(transfer.paymentAmount), issuance_recipient: fm(0n),
    relay_fee_amount: fm(0n), relay_fee_owner_commitment: fm(0n),
    native_burn: { network_fee_amount: fm(build.burn.networkFeeAmount), voluntary_burn_amount: fm(build.burn.voluntaryBurnAmount) },
    native_change_amount: fm(build.scenario.changeAmount!), private_value: privateValueMap(build.transaction),
    issuance_note_secret: fm(0n), recipient_note_secret: fm(build.outputNoteSecrets[0]!), event_entry: fm(build.eventOpening.eventEntry),
  };
  const proof = await proveTransferTransactionChonk({ ...prover, build, authorizationPackage: "example_passkey_wallet", authorizationWitnessMap: witness });
  return build.encodeTransaction(proof.proof);
}

Limits

  • The passkey prompt names only the site, not the payment. The app's page decides what gets signed, so that page, and any script running on a page allowed to use the passkey, is trusted with every payment.
  • The rule approves native PCASH payments only. Token payments, rule changes and other actions still go through the account's default Ethereum-key rules, which stay installed, and an account is only as safe as the weakest rule it has.
  • A user account is created with an Ethereum key, and this rule is added beside it. Making the passkey the only key would take passkey versions of the other rules, including one for account updates. Removing the default rules without one leaves the rule set unable to change.
  • The circuit checks the client data's type and challenge, the user-present and user-verified flags, and the signature. It doesn't check the origin, the site's ID hash or the signature counter.
  • Client data longer than 320 bytes or authenticator data longer than 128 bytes is rejected.
  • With the SDK as it is, a payment can spend at most three notes. When all four input slots hold notes, the SDK gives the change note a random secret, and this rule requires the derived one.
  • The circuit is about 192,000 gates, against about 157,000 for the default payment rule. Both fit the same proving setup.

Run the tests

nargo test --program-dir examples/passkey-wallet checks that the circuit accepts a real passkey signature and rejects another key, another payment, altered client data and a signature the app did not convert, and just test-examples-noir runs every example's tests.

The spec defines what the rule relies on: account-rule entries, the rule statement, action commitments and user-account updates.