Skip to content

Latest commit

 

History

History
2554 lines (1989 loc) · 158 KB

0100.md

File metadata and controls

2554 lines (1989 loc) · 158 KB

BRC-100: Unified, Vendor-Neutral, Unchanging, and Open BSV Blockchain Standard Wallet-to-Application Interface

Abstract

We define the BSV Blockchain's standard wallet-to-application interface. This interface defines a robust and secure communication protocol between BSV wallets and applications. This protocol, built on the MetaNet architectural principles, aims to standardize the interaction between wallets and decentralized applications in the BSV ecosystem. The interface is designed to be vendor-neutral, supporting a wide range of implementations, ensuring interoperability, and promoting openness across different wallet and app vendors.

Motivation

Computing has long been subject to shortfalls in the areas of information centralization and architectural cross-compatibility. Users on the internet struggle with complex and insecure authentication systems which leave them vulnerable and leak their data. Websites rely on advertising to monetize their offerings, but ads warp the incentives of platforms and creators in ways that ultimately harm everyone involved. By defining a standard interface by which users can identify themselves, protect their data and engage in e-commerce with Bitcoin, this standard offers a solution to problems that have long plagued the existing model.

Primary Objectives

  1. Standardization: The interface provides a consistent and standardized API that ensures that any application can integrate with any compliant wallet without needing custom adaptations.

  2. Vendor-Neutrality: The interface abstracts the underlying wallet implementation, allowing applications to work seamlessly with wallets from different vendors.

  3. Open Specification: The interface is openly documented, encouraging community adoption, and providing a bedrock foundation atop which anyone can build with confidence, knowing the interface will remain constant.

  4. Security and Privacy: Emphasizing secure handling of keys, transactions, and data through the use of secure cryptographic protocols and minimal exposure of sensitive information.

  5. Comprehensive Functionality: The interface covers a broad range of functionalities, from transaction creation, signing, and broadcasting, to identity management, encryption, and digital signatures.

Foundational Requirements

SECTION TL;DR: We use the BSV Blockchain. We use the secp256k1 elliptic curve. We use compressed, DER-formatted public keys. We use BKDS key derivation. We use BRC-43 for security levels, protocol IDs, key IDs, and counterparties (with BRC-44 protocols reserved for internal wallet use). We subscribe to the BRC-45 idea that "Outputs are tokens". We use BRC-46 output baskets for tracking tokens. For categorization and filtering purposes, we allow transactions to be given a set of labels, and outputs to be given a set of tags. We utilize the BRC-67 rules for SPV validation. We use the BEEF standard outlined in BRC-62 for representing transactions. For encryption and decryption, we use the methods described in BRC-2. For creating digital signatures, we use the methods described in BRC-3. For HMACs, we derive symmetric keys as in BRC-2, but then use them for HMAC operations instead of AES-GCM encryption. For the digital certificate structure and field encryption scheme, we use BRC-52. For internalizing payment outputs that increase the user's wallet balance, we employ the key derivation protocol described within BRC-29. For revealing key linkages, we employ the two methods described within BRC-69, and we protect this information as described in BRC-72. These foundational prerequisites allow us to fully define and specify the behavior and functionality of the digital wallet system.

Section Overview

The Wallet Interface is built upon a set of essential foundational standards and protocols that define the underlying architecture, cryptographic operations, and key management systems required for a robust and coherent wallet-to-application interface within the BSV ecosystem. This section thoroughly explains these foundational requirements, incorporating relevant content from the preceding BRCs to provide a holistic understanding of the interface's structure.

1. Key Derivation using BKDS with BRC-42

At the heart of the Wallet Interface lies the BRC-42: BSV Key Derivation Scheme. This scheme defines how keys are derived between two interacting parties. BKDS leverages the secp256k1 elliptic curve and enables participants to derive multiple unique public-private key pairs from a shared master key.

Identity Keys:

  • Each wallet has an everyday master private key and a corresponding master public key derived from the secp256k1 elliptic curve. The public key is known as the "identity key".
  • Additionally, there's a whole secondary "privileged mode" keyring for sensitive operations, allowing these privileged keys to be treated with higher security than the user's everyday keyring.

Key Derivation Process:

  • When deriving a key for a payment or exchange, the sender computes an elliptic curve Diffie-Hellman (ECDH) shared secret using their private key and the recipient's public key.
  • The shared secret is then used to generate a scalar through HMAC and convert it to a point on the elliptic curve.
  • This point is combined with the recipient's master public key to produce a child public key.

Key Privacy:

  • No information about the derived private key is exposed until actually used. This ensures that only the recipient can derive the private key corresponding to the public key provided by the sender.

Expanding Key Universes:

  • With BKDS, wallets can create a virtually unlimited number of unique key pairs through simple modifications of the derivation inputs (e.g., invoice numbers). This open-ended invoice numbering scheme is baked into the Wallet Interface, facilitating custom, flexible key derivation for transactions, signatures, and encryption.

2. Security Levels and Protocol IDs with BRC-43

BRC-43 plays a vital role in organizing how keys are used and accessed in the wallet. This standard introduces Security Levels, Protocol IDs, Key IDs, and Counterparties rules that govern key derivation, permissions, and data access within standard wallets.

Security Levels:

  • Security levels determine the required user permissions and access controls for a derived key:
    • Level 0: No restrictions, open access.
    • Level 1: Requires a level of user authorization that applies across all counterparties who use the same protocol.
    • Level 2: Restricts key usage to specific counterparties and requires individual permission for each.

Protocol IDs & Key IDs:

  • Protocol IDs further define the usage context for a derived key, such as "Document Signing" or "Encryption".
  • A Key ID is a unique identifier that differentiates specific keys under the same Protocol ID, allowing numerous derived keys under the same context but with different purposes.

Counterparties:

  • Counterparties are entities with whom keys are shared (sender, receiver, etc.). For instance, the interface allows single-party self-derivations where a sender and receiver are the same (useful for internal key operations) and anyone-derivations denoted by the private key 1 (for public operations).

Permission System:

  • Permission grants are managed transparently by the wallet and include expiration times, user notifications, and granularity based on the security level. This ensures that applications receive only the delineated keys they need and no more.

3. Reserved Internal Protocols with BRC-44

BRC-44 discusses Admin-reserved and Prohibited Key Derivation Protocols that are exclusive to administrative use by the wallet. These reserved protocols prevent application access to key derivation operations that are inherently internal and crucial to wallet security and integrity.

Internal Protocol Guidelines:

  • Any protocol ID that begins with admin is off-limits for external applications.
  • The Wallet Interface requires that this reserved protocol space is never exposed to or invoked by third-party applications, maintaining the separation between user-facing operations and internal wallet functionalities.

4. Tokenization of UTXOs with BRC-45

BRC-45 defines UTXOs as Tokens, asserting that Unspent Transaction Outputs (UTXOs) are the base units of tokenization within Bitcoin. This principle is integral to the interface, where UTXOs serve as tokens that can be managed within wallets using custom baskets, as discussed below.

Transaction Outputs as Tokens:

  • UTXOs represent discrete token units that can be transferred directly from sender to recipient. Their validity and legitimacy can be independently verified by anyone receiving the transaction.
  • The Wallet Interface relies on the UTXO model for scalability, decentralization, and minimizing trust.

Simplified Payment Verification (SPV):

  • The wallet interface integrates transaction validation protocols that follow BRC-67's SPV method. By validating UTXOs through matching txid and proof inclusion within the blockchain, wallets can quickly confirm that tokens are genuine without needing the entire chain.

5. Tracking and Managing Outputs with BRC-46

To facilitate complex tracking and interaction with UTXOs, BRC-46 establishes Wallet Transaction Output Tracking (Output Baskets) within the interface.

Baskets:

  • Baskets are conceptual containers for grouping UTXOs, creating an easy-to-manage structure for tracking specific outputs used across applications or protocols.
  • A wallet must support basket management, including returning transaction outputs from a given basket, customizing outputs with relevant instructions, and spending or relinquishing them.

Permissions:

  • Like with key derivation, permissioning is enforced for applications executing operations involving baskets. The security model here follows from BRC-43, ensuring consistency across the system.
  • Wallets must ensure that users have given consent before listing the outputs from a given basket, creating transactions that insert outputs into a basket, or internalizing transactions that facilitate output insertion into baskets.

6. Transaction Verification with BRC-67 and BRC-62

Authenticated transaction verification is critical in wallet operations, and this builds, in part, on BRC-67: Simplified Payment Verification and BRC-62: Background Evaluation Extended Format (BEEF) Transactions.

BEEF Data Structure:

  • The BEEF format specified in BRC-62 is optimized for SPV and designed for efficient data transmission, focusing on economy of information while retaining verification integrity.
  • Wallets should utilize BEEF when constructing, communicating, and validating transactions. BEEF supports streaming validation, enabling the wallet to begin verifying a transaction as soon as its data begins transmission.

Verification Steps:

  • BRC-67 outlines the steps to be undertaken for verifying a transaction, including script validation, fee checking, sequence, and locktime examination. These checks ensure that transactions processed through the wallet interface are legitimate and contextually accurate.

SPV Empowerment:

  • The SPV model allows lightweight wallet clients to verify the chain, making them resistant to fraud while not requiring them to store or access all blockchain data.

7. Data Security with BRC-2 for Encryption and Decryption

Security is paramount in the Wallet Interface, and BRC-2 defines Encryption and Decryption operations encapsulated within the interface's cryptographic functionality.

AES-256-GCM Encryption:

  • Wallets employ AES-256-GCM for symmetric encryption, where the derived shared secret between the sender's and recipient's child keys becomes the basis for the encryption key.

Encryption & Decryption Process:

  • Wallets use their private keys and their counterparty's public keys (derived through BKDS) to encrypt data under a given protocol ID and key ID. Similarly, upon receipt, the recipient decrypts the data using their private key combined with the sender's public key.

Confidentiality Assurance:

  • Encryption through this interface ensures the confidentiality of transmitted data and can be applied for user-specific actions like private document exchange (shielded with encryption keys derived from BKDS).

8. Authorized Digital Signatures with BRC-3

The Wallet Interface supports digital signing functionalities defined in BRC-3: Digital Signature Creation and Verification.

Digital Signature Process:

  • BRC-3 mandates use of ECDSA over secp256k1 keys.
  • Derived child keys (from BKDS) are used to sign data based on the security levels, protocol IDs, and key IDs defined in BRC-43.

Private & Public Signatures:

  • Wallets can create private digital signatures intended for a specified receiver, by naming them as a counterparty.
  • It's also possible to create publicly verifiable signatures, simply by naming anyone as the counterparty.

Verification:

  • The signature is verifiable by the recipient using derived public keys. The recipient uses BRC-43 mechanics to derive the corresponding public key and validates the signature using this key over the provided data.

9. Identity Certificates and Selective Revelation with BRC-52

BRC-52 defines Identity Certificates, which incorporate selective revelation protocols that wallets must support.

Certificate Structure:

  • Identity certificates encapsulate a subject's identity information, certified by a trusted entity, with fields selectively encryptable to preserve user privacy.

Selective Revelation:

  • Wallets must facilitate keyring management for applications to reveal or withhold certificate fields selectively. The wallet keeps a copy of the master keyring, transmitting only the necessary revelation keys to authorized parties in an encrypted form.

Revocation Mechanism:

  • Identity certificate revocation is implemented via UTXO tracking. If the UTXO tied to a revocation outpoint is spent, everyone considers the certificate invalid—this adds an additional layer of trust and decentralized authority, depending on the constraints placed upon the UTXO.

10. Payment Internalization with BRC-29

The Wallet Interface incorporates support for BRC-29: Simple Authenticated BSV P2PKH Payment Protocol, which standardizes how payments are derived, handled, and internalized within the wallet.

Payment Key Derivation:

  • BKDS Integration: Payments utilize keys derived through BKDS. They are based on a combination of transaction-specific data (such as a unique derivation prefix) and counterparty public keys. The derived keys are used to generate P2PKH scripts, ensuring that only the intended recipient can derive the corresponding private keys for spending.

Internalization Process:

  • Decoding and Deriving Keys: Upon receiving a payment message, the wallet decodes the message, derives the necessary private keys using the provided derivationPrefix and derivationSuffix, checks the scripts match, and processes the UTXOs.
  • Baskets and Custom Instructions: Non-P2PKH outputs with custom scripts can be directed into specific baskets, enabling organized tracking within the wallet. Custom instructions attached to UTXOs are also stored and can be used by applications for token history tracking or future spending.
  • SPV Verification: Regardless of whether a payment increments a user's wallet balance via BRC-29, inserts outputs into custom baskets with tags and custom instructions, or both, the wallet always employs BRC-67 to confirm the transaction's validity according to the rules of SPV.

