LogoLogo
  • README
  • Contribute
    • Discuss on Github
  • Example
    • Banana-Powered Bitcoin Wallet Control Protocol
  • Apps
    • The deployment-info.json Specification
  • Wallet
    • Transaction Creation
    • Data Encryption and Decryption
    • Digital Signature Creation and Verification
    • Input Redemption
    • HTTP Wallet Communications Substrate
    • XDM Wallet Communications Substrate
    • Window Wallet Communication Substrate
    • Wallet Transaction Output Tracking (Output Baskets)
    • Submitting Received Payments to a Wallet
    • Certificate Creation and Revelation
    • Unified Abstract Wallet-to-Application Messaging Layer
    • Transaction Labels and List Actions
    • Output Basket Removal and Certificate Deletion
    • Group Permissions for App Access
    • Extensible Proof-Type Format for Specific Key Linkage Claims
    • P Protocols: Allowing future wallet protocol permission schemes
    • P Baskets: Allowing Future Wallet Basket and Digital Asset Permission Schemes
    • Unified, Vendor-Neutral, Unchanging, and Open BSV Blockchain Standard Wallet-to-Application Interface
  • Transactions
    • Everett-style Transaction Envelopes
    • Simplified Payment Verification
    • Merkle proof standardised format
    • TSC Proof Format with Heights
    • Raw Transaction Format
    • TXO Transaction Object Format
    • Transaction Extended Format (EF)
    • Merkle Path JSON format
    • Compound Merkle Path Format
    • Background Evaluation Extended Format (BEEF) Transactions
    • Simplified Payment Verification
    • Merkle Path Binary Format
    • BSV Unified Merkle Path (BUMP) Format
    • Graph Aware Sync Protocol
    • Scalable Transaction Processing in the BSV Network
    • Atomic BEEF Transactions
    • BEEF V2 Txid Only Extension
  • Scripts
    • Bitcoin Script Binary, Hex and ASM Formats
    • Bitcoin Script Assembly Language
    • Pay to Public Key Hash
    • Pay to R Puzzle Hash
    • Pay to False Return
    • Pay to True Return
    • Push TX
    • Bare Multi-Signature
    • Pay to Push Drop
  • Tokens
    • There is no BRC-20
    • Definition of UTXOs as Bitcoin Tokens
    • Token Exchange Protocol for UTXO-based Overlay Networks
    • Mandala Token Protocol
  • Overlays
    • Overlay Network Data Synchronization
    • Confederacy Host Interconnect Protocol (CHIP)
    • Overlay Network Lookup Services
    • Confederacy Lookup Availability Protocol (CLAP)
    • Universal Hash Resolution Protocol
    • Overlay Network Transaction History Tracking
    • Private Overlays with P2PKH Transactions
    • Standardized Naming Conventions for BRC-22 Topic Managers and BRC-24 Lookup Services
    • Overlay Services Synchronization Architecture
    • Diverse Facilitators and URL Protocols for SHIP and SLAP Overlay Advertisements
  • Payments
    • Direct Payment Protocol (DPP)
    • Paymail Payment Destinations
    • Simple Authenticated BSV P2PKH Payment Protocol
    • PacketPay HTTP Payment Mechanism
    • Hybrid Payment Mode for DPP
    • HTTPS Transport Mechanism for DPP
    • Paymail BEEF Transaction
    • HTTP Service Monetization Framework
  • Peer-to-Peer
    • Authrite Mutual Authentication
    • PeerServ Message Relay Interface
    • PeerServ Host Interconnect Protocol
    • Identity Certificates
    • Genealogical Identity Protocol
    • Publishing Trust Anchor Details at an Internet Domain
    • Message Signature Creation and Verification
    • Serialization Format for Portable Encrypted Messages
    • Defining a Scalable IPv6 Multicast Protocol for Blockchain Transaction Broadcast and Update Delivery
    • Proven Identity Key Exchange (PIKE)
    • Peer-to-Peer Mutual Authentication and Certificate Exchange Protocol
    • HTTP Transport for BRC-103 Mutual Authentication
  • Key Derivation
    • BIP32 Key Derivation Scheme
    • BSV Key Derivation Scheme (BKDS)
    • Security Levels, Protocol IDs, Key IDs and Counterparties
    • Admin-reserved and Prohibited Key Derivation Protocols
    • Revealing Key Linkages
    • Protecting BRC-69 Key Linkage Information in Transit
    • Mnemonic For Master Private Key
    • Linked Key Derivation Scheme
    • Bidirectionally Authenticated Derivation of Privacy Restricted Type 42 Keys
    • Limitations of BRC-69 Key Linkage Revelation
    • Verifiable Revelation of Shared Secrets Using Schnorr Protocol
  • Outpoints
    • Format for Bitcoin Outpoints
    • Spending Instructions Extension for UTXO Storage Format
  • Opinions
    • Users should never see an address
    • List of user experiences
    • Legitimate Uses for mAPI
    • Security and Scalability Benefits of UTXO-based Overlay Networks
    • Improving on MLD for BSV Multicast Services
    • Web 3.0 Standard (at a high level)
    • Thoughts on the Mandala Network
    • Outputs, Overlays, and Scripts in the Mandala Network
  • State Machines
    • Simplifying State Machine Event Chains in Bitcoin
