# Module BSV::Auth::Nonce <a id="module-BSV-Auth-Nonce"></a>

Nonce creation and verification for BRC-31 mutual authentication.

A nonce is a 48-byte value: 16 random bytes concatenated with a 32-byte
HMAC-SHA256 over those 16 bytes, base64-encoded. The HMAC is computed with the
wallet using protocol [2, 'server hmac'] and the raw bytes as the key ID
(decoded to a string). This makes nonces self-authenticating —only the wallet
that created a nonce can verify it.

The key ID is derived by decoding the 16 random bytes as UTF-8, replacing any
invalid byte sequences with the Unicode replacement character (U+FFFD). This
matches the ts-sdk behaviour (TextDecoder in non-fatal replacement mode).
Since nonces are always self-verified (counterparty='self'), the key ID
encoding does not need to be interoperable across SDK implementations.

## Constants
### `PROTOCOL_ID` <a id="constant-PROTOCOL_ID"></a> <a id="PROTOCOL_ID-constant"></a>
Not documented.

### `RANDOM_BYTES` <a id="constant-RANDOM_BYTES"></a> <a id="RANDOM_BYTES-constant"></a>
Not documented.

## Public Class Methods
### `create(wallet, counterparty = 'self')` <a id="method-c-create"></a> <a id="create-class_method"></a>
Creates a self-authenticating nonce.
- **@param** `wallet` [BSV::Wallet::Interface] wallet with HMAC capability
- **@param** `counterparty` [String] counterparty ('self', 'anyone', or public key hex).
Defaults to 'self' — nonces are self-verified by the creating wallet.
- **@return** [String] base64-encoded nonce (48 bytes: 16 random + 32 HMAC)

### `decode_as_utf8(bytes)` <a id="method-c-decode_as_utf8"></a> <a id="decode_as_utf8-class_method"></a>
Decodes a binary string as UTF-8, replacing invalid byte sequences with the
Unicode replacement character (U+FFFD). Used to derive the HMAC key ID from
the random nonce bytes in a way consistent with the ts-sdk's use of
TextDecoder (non-fatal mode).
- **@param** `bytes` [String] binary (ASCII-8BIT) string
- **@return** [String] UTF-8 encoded string

### `verify(nonce, wallet, counterparty = 'self')` <a id="method-c-verify"></a> <a id="verify-class_method"></a>
Verifies that a nonce was created by the given wallet.
- **@param** `nonce` [String] base64-encoded nonce to verify
- **@param** `wallet` [BSV::Wallet::Interface] wallet
- **@param** `counterparty` [String] counterparty — must match the value used
when the nonce was created (typically 'self')
- **@return** [Boolean] true if the nonce is valid