Flexible Payment Handling:

  • Multiple Outputs and Transactions: BRC-29 supports handling multiple outputs and even transactions within a single "payment." Each transaction output can be individually indexed with a unique derivation suffix, allowing the wallet to differentiate and manage multiple outputs efficiently, while all outputs within one given payment share a common derivation prefix.

11. Auditability and Key Linkage Revelations with BRC-69 and BRC-72

The Wallet Interface incorporates methods to enhance transparency and auditability through BRC-69: Revealing Key Linkages, while ensuring the protection of sensitive data during transit with BRC-72: Protecting BRC-69 Key Linkage Information in Transit.

Key Linkage Revelations:

  • BKDS Based Key Linkage: BRC-69 outlines two methods for revealing key linkages from BKDS derived keys. The first method allows wallets to reveal a root ECDH shared secret between a user's identity key and another counterparty's key, enabling anyone to link all interactions between them. The second method reveals the specific key offset for individual derived child keys, enabling audit trails while preserving privacy in other contexts.

Protection of Linkage Information:

  • BRC-72 Integration: Protecting sensitive linkage data is paramount. BRC-72 specifies mechanisms for encrypting key linkage revelations when they are in transit. This encryption is done using the BRC-2 AES-256-GCM method, ensuring that only authorized verifiers (recipients) can decrypt and access the linkage data. This preserves privacy and security, even when key linkages must be revealed for audit or verification purposes.

  • Additionally, BRC-94 proofs help overcome the limitations described in BRC-93. BRC-97 allows for future zero-knowledge proof types to be used in the context of specific key linkage revelation as technology develops.

The foundational BRCs integrated into this Wallet Interface ensure security, scalability, and flexibility across operations performed within the BSV ecosystem. These frameworks from key derivation, rigorous cryptographic principles, selective identity verification, tokenization, secure payments, and audit trails through linkage revelations all combine to form a robust and future-proof digital wallet architecture. The next section defines the high-level structure of the wallet interface.

Interface Structure

The interface comprises numerous methods that cater to different functional areas related to wallet operations and application needs. The methods are grouped for easier understanding:

Transaction Operations:

  • Creation: createAction allows for constructing complex Bitcoin transactions with multiple inputs, outputs, and options that customize how the transaction behaves, such as whether it should be broadcast or only partially built.
  • Signing: signAction allows for signing and processing previously created transactions from the createAction method.
  • Aborting: abortAction facilitates the cancellation of transactions that have not yet been completed.
  • Internalization: internalizeAction enables wallets to accept and manage incoming transactions by parsing, tagging, and organizing outputs.
  • Listing: listActions and listOutputs allow querying transactions and outputs based on specific criteria like labels, baskets, and tags.
  • Relinquishment: relinquishOutput releases an output from a basket tracked by the wallet, even if it has yet to be spent.

Public Key Management:

  • Key Retrieval: getPublicKey facilitates the retrieval of public keys, be they derived keys based on protocols or the user's main identity keys.
  • Key Linkage: Methods revealCounterpartyKeyLinkage and revealSpecificKeyLinkage disclose key relationships, essential for identity verification and the auditing of interactions between parties.

Cryptography Operations:

  • Encryption/Decryption: encrypt and decrypt methods implement secure encryption and decryption of data using derived keys and consistent protocol definitions, enabling private exchanges of information between counterparties.
  • HMAC Operations: createHmac and verifyHmac allow for the creation and verification of Hash-based Message Authentication Codes (HMAC) to ensure data integrity.
  • Signatures: createSignature and verifySignature enable the creation and verification of digital signatures, both public and private, essential for validating the authenticity of transactions, documents, and data.

Identity and Certificate Management:

  • Certificate Acquisition: acquireCertificate allows the wallet to obtain identity certificates, either by directly saving them or through a standardized issuance protocol. Conversely, relinquishCertificate allows an old certificate to be removed.
  • Certificate Listing and Discovery: listCertificates, discoverByIdentityKey, and discoverByAttributes enable querying of identity certificates owned by the user or others based on identity keys or specific attributes.
  • Proving Identity Certificates: proveCertificate is utilized in situations where a user's identity or certified attributes need to be proven to a third party.

Blockchain and Network Data:

  • Blockchain Height: getHeight retrieves the current height of the blockchain.
  • Merkle Root Retrieval: getMerkleRootForHeight retrieves the Merkle root at a specific block height.
  • Network and Version Information: getNetwork and getVersion retrieve information about the network (mainnet or testnet) and the wallet's version.

Authentication:

  • User Authentication: isAuthenticated checks the user's authentication status, ensuring they've set up their wallet before operations are attempted.
  • Authentication Wait: waitForAuthentication waits for the user to complete authentication and returns once the wallet has been fully set up.

Data Types and Constraints

To ensure consistency and prevent errors, the interface defines various data types and associated constraints. A few key examples include:

Boolean Types:

  • BooleanDefaultFalse: Defaults to false if not provided.
  • BooleanDefaultTrue: Defaults to true if not provided.

Integer Types:

  • Byte: An integer between 0 and 255.
  • PositiveIntegerOrZero: A non-negative integer with an upper bound of 2^32 - 1.
  • PositiveIntegerMax10: A positive integer between 1 and 10.
  • PositiveIntegerDefault10Max10000: A positive integer that defaults to 10, and has an upper bound of 10000.
  • SatoshiValue: Represents a value in Satoshis, ranging between 1 and 2.1 * 10^15.

String Types:

  • ISOTimestampString: Represents an ISO 8601 format timestamp.
  • HexString: A string containing hexadecimal characters.
  • Base64String: A string in standard base64 encoded format.
  • Specialized Strings: Defined for specific fields, including transactions, descriptions, version strings, certificate field names, etc.

Error Handling and Validation

Errors are raised using a uniform structure containing:

  • status: Denotes the presence of a failure (always "error").
  • code: A short machine-readable string representing the specific error or fault.
  • description: A human-readable explanation of the error.
  • context: (Optional) Additional contextual data relevant to the error---often binary or debug information. When errors occur, they must be communicated and thrown such that they preserve these structural elements. Specific instantiations or realizations of this interface, comprising APIs or transport mechanisms for messages between wallets and applications, must specify how these errors are communicated.

Usage and Best Practices

  • Interoperability: Since the interface is vendor-neutral, developers should ensure they comply fully with the defined types, constraints, and method contracts, allowing their wallets and applications to interface smoothly with others.

  • Use of Privileged Mode: Methods related to the use of keys include options that allow an alternative "privileged access" mode to be used. When implemented, a secondary and more secure set of keys is used instead of the primary ones. This should only be invoked when necessary, and requires proper justification to be provided.

  • Request Originators and Permissions: The interface ensures that operations like key derivation, signing, encryption, certificate field revelation, and transaction creation are conducted with proper authorization by incorporating the request's originator. The wallet can then authenticate the originator and seek user permission if necessary.

Restrictions on Protocol and Basket Namespaces

Protocol IDs and basket names are used to control access to data and assets, respectively. In order to ensure that consistent rules apply across wallet implementations, and to ensure that appropriate reservations are made for future permissions architectures (see BRC-98 and BRC-99), we specify the rules that apply to these namespaces here:

Rules for Protocol Names