Powered by GitBook
On this page
  • Abstract
  • Motivation
  • Primary Objectives
  • Foundational Requirements
  • Section Overview
  • 1. Key Derivation using BKDS with BRC-42
  • 2. Security Levels and Protocol IDs with BRC-43
  • 3. Reserved Internal Protocols with BRC-44
  • 4. Tokenization of UTXOs with BRC-45
  • 5. Tracking and Managing Outputs with BRC-46
  • 6. Transaction Verification with BRC-67 and BRC-62
  • 7. Data Security with BRC-2 for Encryption and Decryption
  • 8. Authorized Digital Signatures with BRC-3
  • 9. Identity Certificates and Selective Revelation with BRC-52
  • 10. Payment Internalization with BRC-29
  • 11. Auditability and Key Linkage Revelations with BRC-69 and BRC-72
  • Interface Structure
  • Transaction Operations:
  • Public Key Management:
  • Cryptography Operations:
  • Identity and Certificate Management:
  • Blockchain and Network Data:
  • Authentication:
  • Data Types and Constraints
  • Boolean Types:
  • Integer Types:
  • String Types:
  • Error Handling and Validation
  • Errors are raised using a uniform structure containing:
  • Recommended Validation Steps:
  • Parameter Errors:
  • Usage and Best Practices
  • Restrictions on Protocol and Basket Namespaces
  • Rules for Protocol Names
  • Rules for Basket Names
  • The Wallet Interface
  • ABI Specification
  • Overview
  • Message Structure
  • Call Codes
  • Originator Handling
  • Error Handling
  • Data Types and Serialization
  • Method Calls Specification
  • General Notes
  • Glossary of Terms

Was this helpful?

Edit on GitHub
Export as PDF
  1. Wallet

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

  • Ty Everett (ty@projectbabbage.com)

  • Tone Engel (tone@projectbabbage.com)

  • Brayden Langley (brayden@projectbabbage.com)

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 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

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

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

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

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 to enhance scalability, ensure decentralization, and promote trustlessness by enabling transparent and verifiable transactions without reliance on intermediaries.

Simplified Payment Verification (SPV):

5. Tracking and Managing Outputs with BRC-46

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:

  • 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

BEEF Data Structure:

  • Wallets should utilize BEEF when constructing, communicating, and validating transactions. BEEF supports streaming validation, enabling the wallet to initiate transaction verification as soon as it starts receiving the data.

Verification Steps:

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

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

Digital Signature Process:

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:

9. Identity Certificates and Selective Revelation with BRC-52

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

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.

Flexible Payment Handling:

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

Key Linkage Revelations:

Protection of Linkage Information:

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: The createAction method creates a new Action, which is effectively a Bitcoin transaction augmented with descriptive metadata and optional categorization (labels). This method can either fully construct and sign a transaction or return a "signableTransaction" reference if some inputs must be signed or processed later. The method always requires at least one input or one output to produce a valid transaction; otherwise, it must return an error. The minimum requirements is that at least one input or one output must be specified. If only description is provided and no inputs and no outputs are given, the wallet must return an error, since a transaction cannot be constructed. If inputs are provided, the wallet requires inputBEEF to supply context and validation data for these inputs. If both inputBEEF and a fully prepared set of inputs are provided, inputBEEF should provide SPV and contextual information about these inputs. The two are complementary: inputs define the UTXOs being consumed, and inputBEEF provides the transaction inclusion proofs or data needed for validation. Both must not conflict. If a conflict is detected, the wallet should return an error. Every input requires an inputDescription. This string documents why a particular UTXO was chosen or what it represents. This field is required to ensure proper user-level record-keeping and transparency. If basket is not provided for an output, that output is considered untracked by the wallet. It will not appear in listOutputs, and the wallet does not maintain any metadata about it. Baskets are used for grouping UTXOs for later retrieval, filtering, and permissioned operations.

  • 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. Labels can be attached to transactions to facilitate discovery via listActions and tags can be attached to outputs to similarly facilitate discovery via listOutputs. They are purely organizational tools and cannot be used as triggers or conditional hooks for other wallet operations. They serve only for later searching and categorizing actions.

  • Relinquishment: relinquishOutput releases an output from a basket tracked by the wallet, even if it has yet to be spent.

  • Pre-Built Transactions: If you already have a fully constructed transaction in BEEF format and simply need to internalize it into the wallet, internalizeAction is the appropriate method. createAction is meant for constructing new transactions within the wallet, not for just adding an existing transaction.

  • Tags vs. Labels: Transaction-level labels categorize entire transactions (Actions) and are used with listActions. Output-level tags categorize individual outputs and are used with listOutputs. Both are organizational metadata fields and do not trigger special wallet logic or external processes. They exist solely for searching, filtering, and organizing data.

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.

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.

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.

Recommended Validation Steps:

Wallets must apply all specified rules and logical validation procedures to all methods within the specification. For example, in the case of createAction, wallets should:

  • Verify that the required fields (description plus at least one input or one output) are present.

  • Check that if inputs are provided, the inputDescription field is also provided for each input.

  • Validate that if inputBEEF is provided, it corresponds logically to the inputs.

  • Ensure that labels, tags, and basket names comply with the defined format and size constraints.

  • If any constraints are not met, or if conflicting parameters are detected (e.g., invalid noSendChange usage), the wallet should return a structured error as previously defined.

Parameter Errors:

If parameters are missing, malformed, or conflict with each other, the wallet should return an error with an appropriate error code and a human-readable description. For instance:

  • Missing required fields: Return an error code like ERR_MISSING_PARAMETER and a description stating which parameter is missing.

  • Invalid numeric ranges or string lengths: Return ERR_INVALID_PARAMETER_VALUE.

  • Conflicts between inputs and inputBEEF: Return ERR_CONFLICTING_PARAMETERS.

These are examples; wallets and implementations are free to use their own naming conventions for error codes as long as they provide a clear description field.

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

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).

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).

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.
 * @remarks
 * Default values are not enforced at the type level. Ensure that implementations explicitly assign the default value.

 */
export type BooleanDefaultFalse = boolean

/**
 * @typedef {boolean} BooleanDefaultTrue
 * Represents an optional boolean parameter, which defaults to `true` if not provided.
 * @remarks
 * Default values are not enforced at the type level. Ensure that implementations explicitly assign the default value.
 */
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
 * @remarks
 * TypeScript cannot enforce numeric ranges. Validate at runtime if the value is within the specified range.
 */
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
 * @remarks
 * TypeScript cannot enforce numeric ranges. Validate at runtime if the value is within the specified range.
 */
export type PositiveInteger = number

/**
 * @typedef {number} PositiveIntegerMax10
 * A positive integer that excludes zero, and has an upper bound of 10.
 * @minimum 1
 * @maximum 10
 * @remarks
 * TypeScript cannot enforce numeric ranges. Validate at runtime if the value is within the specified range.
 */
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
 * @remarks
 * Default values are not enforced at the type level. Validate at runtime if the value is within the specified range and assign the default if omitted.
 */
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
 * @remarks
 * TypeScript cannot enforce numeric ranges. Validate at runtime if the value is within the specified range.
 */
export type SatoshiValue = number

/**
 * @typedef {string} ISOTimestampString
 * Represents an ISO timestamp string.
 * @remarks
 * Ensure runtime validation to confirm the string adheres to the ISO 8601 standard.
 */
export type ISOTimestampString = string

/**
 * @typedef {string} HexString
 * A string containing only hexadecimal characters (0-9, a-f).
 * @remarks
 * TypeScript does not enforce format or case. Validate at runtime to ensure the string is properly formatted.
 */
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
 * @remarks
 * TypeScript cannot enforce string length. Validate at runtime for length and format compliance.
 */
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.
 * @remarks
 * Validate at runtime to ensure the correct format: `<TXID>.<index>`.
 */
export type OutpointString = string

/**
 * @typedef {HexString} PubKeyHex
 * Represents a compressed DER secp256k1 public key, exactly 66 hex characters (33 bytes) in length.
 * @length 66
 * @remarks
 * TypeScript does not enforce length or format. Validate at runtime to ensure the string is 66 characters long and valid hexadecimal.
 */
export type PubKeyHex = HexString

/**
 * @typedef {string} Base64String
 * A standard base64 encoded string.
 * @remarks
 * Validate at runtime to ensure the string adheres to the Base64 format.
 */
export type Base64String = string

/**
 * @typedef {string} OriginatorDomainNameString
 * Represents the fully qualified domain name (FQDN) of the application that originates the request.
 * @remarks
 * Validate at runtime to ensure the string conforms to FQDN formatting rules.
 */
export type OriginatorDomainNameString = string

/**
 * @typedef {string & { minLength: 5, maxLength: 50 }} DescriptionString5to50Characters
 * A string used for descriptions, with a length between 5 and 50 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type DescriptionString5to50Characters = string

/**
 * @typedef {string & { maxLength: 300 }} BasketStringUnder300Characters
 * A string for naming baskets, with a maximum length of 300 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type BasketStringUnder300Characters = string

/**
 * @typedef {string & { maxLength: 300 }} OutputTagStringUnder300Characters
 * A string for tagging outputs, with a maximum length of 300 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type OutputTagStringUnder300Characters = string

/**
 * @typedef {string & { maxLength: 300 }} LabelStringUnder300Characters
 * A string for labeling transactions, with a maximum length of 300 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
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.
 * @remarks
 * Validate at runtime to ensure each element is within the specified range.
 */
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.
 * @remarks
 * Validate at runtime to ensure each element is within the specified range.
 */
export type AtomicBEEF = Byte[]

/**
 * @typedef {string & { minLength: 5, maxLength: 400 }} ProtocolString5To400Characters
 * A protocol identifier with a length between 5 and 400 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type ProtocolString5To400Characters = string

/**
 * @typedef {string & { maxLength: 800 }} KeyIDStringUnder800Characters
 * Represents a key identifier string, with a maximum length of 800 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type KeyIDStringUnder800Characters = string

/**
 * @typedef {string & { maxLength: 50 }} CertificateFieldNameUnder50Characters
 * Represents a certificate field name with a maximum length of 50 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type CertificateFieldNameUnder50Characters = string

/**
 * @typedef {string & { maxLength: 100 }} EntityNameStringMax100Characters
 * Represents a trusted entity name with a maximum length of 100 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
export type EntityNameStringMax100Characters = string

/**
 * @typedef {string & { maxLength: 500 }} EntityIconURLStringMax500Characters
 * Represents a trusted entity icon URL with a maximum length of 500 characters.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
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]
 * @remarks
 * Validate at runtime for format and length compliance.
 */
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.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
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.
 * @remarks
 * TypeScript cannot enforce length constraints. Validate at runtime for length compliance.
 */
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, ensuring consistent and detailed information about any issues that occur during method execution. This format enables precise error reporting, seamless debugging, and interoperability across implementations:

  • 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