Protocol IDs:

  • Must be at least 5 characters
  • Generally must not exceed 400 characters (except for the specific linkage revelation protocol, which is allowed to be up to 430 characters, since it's the only protocol that encapsulates anotherr full protocol name within itself)
  • Must not contain multiple consecutive spaces (e.g., " ")
  • Must only contain lowercase letters, numbers, and spaces
  • Must not end with protocol (this is redundant)
  • Must not start with p (allows for future "specially permissioned" protocols, not contemplated by this specification, see BRC-98)

Key IDs:

  • Must be at least one byte in length
  • Must not exceed 800 bytes in length

Rules for Basket Names

Basket names:

  • Must be at least 5 characters
  • Must be no more than 400 characters
  • Must only contain lowercase letters, numbers, and spaces
  • Must not end with basket (this is redundant)
  • Must not contain consecutive spaces
  • Must not start with admin (allows the wallet to manage assets internal to its operations)
  • Must not be default (some wallets have historically used this for internal operations)
  • Must not start with p (allows for future "specially permissioned" baskets, not contemplated by this specification, see BRC-99)

The Wallet Interface

This interface is specified in TypeScript as follows:

/**
 * @typedef {boolean} BooleanDefaultFalse
 * Represents an optional boolean parameter, which defaults to `false` if not provided.
 */
export type BooleanDefaultFalse = boolean

/**
 * @typedef {boolean} BooleanDefaultTrue
 * Represents an optional boolean parameter, which defaults to `true` if not provided.
 */
export type BooleanDefaultTrue = boolean

/**
 * @typedef {number} Byte
 * Represents an integer from 0 to 255 (inclusive).
 * @minimum 0
 * @maximum 255
 */
export type Byte = number

/**
 * @typedef {number} PositiveIntegerOrZero
 * A positive integer, includes zero and has an upper bound of `2^32 - 1`.
 * @minimum 0
 * @maximum 4294967295
 */
export type PositiveIntegerOrZero = number

/**
 * @typedef {number} PositiveInteger
 * A positive integer that excludes zero, and has an upper bound of `2^32 - 1`.
 * @minimum 1
 * @maximum 4294967295
 */
export type PositiveInteger = number

/**
 * @typedef {number} PositiveIntegerMax10
 * A positive integer that excludes zero, and has an upper bound of 10.
 * @minimum 1
 * @maximum 10
 */
export type PositiveIntegerMax10 = number

/**
 * @typedef {number} PositiveIntegerDefault10Max10000
 * A positive integer that defaults to 10, and has an upper bound of 10000.
 * @minimum 1
 * @default 10
 * @maximum 10000
 */
export type PositiveIntegerDefault10Max10000 = number

/**
 * @typedef {number} SatoshiValue
 * Represents a value in Satoshis, constrained by the max supply of Bitcoin (2.1 * 10^15 Satoshis).
 * @minimum 1
 * @maximum 2100000000000000
 */
export type SatoshiValue = number

/**
 * @typedef {string} ISOTimestampString
 * Represents an ISO timestamp string.
 */
export type ISOTimestampString = string

/**
 * @typedef {string} HexString
 * A string containing only hexadecimal characters (0-9, a-f).
 */
export type HexString = string

/**
 * @typedef {HexString} TXIDHexString
 * Represents a transaction ID, enforced to be exactly 64 characters in length and in hexadecimal format.
 * @length 64
 */
export type TXIDHexString = HexString

/**
 * @typedef {string} OutpointString
 * Represents a transaction ID and output index pair. The TXID is given as a hex string followed by a period "." and then the output index is given as a decimal integer.
 */
export type OutpointString = string

/**
 * @typedef {HexString} PubKeyHex
 * Represents a compressed DER secp256k1 public key, exactly 66 hex characters (33 bytes) in length.
 * @length 66
 */
export type PubKeyHex = HexString

/**
 * @typedef {string} Base64String
 * A standard base64 encoded string.
 */
export type Base64String = string

/**
 * @typedef {string} OriginatorDomainNameString
 * Represents the fully qualified domain name (FQDN) of the application that originates the request.
 */
export type OriginatorDomainNameString = string

/**
 * @typedef {string & { minLength: 5, maxLength: 50 }} DescriptionString5to50Characters
 * A string used for descriptions, with a length between 5 and 50 characters.
 */
export type DescriptionString5to50Characters = string

/**
 * @typedef {string & { maxLength: 300 }} BasketStringUnder300Characters
 * A string for naming baskets, with a maximum length of 300 characters.
 */
export type BasketStringUnder300Characters = string

/**
 * @typedef {string & { maxLength: 300 }} OutputTagStringUnder300Characters
 * A string for tagging outputs, with a maximum length of 300 characters.
 */
export type OutputTagStringUnder300Characters = string

/**
 * @typedef {string & { maxLength: 300 }} LabelStringUnder300Characters
 * A string for labeling transactions, with a maximum length of 300 characters.
 */
export type LabelStringUnder300Characters = string

/**
 * @typedef {Byte[]} BEEF
 * An array of integers, each ranging from 0 to 255, indicating transaction data in BEEF (BRC-62) format.
 */
export type BEEF = Byte[]

/**
 * @typedef {Byte[]} AtomicBEEF
 * An array of integers, each ranging from 0 to 255, indicating transaction data in Atomic BEEF (BRC-95) format.
 */
export type AtomicBEEF = Byte[]

/**
 * @typedef {string & { minLength: 5, maxLength: 400 }} ProtocolString5To400Characters
 * A protocol identifier with a length between 5 and 400 characters.
 */
export type ProtocolString5To400Characters = string

/**
 * @typedef {string & { maxLength: 800 }} KeyIDStringUnder800Characters
 * Represents a key identifier string, with a maximum length of 800 characters.
 */
export type KeyIDStringUnder800Characters = string

/**
 * @typedef {string & { maxLength: 50 }} CertificateFieldNameUnder50Characters
 * Represents a certificate field name with a maximum length of 50 characters.
 */
export type CertificateFieldNameUnder50Characters = string

/**
 * @typedef {string & { maxLength: 100 }} EntityNameStringMax100Characters
 * Represents a trusted entity name with a maximum length of 100 characters.
 */
export type EntityNameStringMax100Characters = string

/**
 * @typedef {string & { maxLength: 500 }} EntityIconURLStringMax500Characters
 * Represents a trusted entity icon URL with a maximum length of 500 characters.
 */
export type EntityIconURLStringMax500Characters = string

/**
 * @typedef {string & { minLength: 7, maxLength: 30 }} VersionString7To30Characters
 * Represents a version string, with a length between 7 and 30 characters.
 *
 * The format is [vendor]-[major].[minor].[patch]
 */
export type VersionString7To30Characters = string

/**
 * @typedef {string & { minLength: 10, maxLength: 40 }} ErrorCodeString10To40Characters
 * Represents a machine-readable error code string, with a length between 10 and 40 characters.
 */
export type ErrorCodeString10To40Characters = string

/**
 * @typedef {string & { minLength: 20, maxLength: 200 }} ErrorDescriptionString20To200Characters
 * Represents a human-readable error description string, with a length between 20 and 200 characters.
 */
export type ErrorDescriptionString20To200Characters = string

/**
 * The Wallet interface defines a wallet capable of various tasks including transaction creation and signing,
 * encryption, decryption, identity certificate management, identity verification, and communication
 * with applications as per the BRC standards. This interface allows applications to interact with
 * the wallet for a range of functionalities aligned with the Babbage architectural principles.
 */
export interface Wallet {
  /**
   * Creates a new Bitcoin transaction based on the provided inputs, outputs, labels, locks, and other options.
   *
   * @param {Object} args - The arguments required to create the transaction.
   * @param {DescriptionString5to50Characters} args.description - A human-readable description of the action represented by this transaction.
   * @param {BEEF} [args.inputBEEF] - BEEF data associated with the set of input transactions from which UTXOs will be consumed.
   * @param {Array<Object>} [args.inputs] - An optional array of input objects used in the transaction.
   * @param {OutpointString} args.inputs[].outpoint - The outpoint being consumed.
   * @param {HexString} args.inputs[].unlockingScript - The unlocking script needed to release the specified UTXO.
   * @param {DescriptionString5to50Characters} args.inputs[].inputDescription - A description of this input for contextual understanding of what it consumes.
   * @param {PositiveIntegerOrZero} [args.inputs[].sequenceNumber] - An optional sequence number applied to the input.
   * @param {PositiveInteger} [args.inputs[].unlockingScriptLength] - Length of the unlocking script, in case it will be provided later using `signAction`.
   * @param {Array<Object>} [args.outputs] - An optional array of output objects for the transaction.
   * @param {HexString} args.outputs[].lockingScript - The locking script that dictates how the output can later be spent.
   * @param {SatoshiValue} args.outputs[].satoshis - Number of Satoshis that constitute this output.
   * @param {DescriptionString5to50Characters} args.outputs[].outputDescription - Description of what this output represents.
   * @param {BasketStringUnder300Characters} [args.outputs[].basket] - Name of the basket where this UTXO will be held, if tracking is desired.
   * @param {string} [args.outputs[].customInstructions] - Custom instructions attached onto this UTXO, often utilized within application logic to provide necessary unlocking context or track token histories.
   * @param {OutputTagStringUnder300Characters[]} [args.outputs[].tags] - Tags assigned to the output for sorting or filtering.
   * @param {PositiveIntegerOrZero} [args.lockTime] - Optional lock time for the transaction.
   * @param {PositiveInteger} [args.version] - Optional transaction version specifier.
   * @param {LabelStringUnder300Characters[]} [args.labels] - Optional labels providing additional categorization for the transaction.
   * @param {Object} [args.options] - Optional settings modifying transaction processing behavior.
   * @param {BooleanDefaultTrue} [args.options.signAndProcess] - Optional. If true and all inputs have unlockingScripts, the new transaction will be signed and handed off for processing by the network; result `txid` and `tx` are valid and `signableTransaciton` is undefined. If false or an input has an unlockingScriptLength, result `txid` and `tx` are undefined and `signableTransaction` is valid.
   * @param {BooleanDefaultTrue} [args.options.acceptDelayedBroadcast] - Optional. If true, the transaction will be sent to the network by a background process; use `noSend` and `sendWith` options to batch chained transactions. If false, the transaction will be broadcast to the network and any errors returned in result; note that rapidly sent chained transactions may still fail due to network propagation delays.
   * @param {'known'} [args.options.trustSelf] - Optional. If `known`, input transactions may omit supporting validity proof data for TXIDs known to this wallet or included in `knownTxids`.
   * @param {TXIDHexString[]} [args.options.knownTxids] - Optional. When working with large chained transactions using `noSend` and `sendWith` options, include TXIDs of inputs that may be assumed to be valid even if not already known by this wallet.
   * @param {BooleanDefaultFalse} [args.options.returnTXIDOnly] - Optional. If true, only a TXID will be returned instead of a transaction.
   * @param {BooleanDefaultFalse} [args.options.noSend] - Optional. If true, the transaction will be constructed but not sent to the network. Supports the creation of chained batches of transactions using the `sendWith` option.
   * @param {Array<OutPoint>} [args.options.noSendChange] - Optional. Valid when `noSend` is true. May contain `noSendChange` outpoints previously returned by prior `noSend` actions in the same batch of chained actions.
   * @param {Array<TXIDHexString>} [args.options.sendWith] - Optional. Sends a batch of actions previously created as `noSend` actions to the network; either synchronously if `acceptDelayedBroadcast` is true or by a background process.
   * @param {BooleanDefaultTrue} [args.options.randomizeOutputs] — optional. When set to false, the wallet will avoid randomizing the order of outputs within the transaction.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise returns different structures based on the outcome: error response, response with TXID, response with transaction, or info about signable transaction (partial BEEF and reference number).
   */
  createAction: (
    args: {
      description: DescriptionString5to50Characters
      inputBEEF?: BEEF
      inputs?: Array<{
        outpoint: OutpointString
        unlockingScript?: HexString
        unlockingScriptLength?: PositiveInteger
        inputDescription: DescriptionString5to50Characters
        sequenceNumber?: PositiveIntegerOrZero
      }>
      outputs?: Array<{
        lockingScript: HexString
        satoshis: SatoshiValue
        outputDescription: DescriptionString5to50Characters
        basket?: BasketStringUnder300Characters
        customInstructions?: string
        tags?: OutputTagStringUnder300Characters[]
      }>
      lockTime?: PositiveIntegerOrZero
      version?: PositiveIntegerOrZero
      labels?: LabelStringUnder300Characters[]
      options?: {
        signAndProcess?: BooleanDefaultTrue
        acceptDelayedBroadcast?: BooleanDefaultTrue
        trustSelf?: 'known'
        knownTxids?: TXIDHexString[]
        returnTXIDOnly?: BooleanDefaultFalse
        noSend?: BooleanDefaultFalse
        noSendChange?: OutpointString[]
        sendWith?: TXIDHexString[]
        randomizeOutputs?: BooleanDefaultTrue
      }
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    txid?: TXIDHexString
    tx?: AtomicBEEF
    noSendChange?: OutpointString[]
    sendWithResults?: Array<{
      txid: TXIDHexString
      status: 'unproven' | 'sending' | 'failed'
    }>
    signableTransaction?: {
      tx: AtomicBEEF
      reference: Base64String
    }
  }>

  /**
   * Signs a transaction previously created using `createAction`.
   *
   * @param {Object} args - Arguments to sign the transaction.
   * @param {Record<PositiveIntegerOrZero, Object>} args.spends - Map of input indexes to the corresponding unlocking script and optional sequence number.
   * @param {HexString} args.spends[].unlockingScript - The unlocking script for the corresponding input.
   * @param {PositiveIntegerOrZero} [args.spends[].sequenceNumber] - The sequence number of the input.
   * @param {Base64String} args.reference - Reference number returned from the call to `createAction`.
   * @param {Object} [args.options] - Optional settings modifying transaction processing behavior.
   * @param {BooleanDefaultTrue} [args.options.acceptDelayedBroadcast] - Optional. If true, transaction will be sent to the network by a background process; use `noSend` and `sendWith` options to batch chained transactions. If false, transaction will be broadcast to the network and any errors returned in result; note that rapidly sent chained transactions may still fail due to network propagation delays.
   * @param {'known'} [args.options.trustSelf] - Optional. If `known`, input transactions may omit supporting validity proof data for TXIDs known to this wallet or included in `knownTxids`.
   * @param {TXIDHexString[]} [args.options.knownTxids] - Optional. When working with large chained transactions using `noSend` and `sendWith` options, include TXIDs of inputs that may be assumed to be valid even if not already known by this wallet.
   * @param {BooleanDefaultFalse} [args.options.returnTXIDOnly] - Optional. If true, only a TXID will be returned instead of a transaction.
   * @param {BooleanDefaultFalse} [args.options.noSend] - Optional. If true, the transaction will be constructed but not sent to the network. Supports the creation of chained batches of transactions using the `sendWith` option.
   * @param {Array<TXIDHexString>} [args.options.sendWith] - Optional. Sends a batch of actions previously created as `noSend` actions to the network; either synchronously if `acceptDelayedBroadcast` is true or by a background process.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise returns an error response or a response with either the completed transaction or TXID.
   */
  signAction: (
    args: {
      spends: Record<
        PositiveIntegerOrZero,
        {
          unlockingScript: HexString
          sequenceNumber?: PositiveIntegerOrZero
        }
      >
      reference: Base64String
      options?: {
        acceptDelayedBroadcast?: BooleanDefaultTrue
        returnTXIDOnly?: BooleanDefaultFalse
        noSend?: BooleanDefaultFalse
        sendWith?: TXIDHexString[]
      }
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    txid?: TXIDHexString
    tx?: AtomicBEEF
    sendWithResults?: Array<{
      txid: TXIDHexString
      status: 'unproven' | 'sending' | 'failed'
    }>
  }>

  /**
   * Aborts a transaction that is in progress and has not yet been finalized or sent to the network.
   *
   * @param {Object} args - Arguments to identify the transaction that needs to be aborted.
   * @param {Base64String} args.reference - Reference number for the transaction to abort.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object indicating the abortion result (either success or error).
   */
  abortAction: (
    args: {
      reference: Base64String
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ aborted: true }>

  /**
   * Lists all transactions matching the specified labels.
   *
   * @param {Object} args - Arguments to specify how to filter or retrieve transactions.
   * @param {LabelStringUnder300Characters[]} args.labels - An array of labels used to filter actions.
   * @param {'any' | 'all'} [args.labelQueryMode] - Specifies how to match labels (default is any which matches any of the labels).
   * @param {BooleanDefaultFalse} [args.includeLabels] - Whether to include transaction labels in the result set.
   * @param {boolean} [args.includeInputs] - Whether to include input details in the result set.
   * @param {boolean} [args.includeInputSourceLockingScripts] - Whether to include input source locking scripts in the result set.
   * @param {boolean} [args.includeInputUnlockingScripts] - Whether to include input unlocking scripts in the result set.
   * @param {boolean} [args.includeOutputs] - Whether to include output details in the result set.
   * @param {boolean} [args.includeOutputLockingScripts] - Whether to include output locking scripts in the result set.
   * @param {PositiveIntegerDefault10Max10000} [args.limit] - The maximum number of transactions to retrieve.
   * @param {PositiveIntegerOrZero} [args.offset] - Number of transactions to skip before starting to return the results.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object containing actions, their metadata, inputs, and outputs if applicable, or an error object.
   */
  listActions: (
    args: {
      labels: LabelStringUnder300Characters[]
      labelQueryMode?: 'any' | 'all'
      includeLabels?: BooleanDefaultFalse
      includeInputs?: BooleanDefaultFalse
      includeInputSourceLockingScripts?: BooleanDefaultFalse
      includeInputUnlockingScripts?: BooleanDefaultFalse
      includeOutputs?: BooleanDefaultFalse
      includeOutputLockingScripts?: BooleanDefaultFalse
      limit?: PositiveIntegerDefault10Max10000
      offset?: PositiveIntegerOrZero
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    totalActions: PositiveIntegerOrZero
    actions: Array<{
      txid: TXIDHexString
      satoshis: SatoshiValue
      status:
      | 'completed'
      | 'unprocessed'
      | 'sending'
      | 'unproven'
      | 'unsigned'
      | 'nosend'
      | 'nonfinal'
      isOutgoing: boolean
      description: DescriptionString5to50Characters
      labels?: LabelStringUnder300Characters[]
      version: PositiveIntegerOrZero
      lockTime: PositiveIntegerOrZero
      inputs?: Array<{
        sourceOutpoint: OutpointString
        sourceSatoshis: SatoshiValue
        sourceLockingScript?: HexString
        unlockingScript?: HexString
        inputDescription: DescriptionString5to50Characters
        sequenceNumber: PositiveIntegerOrZero
      }>
      outputs?: Array<{
        outputIndex: PositiveIntegerOrZero
        satoshis: SatoshiValue
        lockingScript?: HexString
        spendable: boolean
        outputDescription: DescriptionString5to50Characters
        basket: BasketStringUnder300Characters
        tags: OutputTagStringUnder300Characters[]
        customInstructions?: string
      }>
    }>
  }>

  /**
   * Submits a transaction to be internalized and optionally labeled, outputs paid to the wallet balance, inserted into baskets, and/or tagged.
   *
   * @param {Object} args - Arguments required to internalize the transaction.
   * @param {BEEF} args.tx - Atomic BEEF-formatted transaction to internalize.
   * @param {Array<Object>} args.outputs - Metadata about outputs, processed differently based on payment or insertion types.
   * @param {PositiveIntegerOrZero} args.outputs[].outputIndex - Index of the output within the transaction.
   * @param {'payment' | 'insert'} args.outputs[].protocol - Specifies whether the output is a payment (to be received into the wallet balance) or an insert operation (into a particular basket).
   * @param {Object} [args.outputs[].paymentRemittance] - Remittance data, structured accordingly for the payment operation.
   * @param {Base64String} args.outputs[].paymentRemittance.derivationPrefix - Payment-level derivation prefix used by the sender for key derivation (for payments).
   * @param {Base64String} args.outputs[].paymentRemittance.derivationSuffix - Specific output-level derivation suffix used by the sender for key derivation (for payments).
   * @param {PubKeyHex} args.outputs[].paymentRemittance.senderIdentityKey - Public identity key of the sender (for payments).
   * @param {Object} [args.outputs[].insertionRemittance] - Remittance data, structured accordingly for the insertion operation.
   * @param {BasketStringUnder300Characters} args.outputs[].insertionRemittance.basket - Basket in which to place the output (for insertions).
   * @param {string} [args.outputs[].insertionRemittance.customInstructions] - Optionally provided custom instructions attached to the output (for insertions).
   * @param {OutputTagStringUnder300Characters[]} [args.outputs[].insertionRemittance.tags] - Tags attached to the output (for insertions).
   * @param {DescriptionString5to50Characters} args.description - Human-readable description of the transaction being internalized.
   * @param {LabelStringUnder300Characters[]} [args.labels] - Optional labels associated with this transaction.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object indicating the success of the operation or an error object.
   */
  internalizeAction: (
    args: {
      tx: AtomicBEEF
      outputs: Array<{
        outputIndex: PositiveIntegerOrZero
        protocol: 'wallet payment' | 'basket insertion'
        paymentRemittance?: {
          derivationPrefix: Base64String
          derivationSuffix: Base64String
          senderIdentityKey: PubKeyHex
        }
        insertionRemittance?: {
          basket: BasketStringUnder300Characters
          customInstructions?: string
          tags?: OutputTagStringUnder300Characters[]
        }
      }>
      description: DescriptionString5to50Characters
      labels?: LabelStringUnder300Characters[]
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ accepted: true }>

  /**
   * Lists the spendable outputs kept within a specific basket, optionally tagged with specific labels.
   *
   * @param {Object} args - Arguments detailing the query for listing spendable outputs.
   * @param {BasketStringUnder300Characters} args.basket - The associated basket name whose outputs should be listed.
   * @param {OutputTagStringUnder300Characters[]} [args.tags] - Filter outputs based on these tags.
   * @param {'all' | 'any'} [args.tagQueryMode] - Filter mode, defining whether all or any of the tags must match. By default, any tag can match.
   * @param {'locking scripts' | 'entire transactions'} [args.include] - Whether to include locking scripts (with each output) or entire transactions (as aggregated BEEF, at the top level) in the result. By default, unless specified, neither are returned.
   * @param {BooleanDefaultFalse} [args.includeEntireTransactions] - Whether to include the entire transaction(s) in the result.
   * @param {BooleanDefaultFalse} [args.includeCustomInstructions] - Whether custom instructions should be returned in the result.
   * @param {BooleanDefaultFalse} [args.includeTags] - Whether the tags associated with the output should be returned.
   * @param {BooleanDefaultFalse} [args.includeLabels] - Whether the labels associated with the transaction containing the output should be returned.
   * @param {PositiveIntegerDefault10Max10000} [args.limit] - Optional limit on the number of outputs to return.
   * @param {PositiveIntegerOrZero} [args.offset] - Number of outputs to skip before starting to return results.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @returns {Promise<Object>} The promise returns an output listing or an error object.
   */
  listOutputs: (
    args: {
      basket: BasketStringUnder300Characters
      tags?: OutputTagStringUnder300Characters[]
      tagQueryMode?: 'all' | 'any'
      include?: 'locking scripts' | 'entire transactions'
      includeCustomInstructions?: BooleanDefaultFalse
      includeTags?: BooleanDefaultFalse
      includeLabels?: BooleanDefaultFalse
      limit?: PositiveIntegerDefault10Max10000
      offset?: PositiveIntegerOrZero
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    totalOutputs: PositiveIntegerOrZero
    BEEF?: BEEF
    outputs: Array<{
      outpoint: OutpointString
      satoshis: SatoshiValue
      lockingScript?: HexString
      spendable: true
      customInstructions?: string
      tags?: OutputTagStringUnder300Characters[]
      labels?: LabelStringUnder300Characters[]
    }>
  }>

  /**
   * Relinquish an output out of a basket, removing it from tracking without spending it.
   *
   * @param {Object} args - Arguments identifying the output in the basket.
   * @param {BasketStringUnder300Characters} args.basket - The associated basket name where the output should be removed.
   * @param {OutpointString} args.outpoint - The output that should be removed from the basket.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise returns an indication of successful removal or an error object.
   */
  relinquishOutput: (
    args: {
      basket: BasketStringUnder300Characters
      output: OutpointString
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ relinquished: true }>

  /**
   * Retrieves a derived or identity public key based on the requested protocol, key ID, counterparty, and other factors.
   *
   * @param {Object} args - Arguments to specify which public key to retrieve.
   * @param {BooleanDefaultFalse|true} [args.identityKey] - Use true to retrieve the current user's own identity key, overriding any protocol ID, key ID, or counterparty specified.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - The security level and protocol string used for key derivation.
   * @param {KeyIDStringUnder800Characters} args.keyID - The key ID used for key derivation.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - The public key of the counterparty involved in the key derivation process.
   * @param {BooleanDefaultFalse} [args.forSelf] - Whether to return the public key derived from the current user's own identity (as opposed to the counterparty's identity).
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to an object containing the public key, or an error response.
   */
  getPublicKey: (
    args: {
      identityKey?: true
      protocolID?: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID?: KeyIDStringUnder800Characters
      privileged?: BooleanDefaultFalse
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      forSelf?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ publicKey: PubKeyHex }>

  /**
   * Reveals the key linkage between ourselves and a counterparty, to a particular verifier, across all interactions with the counterparty.
   *
   * @param {Object} args - Contains information about counterparty, verifier, and whether the operation is privileged.
   * @param {PubKeyHex} args.counterparty - The public key of the counterparty involved in the linkage.
   * @param {PubKeyHex} args.verifier - The public key of the verifier requesting the linkage information.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to the key linkage, or an error response.
   */
  revealCounterpartyKeyLinkage: (
    args: {
      counterparty: PubKeyHex
      verifier: PubKeyHex
      privilegedReason?: DescriptionString5to50Characters
      privileged?: BooleanDefaultFalse
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    prover: PubKeyHex
    verifier: PubKeyHex
    counterparty: PubKeyHex
    revelationTime: ISOTimestampString
    encryptedLinkage: Byte[]
    encryptedLinkageProof: Byte[]
  }>

  /**
   * Reveals the key linkage between ourselves and a counterparty, to a particular verifier, with respect to a specific interaction.
   *
   * @param {Object} args - The object defining the counterparty, verifier, protocol, and keyID for which linkage should be revealed.
   * @param {PubKeyHex} args.counterparty - The public key of the counterparty involved in the linkage.
   * @param {PubKeyHex} args.verifier - The public key of the verifier requesting the linkage information.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - The security level and protocol string associated with the linkage information to reveal.
   * @param {KeyIDStringUnder800Characters} args.keyID - The key ID associated with the linkage information to reveal.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise returns the requested linkage information, or an error object.
   */
  revealSpecificKeyLinkage: (
    args: {
      counterparty: PubKeyHex
      verifier: PubKeyHex
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      privileged?: BooleanDefaultFalse
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    prover: PubKeyHex
    verifier: PubKeyHex
    counterparty: PubKeyHex
    protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
    keyID: KeyIDStringUnder800Characters
    encryptedLinkage: Byte[]
    encryptedLinkageProof: Byte[]
    proofType: Byte
  }>

  /**
   * Encrypts the provided plaintext data using derived keys, based on the protocol ID, key ID, counterparty, and other factors.
   *
   * @param {Object} args - Information needed for encryption, including the plaintext, protocol ID, and key ID.
   * @param {Byte[]} args.plaintext - Array of bytes constituting the plaintext data to be encrypted.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - The security level and protocol string under which the data should be encrypted.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID under which the encryption will be performed.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public key of the counterparty (if two-party encryption is desired).
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to the encrypted ciphertext bytes or an error if encryption fails.
   */
  encrypt: (
    args: {
      plaintext: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ ciphertext: Byte[] }>

  /**
   * Decrypts the provided ciphertext using derived keys, based on the protocol ID, key ID, counterparty, and other factors.
   *
   * @param {Object} args - Contains the ciphertext, protocol ID, and key ID required to decrypt the data.
   * @param {Byte[]} args.ciphertext - Encrypted bytes, including the initialization vector, for decryption.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - Security level and protocol string that were used during the encryption of the ciphertext.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID used during the encryption of the ciphertext.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public identity key of the counterparty for the encryption operation.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to the decryption result, containing the plaintext data or an error.
   */
  decrypt: (
    args: {
      ciphertext: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ plaintext: Byte[] }>

  /**
   * Creates an HMAC (Hash-based Message Authentication Code) based on the provided data, protocol, key ID, counterparty, and other factors.
   *
   * @param {Object} args - Arguments containing the data, protocol ID, and key ID to generate the HMAC from.
   * @param {Byte[]} args.data - Input data (in bytes) for which the HMAC needs to be created.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - Security level and protocol string to be used during the HMAC operation.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID to be used in the HMAC operation.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public identity key of the counterparty if the operation encompasses a two-party interaction.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to an object containing the generated HMAC bytes, or an error if the creation fails.
   */
  createHmac: (
    args: {
      data: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ hmac: Byte[] }>

  /**
   * Verifies an HMAC (Hash-based Message Authentication Code) based on the provided data, protocol, key ID, counterparty, and other factors.
   *
   * @param {Object} args - Arguments containing the HMAC data, protocol ID, and key ID needed for verification.
   * @param {Byte[]} args.data - The input data whose HMAC is to be verified.
   * @param {Byte[]} args.hmac - Byte array representing the HMAC value to be verified.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - Security level and protocol string to be used during the HMAC operation.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID to be used during the HMAC operation.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public identity key of the counterparty if the operation encompasses a two-party interaction.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to an object confirming whether the HMAC was valid or an error.
   */
  verifyHmac: (
    args: {
      data: Byte[]
      hmac: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ valid: true }>

  /**
   * Creates a digital signature for the provided data or hash using a specific protocol, key, and optionally considering privilege and counterparty.
   *
   * @param {Object} args - Arguments to specify data, protocol, key ID, and privilege for creating the signature.
   * @param {Byte[]} [args.data] - Data to be signed using the derived private key with ECDSA. Required unless directly signing a hash.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - Security level and protocol string to be used during the signing operation.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID to be used during the signing operation.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public identity key of the counterparty if the operation encompasses a two-party interaction.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {Byte[]} [args.hashToDirectlySign] - Sign a pre-hashed value in situations where data can't or shouldn't be revealed, whether due to its size or for privacy.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise will resolve to an object containing the DER-encoded ECDSA signature, or an error on failure.
   */
  createSignature: (
    args: {
      data?: Byte[]
      hashToDirectlySign?: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ signature: Byte[] }>

  /**
   * Verifies a digital signature for the provided data or hash using a specific protocol, key, and optionally considering privilege and counterparty.
   *
   * @param {Object} args - Arguments specifying the data, signature, protocol, and key ID.
   * @param {Byte[]} [args.data] - The data originally signed, which is required for verification unless directly verifying a hash.
   * @param {Byte[]} args.signature - The DER-encoded ECDSA signature to validate.
   * @param {[0 | 1 | 2, ProtocolString5To400Characters]} args.protocolID - Security level and protocol string to be used during signature verification.
   * @param {KeyIDStringUnder800Characters} args.keyID - Key ID to be used during signature verification.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {PubKeyHex | 'self' | 'anyone'} [args.counterparty] - Public identity key of the counterparty if the operation encompasses a two-party interaction.
   * @param {BooleanDefaultFalse} [args.forSelf] - Whether the signature to be verified was created by this user rather than the counterparty.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {Byte[]} [args.hashToDirectlyVerify] - Optional field to verify the signature against a precomputed hash instead of data.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to a boolean object indicating whether the signature was valid or an error message.
   */
  verifySignature: (
    args: {
      data?: Byte[]
      hashToDirectlyVerify?: Byte[]
      signature: Byte[]
      protocolID: [0 | 1 | 2, ProtocolString5To400Characters]
      keyID: KeyIDStringUnder800Characters
      privilegedReason?: DescriptionString5to50Characters
      counterparty?: PubKeyHex | 'self' | 'anyone'
      forSelf?: BooleanDefaultFalse
      privileged?: BooleanDefaultFalse
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ valid: true }>

  /**
   * Acquires an identity certificate, whether by acquiring one from the certifier or by directly receiving it.
   *
   * @param {Object} args - Contains the type of certificate, certifier information, and fields of the certificate to be provided, among other details.
   * @param {Base64String} args.type - Type identifier for the certificate.
   * @param {PubKeyHex} args.certifier - The public identity key of the certifier.
   * @param {'issuance' | 'direct'} args.acquisitionProtocol - Specifies the acquisition process, set to either 'issuance' or 'direct'.
   * * @param {Record<CertificateFieldNameUnder50Characters, string>} args.fields - The fields included within the certificate.
   * @param {Base64String} [args.serialNumber] - Serial number of the certificate to acquire (required when the acquisition protocol is direct).
   * @param {string} [args.revocationOutpoint] - Reference for an outpoint comprising a Bitcoin token that, if ever spent, marks the certificate as invalid (required when the acquisition protocol is direct).
   * @param {HexString} [args.signature] - Signature over the certificate (required when the acquisition protocol is direct).
   * @param {string} [args.certifierUrl] - URL of the certifier where certificate acquisition requests will be sent (required when the acquisition protocol is issuance).
   * @param {PubKeyHex | 'certifier'} [args.keyringRevealer] - The public identity key of the entity revealing the keyring to the user, if different from the certifier (required when the acquisition protocol is direct).
   * @param {Record<CertificateFieldNameUnder50Characters, Base64String>} [args.keyringForSubject] - Keyring revealing all certificate fields to the subject (required when the acquisition protocol is direct).
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object containing the acquired certificate, or an error object.
   */
  acquireCertificate: (
    args: {
      type: Base64String
      certifier: PubKeyHex
      acquisitionProtocol: 'direct' | 'issuance'
      fields: Record<CertificateFieldNameUnder50Characters, string>
      serialNumber?: Base64String
      revocationOutpoint?: OutpointString
      signature?: HexString
      certifierUrl?: string
      keyringRevealer?: PubKeyHex | 'certifier'
      keyringForSubject?: Record<
        CertificateFieldNameUnder50Characters,
        Base64String
      >
      privileged?: BooleanDefaultFalse
      privilegedReason?: DescriptionString5to50Characters
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    type: Base64String
    subject: PubKeyHex
    serialNumber: Base64String
    certifier: PubKeyHex
    revocationOutpoint: OutpointString
    signature: HexString
    fields: Record<CertificateFieldNameUnder50Characters, string>
  }>

  /**
   * Lists identity certificates belonging to the user, filtered by certifier(s) and type(s).
   *
   * @param {Object} args - Arguments used to filter or limit the list of certificates returned by the request.
   * @param {PubKeyHex[]} args.certifiers - An array of public keys for specific certifiers (filters by these certifiers).
   * @param {Base64String[]} args.types - An array of certificate types issued by any of the specified certifiers, which should be returned.
   * @param {PositiveIntegerDefault10Max10000} [args.limit] - Maximum number of certificates to return.
   * @param {PositiveIntegerOrZero} [args.offset] - Number of records to skip before starting to return results.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object containing certificates or an error response.
   */
  listCertificates: (
    args: {
      certifiers: PubKeyHex[]
      types: Base64String[]
      limit?: PositiveIntegerDefault10Max10000
      offset?: PositiveIntegerOrZero
      privileged?: BooleanDefaultFalse
      privilegedReason?: DescriptionString5to50Characters
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    totalCertificates: PositiveIntegerOrZero
    certificates: Array<{
      type: Base64String
      subject: PubKeyHex
      serialNumber: Base64String
      certifier: PubKeyHex
      revocationOutpoint: OutpointString
      signature: HexString
      fields: Record<CertificateFieldNameUnder50Characters, string>
    }>
  }>

  /**
   * Proves select fields of an identity certificate, as specified, when requested by a verifier.
   *
   * @param {Object} args - Arguments including the certificate, fields to reveal, and verifier's public key.
   * @param {Object} args.certificate - The specific identity certificate being proven.
   * @param {Base64String} args.certificate.type - The type of the certificate to be proven.
   * @param {PubKeyHex} args.certificate.subject - Public key belonging to the certificate's subject.
   * @param {Base64String} args.certificate.serialNumber - Unique serial number of the certificate.
   * @param {PubKeyHex} args.certificate.certifier - Public key of the certifier who issued the certificate.
   * @param {OutpointString} args.certificate.revocationOutpoint - The outpoint used to confirm that the certificate has not been revoked.
   * @param {HexString} args.certificate.signature - Certificate signature by the certifier's private key.
   * @param {Record<CertificateFieldNameUnder50Characters, string>} args.certificate.fields - All the encrypted fields present in the certificate.
   * @param {CertificateFieldNameUnder50Characters[]} args.fieldsToReveal - Array of field names that need to be revealed to the verifier.
   * @param {PubKeyHex} args.verifier - Public key of the verifier, to whom the key revelations will be made.
   * @param {BooleanDefaultFalse} [args.privileged] - Whether this is a privileged request.
   * @param {DescriptionString5to50Characters} [args.privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to a keyring for the verifier or an error object.
   */
  proveCertificate: (
    args: {
      certificate: {
        type: Base64String
        subject: PubKeyHex
        serialNumber: Base64String
        certifier: PubKeyHex
        revocationOutpoint: OutpointString
        signature: HexString
        fields: Record<CertificateFieldNameUnder50Characters, string>
      }
      fieldsToReveal: CertificateFieldNameUnder50Characters[]
      verifier: PubKeyHex
      privileged?: BooleanDefaultFalse
      privilegedReason?: DescriptionString5to50Characters
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    keyringForVerifier: Record<
      CertificateFieldNameUnder50Characters,
      Base64String
    >
  }>

  /**
   * Relinquishes an identity certificate, removing it from the wallet regardless of whether the revocation outpoint has become spent.
   *
   * @param {Object} args - Contains the type of certificate, certifier, and serial number for relinquishment.
   * @param {Base64String} args.type - Type identifier for the certificate.
   * @param {PubKeyHex} args.certifier - The public identity key of the certifier.
   * @param {Base64String} args.serialNumber - Serial number of the certificate to relinquish.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an indication of successful relinquishment or an error object.
   */
  relinquishCertificate: (
    args: {
      type: Base64String
      serialNumber: Base64String
      certifier: PubKeyHex
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{ relinquished: true }>

  /**
   * Discovers identity certificates, issued to a given identity key by a trusted entity.
   *
   * @param {Object} args - Arguments for requesting the discovery based on the identity key.
   * @param {PubKeyHex} args.identityKey - Identity key used to filter and discover certificates.
   * @param {PositiveIntegerDefault10Max10000} [args.limit] - Maximum number of certificates to return in the response.
   * @param {PositiveIntegerOrZero} [args.offset] - Skip this number of records before starting to provide results.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to the list of certificates discovered or an error object.
   */
  discoverByIdentityKey: (
    args: {
      identityKey: PubKeyHex
      limit?: PositiveIntegerDefault10Max10000
      offset?: PositiveIntegerOrZero
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    totalCertificates: PositiveIntegerOrZero
    certificates: Array<{
      type: Base64String
      subject: PubKeyHex
      serialNumber: Base64String
      certifier: PubKeyHex
      revocationOutpoint: OutpointString
      signature: HexString
      fields: Record<CertificateFieldNameUnder50Characters, Base64String>
      certifierInfo: {
        name: EntityNameStringMax100Characters
        iconUrl: EntityIconURLStringMax500Characters
        description: DescriptionString5to50Characters
        trust: PositiveIntegerMax10
      }
      publiclyRevealedKeyring: Record<
        CertificateFieldNameUnder50Characters,
        Base64String
      >
      decryptedFields: Record<CertificateFieldNameUnder50Characters, string>
    }>
  }>

  /**
   * Discovers identity certificates belonging to other users, where the documents contain specific attributes, issued by a trusted entity.
   *
   * @param {Object} args - Attributes and optional parameters used to discover certificates.
   * @param {Record<CertificateFieldNameUnder50Characters, string>} args.attributes - The attributes used to discover the certificates.
   * @param {PositiveIntegerDefault10Max10000} [args.limit] - Optional limit on the number of results returned.
   * @param {PositiveIntegerOrZero} [args.offset] - Starts retrieval of results after the specified number of records.
   * @param {BooleanDefaultTrue} [args.seekPermission] — Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to a list of matching certificates or an error object.
   */
  discoverByAttributes: (
    args: {
      attributes: Record<CertificateFieldNameUnder50Characters, string>
      limit?: PositiveIntegerDefault10Max10000
      offset?: PositiveIntegerOrZero
      seekPermission?: BooleanDefaultTrue
    },
    originator?: OriginatorDomainNameString
  ) => Promise<{
    totalCertificates: PositiveIntegerOrZero
    certificates: Array<{
      type: Base64String
      subject: PubKeyHex
      serialNumber: Base64String
      certifier: PubKeyHex
      revocationOutpoint: OutpointString
      signature: HexString
      fields: Record<CertificateFieldNameUnder50Characters, Base64String>
      certifierInfo: {
        name: EntityNameStringMax100Characters
        iconUrl: EntityIconURLStringMax500Characters
        description: DescriptionString5to50Characters
        trust: PositiveIntegerMax10
      }
      publiclyRevealedKeyring: Record<
        CertificateFieldNameUnder50Characters,
        Base64String
      >
      decryptedFields: Record<CertificateFieldNameUnder50Characters, string>
    }>
  }>

  /**
   * Checks the authentication status of the user.
   *
   * @param {Object} args - Empty object, as no parameters are needed.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object indicating whether the user is authenticated or an error response.
   */
  isAuthenticated: (
    args: {},
    originator?: OriginatorDomainNameString
  ) => Promise<{ authenticated: boolean }>

  /**
   * Continuously waits until the user is authenticated, returning the result once confirmed.
   *
   * @param {Object} args - Not used, pass an empty object.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The final result indicating that the user is authenticated or an error object.
   */
  waitForAuthentication: (
    args: {},
    originator?: OriginatorDomainNameString
  ) => Promise<{ authenticated: true }>

  /**
   * Retrieves the current height of the blockchain.
   *
   * @param {Object} args - Empty object as no other parameters are necessary.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to an object indicating the current height or an error on failure.
   */
  getHeight: (
    args: {},
    originator?: OriginatorDomainNameString
  ) => Promise<{ height: PositiveInteger }>

  /**
   * Retrieves the block header of a block at a specified height.
   *
   * @param {Object} args - Contains the height parameter needed to retrieve the block header.
   * @param {PositiveInteger} args.height - Specifies the height at which the block header needs to be retrieved.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an 80-byte block header or an error if it cannot be retrieved.
   */
  getHeaderForHeight: (
    args: { height: PositiveInteger },
    originator?: OriginatorDomainNameString
  ) => Promise<{ header: HexString }>

  /**
   * Retrieves the Bitcoin network the client is using (mainnet or testnet).
   *
   * @param {Object} args - No arguments required, pass an empty object.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} The promise resolves to an object indicating whether the client is using the mainnet or testnet.
   */
  getNetwork: (
    args: {},
    originator?: OriginatorDomainNameString
  ) => Promise<{ network: 'mainnet' | 'testnet' }>

  /**
   * Retrieves the current version string of the wallet.
   *
   * @param {Object} args - Empty argument object.
   * @param {OriginatorDomainNameString} [originator] - Fully-qualified domain name (FQDN) of the application that originated the request.
   * @returns {Promise<Object>} Resolves to an object containing the version string of the wallet, or an error.
   */
  getVersion: (
    args: {},
    originator?: OriginatorDomainNameString
  ) => Promise<{ version: VersionString7To30Characters }>
}

ABI Specification

This section defines the Application Binary Interface (ABI) specification for the Wallet Interface, detailing the binary communication protocol used between applications and wallets over a Wallet Wire. It provides a comprehensive description of how method calls are structured, how data is serialized and deserialized, and how errors and origins are handled within the protocol. This specification ensures that all implementations conform to a standardized binary protocol, enabling interoperability across different platforms and vendors.

Overview

The Wallet ABI defines a binary protocol for communication between an application and the user's digital wallet. Each message transmitted over the Wallet Wire consists of a structured binary frame that includes the method call code, originator information, parameters, and return values. The protocol is designed to be efficient, minimizing the data transmitted while ensuring all necessary information is accurately conveyed.

Message Structure

Every message sent to the wallet follows this general structure:

  • Call Code (1 byte): An unsigned integer representing the method being invoked.
  • Originator Length (1 byte): The length of the originator domain name in bytes.
  • Originator (variable length): The UTF-8 encoded fully qualified domain name (FQDN) of the application originating the request.
  • Parameters (variable length): Method-specific parameters serialized according to the rules defined in this specification.

Responses from the wallet consist of:

  • Error Code (1 byte): A byte indicating success (0) or an error code (1-255).
  • Response Data (variable length): If Error Code is 0, this contains the serialized return values. If an error occurred, it contains the serialized error message and optional stack trace.

Call Codes

Each method in the Wallet Interface is assigned a unique call code. The call codes are defined as follows:

Call Code Method Name
1 createAction
2 signAction
3 abortAction
4 listActions
5 internalizeAction
6 listOutputs
7 relinquishOutput
8 getPublicKey
9 revealCounterpartyKeyLinkage
10 revealSpecificKeyLinkage
11 encrypt
12 decrypt
13 createHmac
14 verifyHmac
15 createSignature
16 verifySignature
17 acquireCertificate
18 listCertificates
19 proveCertificate
20 relinquishCertificate
21 discoverByIdentityKey
22 discoverByAttributes
23 isAuthenticated
24 waitForAuthentication
25 getHeight
26 getHeaderForHeight
27 getNetwork
28 getVersion

Originator Handling

The originator is the fully qualified domain name (FQDN) of the application making the request. It is included in each message to allow the wallet to:

  • Identify the requesting application.
  • Apply appropriate permissions and access controls.
  • Record audit logs for security and compliance.

The originator is serialized as follows:

  • Originator Length (1 byte): The length of the originator string in bytes.
  • Originator (variable length): UTF-8 encoded bytes representing the originator's FQDN.

Error Handling

Errors are communicated using a structured format to provide consistent and detailed information about any issues that occur during method execution.

  • Error Code (1 byte):
    • 0: Indicates success; the method executed without errors.
    • 1-255: Indicates an error occurred; the specific code may correspond to predefined error types or be used for custom error categorization.

If an error occurs (Error Code is non-zero), the following fields are included in the response:

  • Error Message Length (VarInt): The length of the error message in bytes.
  • Error Message (variable length): UTF-8 encoded string describing the error.
  • Stack Trace Length (VarInt): The length of the stack trace in bytes (optional, -1 if absent).
  • Stack Trace (variable length): UTF-8 encoded string containing the stack trace (optional).

Data Types and Serialization

The following data types are used in the binary protocol:

  • Byte: An unsigned 8-bit integer (0 to 255).
  • Int8: A signed 8-bit integer (-128 to 127).
  • UInt8: An unsigned 8-bit integer (0 to 255).
  • VarInt: A variable-length integer used for lengths and counts.
  • UTF-8 String: A string prefixed with its length (as a VarInt), followed by UTF-8 encoded bytes.
  • Byte Array: A sequence of bytes prefixed with its length (as a VarInt).

VarInt Encoding

Variable-length integers (VarInt) are used to efficiently represent integer values. The encoding follows the Bitcoin protocol's VarInt format:

  • For values from 0 to 0xFC (inclusive), a single byte represents the value.
  • For larger values, a marker byte indicates the length:
    • 0xFD: Next two bytes are the value as a little-endian unsigned integer.
    • 0xFE: Next four bytes are the value as a little-endian unsigned integer.
    • 0xFF: Next eight bytes are the value as a little-endian unsigned integer.

Method Calls Specification

Each method call has specific parameter and return value formats. The following sections detail the serialization and deserialization process for each method.

1. createAction

  • Call Code: 1
Parameters
Field Type Description
description UTF-8 String A human-readable description of the action represented by this transaction.
inputBEEF VarInt Length + Byte Array BEEF data associated with inputs (optional). Use VarInt -1 if absent.
inputs VarInt Length + Array An array of input objects (optional). Use VarInt -1 if absent.
outputs VarInt Length + Array An array of output objects (optional). Use VarInt -1 if absent.
lockTime VarInt Transaction lock time (optional). Use -1 to indicate absence.
version VarInt Transaction version (optional). Use -1 to indicate absence.
labels VarInt Length + Array An array of labels (optional). Use VarInt -1 if absent.
options Int8 Flag + Options Struct Options object (optional). If present, 1; else, 0.

Inputs Array:

For each input:

Field Type Description
outpoint Byte Array (32 bytes + VarInt) 32-byte TXID followed by VarInt output index.
unlockingScript VarInt Length + Byte Array Unlocking script (optional). If present, provide length and data. If absent, use VarInt -1 and then provide unlockingScriptLength (VarInt).
unlockingScriptLength VarInt Length of the unlocking script if unlockingScript is absent, VarInt -1 otherwise.
inputDescription UTF-8 String Description of this input.
sequenceNumber VarInt Sequence number (optional). Use -1 to indicate absence.

Outputs Array:

For each output:

Field Type Description
lockingScript VarInt Length + Byte Array Locking script.
satoshis VarInt Amount in satoshis.
outputDescription UTF-8 String Description of this output.
basket UTF-8 String Basket name (optional). If absent, VarInt -1.
customInstructions UTF-8 String Custom instructions (optional). If absent, VarInt -1.
tags VarInt Length + Array Array of tags (optional). If absent, VarInt -1.
  • For each tag:
    • UTF-8 String

Options Struct:

Field Type Description
signAndProcess Int8 1 for true, 0 for false, -1 if not provided.
acceptDelayedBroadcast Int8 1 for true, 0 for false, -1 if not provided.
trustSelf Int8 1 if 'known', -1 if not provided.
knownTxids VarInt Length + Array Array of TXIDs (optional). If absent, VarInt -1.
returnTXIDOnly Int8 1 for true, 0 for false, -1 if not provided.
noSend Int8 1 for true, 0 for false, -1 if not provided.
noSendChange VarInt Length + Array Array of outpoints (optional). If absent, VarInt -1.
sendWith VarInt Length + Array Array of TXIDs (optional). If absent, VarInt -1.
randomizeOutputs Int8 1 for true, 0 for false, -1 if not provided.
  • For each TXID:
    • Byte Array (32 bytes)
  • For each outpoint:
    • Byte Array (32 bytes + VarInt)
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data:

Depending on the outcome, the response may include:

Field Type Description
txid Int8 Flag + Byte Array (32 bytes) If present, 1 followed by 32-byte TXID. Else, 0.
tx Int8 Flag + VarInt Length + Byte Array If present, 1 followed by transaction data (AtomicBEEF). Else, 0.
noSendChange VarInt Length + Array Array of outpoints (optional). If absent, VarInt -1.
sendWithResults VarInt Length + Array Array of structures containing txid and status. If absent, VarInt -1.
signableTransaction Int8 Flag + Struct If present, 1 followed by signable transaction data. Else, 0.
  • For each outpoint:
    • Byte Array (32 bytes + VarInt)
  • For each sendWithResults entry:
    • txid: Byte Array (32 bytes)
    • status: Int8 (1 for 'unproven', 2 for 'sending', 3 for 'failed')

Signable Transaction Struct:

Field Type Description
tx VarInt Length + Byte Array Transaction data in AtomicBEEF format.
reference VarInt Length + Byte Array Reference identifier as a Base64-encoded string.

2. signAction

  • Call Code: 2
Parameters
Field Type Description
spends VarInt Count + Map Map of input indexes to spend information.
reference VarInt Length + Byte Array Reference number as a Base64-encoded string.
options Int8 Flag + Options Struct Options object (optional). If present, 1; else, 0.
  • For each spend:
    • inputIndex: VarInt
    • unlockingScript: VarInt Length + Byte Array
    • sequenceNumber: VarInt (optional). Use -1 to indicate absence.

Options Struct:

Same as in the createAction method, but only applicable fields:

Field Type Description
acceptDelayedBroadcast Int8 1 for true, 0 for false, -1 if not provided.
returnTXIDOnly Int8 1 for true, 0 for false, -1 if not provided.
noSend Int8 1 for true, 0 for false, -1 if not provided.
sendWith VarInt Length + Array Array of TXIDs (optional). If absent, VarInt -1.
  • For each TXID:
    • Byte Array (32 bytes)

Return Values

  • Error Code (1 byte): 0 on success.
  • Response Data:
Field Type Description
txid Int8 Flag + Byte Array (32 bytes) If present, 1 followed by 32-byte TXID. Else, 0.
tx Int8 Flag + VarInt Length + Byte Array If present, 1 followed by transaction data (AtomicBEEF). Else, 0.
noSendChange VarInt Length + Array Array of outpoints (optional). If absent, VarInt -1.
sendWithResults VarInt Length + Array Array of structures containing txid and status. If absent, VarInt -1.

3. abortAction

  • Call Code: 3
Parameters
Field Type Description
reference VarInt Length + Byte Array Reference identifier (Base64-encoded).
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data: None.

4. listActions

  • Call Code: 4
Parameters
Field Type Description
labels VarInt number + Array Array of labels to filter actions.
labelQueryMode Int8 1 for 'any', 2 for 'all', -1 if not provided.
includeLabels Int8 1 for true, 0 for false, -1 if not provided.
includeInputs Int8 Same as above.
includeInputSourceLockingScripts Int8 Same as above.
includeInputUnlockingScripts Int8 Same as above.
includeOutputs Int8 Same as above.
includeOutputLockingScripts Int8 Same as above.
limit VarInt Maximum number of actions to return. Use -1 if not provided.
offset VarInt Number of actions to skip. Use -1 if not provided.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data:
Field Type Description
totalActions VarInt Total number of actions matching the query.
actions Array Serialized array of action objects (details follow).

Action Object:

For each action:

Field Type Description
txid Byte Array (32 bytes) Transaction ID.
satoshis VarInt Amount in satoshis.
status Int8 Status code (see below).
isOutgoing Int8 1 for true, 0 for false.
description UTF-8 String Description of the action.
labels VarInt Length + Array Array of labels (if includeLabels is true, zero-length otherwise).
version VarInt Transaction version.
lockTime VarInt Transaction lock time.
inputs VarInt Length + Array Array of input objects (if includeInputs is true, zero-length otherwise).
outputs VarInt Length + Array Array of output objects (if includeOutputs is true, zero-length otherwise).

Status Codes:

  • 1: 'completed'
  • 2: 'unprocessed'
  • 3: 'sending'
  • 4: 'unproven'
  • 5: 'unsigned'
  • 6: 'nosend'
  • 7: 'nonfinal'

Input Object:

For each input:

Field Type Description
sourceOutpoint Byte Array Outpoint (TXID + output index).
sourceSatoshis VarInt Amount in satoshis of the source output.
sourceLockingScript VarInt Length + Byte Array Locking script of the source output (if included).
unlockingScript VarInt Length + Byte Array Unlocking script (if included).
inputDescription UTF-8 String Description of the input.
sequenceNumber VarInt Sequence number.

Output Object:

For each output:

Field Type Description
outputIndex VarInt Index of the output within the transaction.
satoshis VarInt Amount in satoshis.
lockingScript VarInt Length + Byte Array Locking script (if included).
spendable Int8 1 for true, 0 for false.
outputDescription UTF-8 String Description of the output.
basket UTF-8 String Basket name (if present, else -1).
tags VarInt Length + Array Array of tags (if present, else -1).
customInstructions UTF-8 String Custom instructions (if present, else -1).

5. internalizeAction

  • Call Code: 5
Parameters
Field Type Description
tx VarInt Length + Byte Array BEEF-formatted transaction.
outputs VarInt Length + Array Array of output objects to internalize.
labels VarInt Length + Array Array of labels (optional). If absent, -1.
description UTF-8 String Description of the action.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.

Output Object:

For each output:

Field Type Description
outputIndex VarInt Index of the output within the transaction.
protocol Int8 1 for 'wallet payment', 2 for 'basket insertion'.
paymentRemittance Struct Remittance data for payments (if protocol is 1).
insertionRemittance Struct Remittance data for insertions (if protocol is 2).

Payment Remittance Struct:

Field Type Description
senderIdentityKey Byte Array (33 bytes) Sender's compressed public key.
derivationPrefix VarInt Length + Byte Array Base64-encoded derivation prefix.
derivationSuffix VarInt Length + Byte Array Base64-encoded derivation suffix.

Insertion Remittance Struct:

Field Type Description
basket UTF-8 String Basket name.
customInstructions UTF-8 String Custom instructions (optional). If absent, -1.
tags VarInt Length + Array Array of tags. If absent, length 0.
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data: None.

6. listOutputs

  • Call Code: 6
Parameters
Field Type Description
basket UTF-8 String Basket name.
tags VarInt Length + Array Array of tags to filter by (optional). If absent, length 0.
tagQueryMode Int8 1 for 'all', 2 for 'any', -1 if not provided.
include Int8 1 for 'locking scripts', 2 for 'entire transactions', -1 if not provided.
includeCustomInstructions Int8 1 for true, 0 for false, -1 if not provided.
includeTags Int8 Same as above.
includeLabels Int8 Same as above.
limit VarInt Maximum number of outputs to return. Use -1 if not provided.
offset VarInt Number of outputs to skip. Use -1 if not provided.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data:
Field Type Description
totalOutputs VarInt Total number of outputs matching the query.
outputs Array Serialized array of output objects (details follow).

Output Object:

For each output:

Field Type Description
outpoint Byte Array Outpoint (TXID + output index).
satoshis VarInt Amount in satoshis.
lockingScript VarInt Length + Byte Array Locking script (if included).
tx VarInt Length + Byte Array Transaction data (if included).
spendable Int8 Always 1 (indicates the output is spendable).
customInstructions UTF-8 String Custom instructions (if included).
tags VarInt Length + Array Array of tags (if included).
labels VarInt Length + Array Array of labels (if included).

7. relinquishOutput

  • Call Code: 7
Parameters
Field Type Description
basket UTF-8 String Basket name.
output Byte Array Outpoint (TXID + output index) to relinquish.
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data: None.

8. getPublicKey

  • Call Code: 8
Parameters
Field Type Description
identityKey UInt8 1 to retrieve the identity key, 0 otherwise.
protocolID Struct Protocol ID (if identityKey is 0).
keyID UTF-8 String Key ID (if identityKey is 0).
counterparty Byte Array or UInt8 Counterparty public key, or 11 for 'self', 12 for 'anyone'.
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason Int8 Length + UTF-8 String Reason for privileged access (optional).
forSelf Int8 1 for true, 0 for false, -1 if not provided.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.

Protocol ID Struct:

Field Type Description
securityLevel UInt8 Security level (0, 1, or 2).
protocolString UTF-8 String Protocol identifier string.
Return Values
  • Error Code (1 byte): 0 on success.
  • Response Data:
Field Type Description
publicKey Byte Array (33 bytes) Compressed DER-formatted public key.

9. revealCounterpartyKeyLinkage

  • Call Code: 9
Parameters
Field Type Description
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason UTF-8 String The privileged reason string (Optional).
counterparty Byte Array (33 bytes) The counterparty's compressed secp256k1 public key.
verifier Byte Array (33 bytes) The verifier's compressed secp256k1 public key.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
prover Byte Array (33 bytes) The prover's (user's) compressed public key.
verifier Byte Array (33 bytes) The verifier's compressed public key.
counterparty Byte Array (33 bytes) The counterparty's compressed public key.
revelationTime UTF-8 String ISO 8601 timestamp string indicating the time of revelation.
encryptedLinkage VarInt Length + Byte Array The encrypted linkage data.
encryptedLinkageProof VarInt Length + Byte Array The encrypted linkage proof data.

10. revealSpecificKeyLinkage

  • Call Code: 10
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
verifier Byte Array (33 bytes) The verifier's compressed public key.

Key-Related Parameters:

Field Type Description
protocolID Protocol ID Struct Security level and protocol string (see Protocol ID Struct from call code 8).
keyID UTF-8 String Key ID used for key derivation.
counterparty Byte Array (33 bytes) or UInt8 Counterparty's compressed public key, 11 for 'self', 12 for 'anyone', or 0 if not provided.
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason UTF-8 String The privileged reason string (Optional).
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
prover Byte Array (33 bytes) The prover's compressed public key.
verifier Byte Array (33 bytes) The verifier's compressed public key.
counterparty Byte Array (33 bytes) The counterparty's compressed public key.
protocolID Protocol ID Struct The security level and protocol string used for key derivation, first described in call code 8).
keyID UTF-8 String The key ID used for key derivation.
encryptedLinkage VarInt Length + Byte Array The encrypted linkage data.
encryptedLinkageProof VarInt Length + Byte Array The encrypted linkage proof data.
proofType UInt8 Number The type of proof generated

11. encrypt

  • Call Code: 11
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
plaintext VarInt Length + Byte Array The plaintext data to be encrypted.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
ciphertext Byte Array The encrypted data (AES-256-GCM).

12. decrypt

  • Call Code: 12
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
ciphertext VarInt Length + Byte Array The ciphertext data to be decrypted.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
plaintext Byte Array The decrypted data.

13. createHmac

  • Call Code: 13
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
data VarInt Length + Byte Array The data over which to compute the HMAC.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
hmac Byte Array The computed HMAC value.

14. verifyHmac

  • Call Code: 14
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
hmac Byte Array The HMAC value to verify.
data VarInt Length + Byte Array The data over which the HMAC was computed.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 if the HMAC is valid, non-zero error code otherwise.

  • Response Data: Nothing extra on successful verification.

15. createSignature

  • Call Code: 15
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
dataTypeFlag UInt8 1 if signing data, 2 if signing hashToDirectlySign.
data VarInt Length + Byte Array The data to be signed (if dataTypeFlag is 1).
hashToDirectlySign Byte Array (32 bytes) The hash to directly sign (if dataTypeFlag is 2).
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
signature Byte Array The DER-encoded ECDSA signature.

16. verifySignature

  • Call Code: 16
Parameters
Field Type Description
Key-Related Parameters See Key-Related Parameters as defined in call code 10.
forSelf Int8 1 for verifying own signature, 0 otherwise, -1 if not provided.
signature VarInt Length + Byte Array The DER-encoded ECDSA signature to verify.
dataTypeFlag UInt8 1 if verifying over data, 2 if over hashToDirectlyVerify.
data VarInt Length + Byte Array The data over which the signature was computed (if dataTypeFlag is 1).
hashToDirectlyVerify Byte Array (32 bytes) The hash over which the signature was computed (if dataTypeFlag is 2).
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 if the signature is valid, non-zero error code otherwise.

  • Response Data: Nothing extra if successfully verified.

17. acquireCertificate

  • Call Code: 17
Parameters
Field Type Description
type Byte Array (Base64 encoded) The certificate type identifier.
certifier Byte Array (33 bytes) The certifier's compressed public key.
fields VarInt number + Map Map of fieldName to fieldValue (both UTF-8 strings).
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason Int8 Length + UTF-8 String The reason for the privileged request (Optional).
acquisitionProtocol UInt8 1 for 'direct', 2 for 'issuance'.

Depending on acquisitionProtocol, include additional fields:

If acquisitionProtocol is 'direct' (1):

Field Type Description
serialNumber Byte Array (Base64 encoded) The certificate serial number.
revocationOutpoint Byte Array (32 bytes) + VarInt The revocation outpoint (TXID + output index).
signature VarInt Length + Byte Array The certifier's signature over the certificate data.
keyringRevealer Byte Array (33 bytes) or UInt8 The revealer's compressed public key, or 11 for 'certifier'.
keyringForSubject VarInt number of entries + Map Map of fieldName to keyring values.

If acquisitionProtocol is 'issuance' (2):

Field Type Description
certifierUrl UTF-8 String The certifier's URL for issuance.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
certificate Byte Array The serialized certificate binary data (format described in call code 19).

18. listCertificates

  • Call Code: 18
Parameters
Field Type Description
certifiers VarInt Length + Array Array of certifier public keys (each 33 bytes).
types VarInt Length + Array Array of certificate types (where each entry is a byte array of 32 bytes).
limit VarInt Maximum number of certificates to return, -1 if not provided.
offset VarInt Number of certificates to skip, -1 if not provided.
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason Int8 Length + UTF-8 String The privileged reason string (Optional)
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
totalCertificates VarInt Total number of certificates matching the criteria.
certificates Array Array of certificate binary data (see below).

Each certificate in the certificates array is serialized as:

  • VarInt Length + Byte Array representing the certificate binary data (the certificate binary format as described in proveCertificate method).

19. proveCertificate

  • Call Code: 19
Parameters
Field Type Description
certificate Certificate Struct The certificate data (see Certificate Struct below).
fieldsToReveal VarInt Length + Array Array of fieldName strings (UTF-8) to reveal.
verifier Byte Array (33 bytes) The verifier's compressed public key.
privileged Int8 1 for true, 0 for false, -1 if not provided.
privilegedReason Int8 Length + UTF-8 String The privileged reason (Optional).

Certificate Struct:

Field Type Description
type Byte Array (Base64 encoded) Certificate type identifier.
subject Byte Array (33 bytes) Subject's compressed public key.
serialNumber Byte Array (Base64 encoded) Certificate serial number.
certifier Byte Array (33 bytes) Certifier's compressed public key.
revocationOutpoint Byte Array Revocation outpoint (TXID + output index).
signature VarInt Length + Byte Array Certificate signature.
fields VarInt Length + Map Map of fieldName to encrypted fieldValue.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

Field Type Description
keyringForVerifier VarInt number of fields + Map Map of fieldName to keyring values.

20. relinquishCertificate

  • Call Code: 20
Parameters
Field Type Description
type Byte Array (Base64 encoded) Certificate type identifier.
serialNumber Byte Array (Base64 encoded) Certificate serial number.
certifier Byte Array (33 bytes) Certifier's compressed public key.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data: None.

21. discoverByIdentityKey

  • Call Code: 21
Parameters
Field Type Description
identityKey Byte Array (33 bytes) The identity key to search for certificates.
limit VarInt Maximum number of certificates to return, -1 if not provided.
offset VarInt Number of certificates to skip, -1 if not provided.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values
  • Error Code (1 byte): 0 on success, non-zero error code otherwise.

  • Response Data (on success):

This method returns a list of certificates with additional certifier information and decrypted fields.

Field Type Description
totalCertificates VarInt Total certificates matching the identity key.
certificates Array Array of extended certificate structs (see below).

Each certificate includes:

  • Certificate Binary Data: Serialized certificate as in proveCertificate method.

  • Certifier Info Struct: Contains the following fields:

    Field Type Description
    name UTF-8 String Certifier's name.
    iconUrl UTF-8 String Certifier's icon URL.
    description UTF-8 String Certifier's description.
    trust UInt8 User trust level of this certifier (1-10).
  • Publicly Revealed Keyring: Map of fieldName to keyring values.

  • Decrypted Fields: Map of fieldName to decrypted fieldValue strings (UTF-8).

22. discoverByAttributes

  • Call Code: 22
Parameters
Field Type Description
attributes VarInt Length + Map Map of fieldName to fieldValue strings (UTF-8).
limit VarInt Maximum number of certificates to return, -1 if not provided.
offset VarInt Number of certificates to skip, -1 if not provided.
seekPermission Int8 1 for true (default), 0 for false, -1 if not provided.
Return Values

Same as discoverByIdentityKey method.

23. isAuthenticated

  • Call Code: 23
Parameters

None.

Return Values
  • Error Code (1 byte): 0 on success.

  • Response Data (on success):

Field Type Description
authenticated UInt8 1 if authenticated, 0 otherwise.

24. waitForAuthentication

  • Call Code: 24
Parameters

None.

Return Values
  • Error Code (1 byte): 0 once the user is authenticated.

  • Response Data: None.

25. getHeight

  • Call Code: 25
Parameters

None.

Return Values
  • Error Code (1 byte): 0 on success.

  • Response Data (on success):

Field Type Description
height VarInt Current block height.

26. getHeaderForHeight

  • Call Code: 26
Parameters
Field Type Description
height VarInt The block height for which to retrieve the header.
Return Values
  • Error Code (1 byte): 0 on success.

  • Response Data (on success):

Field Type Description
header Byte Array (80 bytes) The serialized block header (80 bytes).

27. getNetwork

  • Call Code: 27
Parameters

None.

Return Values
  • Error Code (1 byte): 0 on success.

  • Response Data (on success):

Field Type Description
network UInt8 0 for 'mainnet', 1 for 'testnet'.

28. getVersion

  • Call Code: 28
Parameters

None.

Return Values
  • Error Code (1 byte): 0 on success.

  • Response Data (on success):

Field Type Description
version UTF-8 String The wallet's version string (e.g., vendor-1.0.0).

General Notes

  • Absence of Optional Fields: Optional fields are often indicated by a special value (e.g., -1 as a VarInt for length fields). Implementations should handle these values appropriately to determine the presence or absence of data.
  • Encoding of Strings: All strings are UTF-8 encoded and prefixed with their length as a VarInt. The -1 value indicates absence, notably different from 0 which indicates an empty string ("").
  • Error Codes: While only 0 (success) and 1 (generic error) are defined here, implementations may use additional error codes for error classification as needed.

This ABI specification provides a complete and detailed description of the binary protocol used for communication between wallets and applications. By adhering to this specification, developers can ensure compatibility and interoperability across different implementations, enabling a robust and secure ecosystem for wallet interactions within the BSV blockchain ecosystem.

Implementers should carefully follow the serialization and deserialization rules outlined for each method to ensure correct functionality.

Glossary of Terms

AbortAction: A method in the Wallet Interface that allows the cancellation of a transaction that is in progress and has not yet been finalized or sent to the network.

AES-256-GCM: Advanced Encryption Standard (AES) cipher with a 256-bit key size using Galois/Counter Mode (GCM); used for symmetric encryption and decryption operations within the Wallet Interface (as per BRC-2). By convention, 32-byte initialization vectors are prepended to the beginning of the ciphertext.

Application Binary Interface (ABI): A specification detailing the binary communication protocol between applications and wallets over a Wallet Wire, ensuring consistent method call structures, data serialization, and error handling as defined in the Wallet Interface.

Background Evaluation Extended Format (BEEF): A compact data format specified in BRC-62 for representing Bitcoin transactions optimized for Simplified Payment Verification (SPV) and efficient data transmission within the Wallet Interface.

Baskets: Conceptual containers within a wallet used to group and manage specific Unspent Transaction Outputs (UTXOs) as per BRC-46, enabling organized tracking and handling across applications or protocols.

Bitcoin Request for Comment (BRC): An informal proposal or standard within the BSV ecosystem that outlines protocols, methods, or guidelines for functionalities such as transactions, key derivation, network architecture, and wallet interfaces.

BKDS (BSV Key Derivation Scheme): A key derivation scheme defined in BRC-42 that allows wallets to derive multiple unique public-private key pairs from a shared master key using the secp256k1 elliptic curve and a counterparty.

Blockchain Height: The number of blocks in the longest valid chain of the blockchain, representing the latest block's height within the BSV network.

BooleanDefaultFalse: A data type representing an optional boolean parameter that defaults to false if not provided in method arguments.

BooleanDefaultTrue: A data type representing an optional boolean parameter that defaults to true if not provided in method arguments.

BSV Blockchain: A network emphasizing stability, scalability, and adherence to Satoshi Nakamoto's original vision for Bitcoin as a token system, a micropayment system, and a peer-to-peer electronic cash system.

Call Code: An unsigned integer used in the ABI specification to represent the method being invoked over the Wallet Wire.

Certificate: In the context of BRC-52, a digital identity document that encapsulates a subject's identity information, certified by a trusted entity, with support for selective field encryption.

Certificate Field Name: The name of a specific attribute or piece of data within an identity certificate, used for identification and selective revelation.

Certificate Revocation: The process by which an identity certificate is invalidated, often implemented via spending a specific UTXO tied to a revocation outpoint; used to indicate the certificate is no longer valid.

Compressed DER-formatted Public Key: A public key formatted according to the Distinguished Encoding Rules (DER), compressed to represent a point on the secp256k1 elliptic curve using 33 bytes (66 hexadecimal characters). The first byte denotes whether Y is odd, and the remaining 32 bytes comprise the X coordinate on the curve.

Counterparty: An entity (e.g., sender, receiver, verifier) involved in a transaction or key derivation process, identified by their public key; used in BKDS and defined in BRC-43.

createAction: A method that constructs a new transaction based on provided inputs, outputs, and options. It can return a completed transaction, or a signableTransaction if the transaction is not finalized.

Custom Instructions: Data attached to UTXOs that provide contextual information or necessary unlocking context within application logic, represented as a string in the Wallet Interface.

Derivation Prefix/Suffix: Values used during the internalization of payment outputs, as described within BRC-29 to generate different key pairs for each output across the same payment.

DescriptionString5to50Characters: A string data type used for descriptions within the Wallet Interface, constrained to a length between 5 and 50 characters.

Digital Signature: A cryptographic value generated using a private key that verifies the authenticity and integrity of data, as outlined in BRC-3 with ECDSA.

ECDH (Elliptic Curve Diffie-Hellman): A key agreement protocol using elliptic curve cryptography that allows two parties to establish a shared secret over an insecure channel.

ECDSA (Elliptic Curve Digital Signature Algorithm): A cryptographic algorithm used for creating digital signatures using elliptic curve cryptography, specifically over the secp256k1 curve.

Encryption/Decryption: The processes of scrambling data to prevent unauthorized access (encryption) and restoring it to its original form (decryption), as specified in BRC-2 with AES-256-GCM and used within the Wallet Interface.

Entity Icon URL: A URL pointing to an icon representing a trusted entity or certifier in identity certificates, used for display and identification purposes.

Entity Name: The name of a trusted entity or certifier associated with an identity certificate, providing a human-readable identifier for the certifier.

Error Handling: The standardized method by which errors are communicated within the Wallet Interface, using structures containing status, code, description, and optional context.

ErrorCodeString10To40Characters: A data type representing a machine-readable error code string with a length between 10 and 40 characters, used in error responses.

ErrorDescriptionString20To200Characters: A data type representing a human-readable error description string with a length between 20 and 200 characters, providing details about an error.

Fully Qualified Domain Name (FQDN): The complete domain name of a specific computer or host on the internet, used as the OriginatorDomainNameString to identify the originator of a request in the Wallet Interface.

HMAC (Hash-based Message Authentication Code): A specific type of message authentication code involving a cryptographic hash function and a secret key, used for data integrity checks within the Wallet Interface.

Identity Key: The master public key of a wallet derived from the master private key using the secp256k1 elliptic curve; used to identify the wallet owner and derive child keys.

Input (Transaction Input): A reference in a transaction to a previous UTXO that is being spent, containing details such as the outpoint and unlocking script.

Key Derivation: The process of generating child keys from a master key using a specified algorithm like BKDS, providing unique keys for different purposes or interactions.

Key ID: A unique identifier differentiating specific keys under the same Protocol ID, allowing for multiple derived keys with different purposes within the same context as defined in BRC-43.

Key Linkage: Information that reveals the relationship between derived keys, used for transparency, auditability, and verification, particularly as per BRC-69 and protected during transit by BRC-72.

Labels (Transaction Labels): Strings used to categorize transactions within a wallet for organizational and filtering purposes.

Locking Script: A script associated with a transaction output that specifies the conditions under which the output can later be spent (also known as an output script or scriptPubKey, though scriptPubKey should no longer be used).

Lock Time: A parameter in a Bitcoin transaction that specifies the earliest time or block height at which the transaction can be included in the blockchain.

Master Private Key: The primary private key of a wallet from which other keys are derived, forming the root of the wallet's key structure.

Merkle Root: The root hash of a Merkle tree, summarizing all transactions in a block; used in SPV to verify transaction inclusion without downloading the entire block.

Originator Domain Name String: The fully qualified domain name (FQDN) of the application that originated the request, used to authenticate and authorize requests in the Wallet Interface.

Outpoint: A reference to a specific output in a previous transaction, identified by the transaction ID (txid) and output index (vout), used when spending UTXOs.

Output (Transaction Output): A component of a transaction that specifies the recipient of funds or data, including the amount (in satoshis) and a locking script.

Output Tags: Strings assigned to outputs within wallets to categorize or indicate attributes, facilitating searching, sorting, and filtering of UTXOs.

Payment Internalization: The process by which a wallet accepts and manages incoming transactions by parsing, tagging, and organizing outputs, as per BRC-29.

Privileged Mode: A mode of operation within the wallet where sensitive or high-security operations are performed using a secondary, more secure set of keys; requires additional authorization.

Private Digital Signature: A signature intended for a specified receiver, created using a private key derived via BKDS, ensuring that only the intended recipient can verify it using the corresponding public key.

Protocol ID: An identifier used in BRC-43 to define the context or usage of a derived key, combining a security level and a protocol string (e.g., [1, "document signing"]).

PubKeyHex: A hexadecimal string representing a compressed DER-formatted secp256k1 public key, 66 characters long (33 bytes).

Satoshi: The smallest unit of Bitcoin, equal to 0.00000001; used as the unit for transaction amounts within the Wallet Interface.

Script Validation: The process of evaluating and verifying the correctness of scripts (locking and unlocking scripts) within transactions, ensuring they adhere to Bitcoin's scripting rules.

Security Level: In BRC-43, a classification that determines the required permissions and access controls for using a derived key (Level 0: open access, Level 1: requires cross-counterparty authorization, Level 2: requires individual permission for each counterparty).

Shared Secret: In ECDH key exchange, a secret value derived by both parties using their own private key and the other party’s public key, used as the basis for deriving child keys or symmetric encryption keys.

Signable Transaction: A Bitcoin transaction that has been created but is not yet fully signed or finalized. This transaction is in a preparatory state where it requires one or more digital signatures before it can be considered complete and potentially broadcast to the Bitcoin network. Returned from createAction as a partially constructed transaction in BEEF (Background Evaluation Extended Format), which includes a reference number for later signing or aborting.

signAction: A method that signs a previously created transaction (a Signable Action) using the unlocking scripts provided, allowing it to be finalized and potentially broadcast.

Signature: Data that proves the authenticity and integrity of a message or transaction, created using a private key and verifiable with the corresponding public key.

Simplified Payment Verification (SPV): A method for verifying that a transaction is included in the blockchain without downloading the entire chain, by verifying the transaction's inclusion in a block (or its ancestors), checking the scripts that transfer coins, and validating that block via its Merkle root and proof-of-work.

TXID (Transaction ID): A unique identifier for a transaction, calculated as a double SHA-256 hash of the transaction data.

TagQueryMode: A parameter determining how tags are matched when listing outputs within a wallet; can be 'any' (matches if any tag matches) or 'all' (matches only if all queried tags are present).

Transaction: An instruction sent to the Bitcoin network to transfer Bitcoin from one or more inputs to one or more outputs; forms the fundamental operation within the blockchain. Also referred to as Actions when used within applications.

Unlocking Script: A script that satisfies the conditions specified by the locking script of an output, allowing the output to be spent (also known as an input script or scriptSig, though scriptSig should no longer be used).

Unspent Transaction Output (UTXO): An output from a prior transaction that has not yet been spent; represents an amount of Bitcoin controlled by a script that can be used as an input in a new transaction.

Vendor Neutrality: A design principle ensuring that an interface or protocol can be implemented by any vendor without proprietary constraints, promoting interoperability and standardization.

VersionString7To30Characters: A data type representing a version string of the wallet, constrained to be between 7 and 30 characters, in the format [vendor]-[major].[minor].[patch].

Wallet Interface: The standardized set of methods and protocols defined in BRC-100 for communication between wallets and applications in the BSV ecosystem, designed to be unified, vendor-neutral, and open.

Wallet Wire: The communication channel or protocol over which applications and wallets exchange messages using the defined ABI specification.

Conclusion

This interface defines a comprehensive, standardized, and secure Wallet-to-Application interaction model within the BSV ecosystem. By enforcing type constraints, standardizing operations, and maintaining vendor neutrality, it enables a broad and flexible ecosystem where apps and wallets can interoperate efficiently, securely, and reliably across a multitude of environments. Its open and unchanging specification through this document enforces stability while promoting widespread adoption, driving forward the implementation of BSV and allowing applications to build on top.

At long last.