UNPKG

@naladelponce/hf-web-client

Version:

Un cliente TypeScript moderno y robusto para interactuar con Hyperledger Fabric desde entornos web y Node.js.

466 lines (453 loc) 14.6 kB
import { Message } from '@bufbuild/protobuf'; type Success<T> = { success: true; data: T; error: null; }; type Failure<E = Error> = { success: false; data: null; error: E; }; type Result<T, E = Error> = Success<T> | Failure<E>; /** * Represents an unlocked application identity. * This is the "magic wand" the application uses to interact with Fabric. * It contains the user's certificate and the CAPABILITY to sign data. */ interface AppIdentity { readonly cert: string; readonly sign: (dataToSign: Uint8Array) => Promise<Uint8Array>; } interface PasswordCreateOptions { certPem: string; keyPem: string; password?: string; } /** * The result of a successful identity creation. * It extends the AppIdentity with the recovery phrase and shares, which the * user MUST save securely. */ interface PasswordCreateResult extends AppIdentity { readonly phrase: string; readonly recoveryShares: string[]; } interface PasswordUnlockOptions { password: string; } /** * ChaincodeEvent is used for events and registrations that are specific to chaincode * string type - "chaincode" * * @generated from message protos.ChaincodeEvent */ type ChaincodeEvent = Message<"protos.ChaincodeEvent"> & { /** * @generated from field: string chaincode_id = 1; */ chaincodeId: string; /** * @generated from field: string tx_id = 2; */ txId: string; /** * @generated from field: string event_name = 3; */ eventName: string; /** * @generated from field: bytes payload = 4; */ payload: Uint8Array; }; /** * @generated from enum common.HeaderType */ declare enum HeaderType { /** * Used for messages which are signed but opaque * * @generated from enum value: MESSAGE = 0; */ MESSAGE = 0, /** * Used for messages which express the channel config * * @generated from enum value: CONFIG = 1; */ CONFIG = 1, /** * Used for transactions which update the channel config * * @generated from enum value: CONFIG_UPDATE = 2; */ CONFIG_UPDATE = 2, /** * Used by the SDK to submit endorser based transactions * * @generated from enum value: ENDORSER_TRANSACTION = 3; */ ENDORSER_TRANSACTION = 3, /** * Was used internally by the orderer for management, no longer used since system channel was removed * * @generated from enum value: ORDERER_TRANSACTION = 4 [deprecated = true]; * @deprecated */ ORDERER_TRANSACTION = 4, /** * Used as the type for Envelope messages submitted to instruct the Deliver API to seek * * @generated from enum value: DELIVER_SEEK_INFO = 5; */ DELIVER_SEEK_INFO = 5, /** * Used for packaging chaincode artifacts for install * * @generated from enum value: CHAINCODE_PACKAGE = 6; */ CHAINCODE_PACKAGE = 6 } /** * @generated from enum protos.TxValidationCode */ declare enum TxValidationCode { /** * @generated from enum value: VALID = 0; */ VALID = 0, /** * @generated from enum value: NIL_ENVELOPE = 1; */ NIL_ENVELOPE = 1, /** * @generated from enum value: BAD_PAYLOAD = 2; */ BAD_PAYLOAD = 2, /** * @generated from enum value: BAD_COMMON_HEADER = 3; */ BAD_COMMON_HEADER = 3, /** * @generated from enum value: BAD_CREATOR_SIGNATURE = 4; */ BAD_CREATOR_SIGNATURE = 4, /** * @generated from enum value: INVALID_ENDORSER_TRANSACTION = 5; */ INVALID_ENDORSER_TRANSACTION = 5, /** * @generated from enum value: INVALID_CONFIG_TRANSACTION = 6; */ INVALID_CONFIG_TRANSACTION = 6, /** * @generated from enum value: UNSUPPORTED_TX_PAYLOAD = 7; */ UNSUPPORTED_TX_PAYLOAD = 7, /** * @generated from enum value: BAD_PROPOSAL_TXID = 8; */ BAD_PROPOSAL_TXID = 8, /** * @generated from enum value: DUPLICATE_TXID = 9; */ DUPLICATE_TXID = 9, /** * @generated from enum value: ENDORSEMENT_POLICY_FAILURE = 10; */ ENDORSEMENT_POLICY_FAILURE = 10, /** * @generated from enum value: MVCC_READ_CONFLICT = 11; */ MVCC_READ_CONFLICT = 11, /** * @generated from enum value: PHANTOM_READ_CONFLICT = 12; */ PHANTOM_READ_CONFLICT = 12, /** * @generated from enum value: UNKNOWN_TX_TYPE = 13; */ UNKNOWN_TX_TYPE = 13, /** * @generated from enum value: TARGET_CHAIN_NOT_FOUND = 14; */ TARGET_CHAIN_NOT_FOUND = 14, /** * @generated from enum value: MARSHAL_TX_ERROR = 15; */ MARSHAL_TX_ERROR = 15, /** * @generated from enum value: NIL_TXACTION = 16; */ NIL_TXACTION = 16, /** * @generated from enum value: EXPIRED_CHAINCODE = 17; */ EXPIRED_CHAINCODE = 17, /** * @generated from enum value: CHAINCODE_VERSION_CONFLICT = 18; */ CHAINCODE_VERSION_CONFLICT = 18, /** * @generated from enum value: BAD_HEADER_EXTENSION = 19; */ BAD_HEADER_EXTENSION = 19, /** * @generated from enum value: BAD_CHANNEL_HEADER = 20; */ BAD_CHANNEL_HEADER = 20, /** * @generated from enum value: BAD_RESPONSE_PAYLOAD = 21; */ BAD_RESPONSE_PAYLOAD = 21, /** * @generated from enum value: BAD_RWSET = 22; */ BAD_RWSET = 22, /** * @generated from enum value: ILLEGAL_WRITESET = 23; */ ILLEGAL_WRITESET = 23, /** * @generated from enum value: INVALID_WRITESET = 24; */ INVALID_WRITESET = 24, /** * @generated from enum value: INVALID_CHAINCODE = 25; */ INVALID_CHAINCODE = 25, /** * @generated from enum value: NOT_VALIDATED = 254; */ NOT_VALIDATED = 254, /** * @generated from enum value: INVALID_OTHER_REASON = 255; */ INVALID_OTHER_REASON = 255 } /** * ChaincodeEventsResponse returns chaincode events emitted from a specific block. * * @generated from message gateway.ChaincodeEventsResponse */ type ChaincodeEventsResponse = Message<"gateway.ChaincodeEventsResponse"> & { /** * Chaincode events emitted by the requested chaincode. The events are presented in the same order that the * transactions that emitted them appear within the block. * * @generated from field: repeated protos.ChaincodeEvent events = 1; */ events: ChaincodeEvent[]; /** * Block number in which the chaincode events were emitted. * * @generated from field: uint64 block_number = 2; */ blockNumber: bigint; }; /** * FilteredBlock is a minimal set of information about a block * * @generated from message protos.FilteredBlock */ type FilteredBlock = Message<"protos.FilteredBlock"> & { /** * @generated from field: string channel_id = 1; */ channelId: string; /** * The position in the blockchain * * @generated from field: uint64 number = 2; */ number: bigint; /** * @generated from field: repeated protos.FilteredTransaction filtered_transactions = 4; */ filteredTransactions: FilteredTransaction[]; }; /** * FilteredTransaction is a minimal set of information about a transaction * within a block * * @generated from message protos.FilteredTransaction */ type FilteredTransaction = Message<"protos.FilteredTransaction"> & { /** * @generated from field: string txid = 1; */ txid: string; /** * @generated from field: common.HeaderType type = 2; */ type: HeaderType; /** * @generated from field: protos.TxValidationCode tx_validation_code = 3; */ txValidationCode: TxValidationCode; /** * @generated from oneof protos.FilteredTransaction.Data */ Data: { /** * @generated from field: protos.FilteredTransactionActions transaction_actions = 4; */ value: FilteredTransactionActions; case: "transactionActions"; } | { case: undefined; value?: undefined; }; }; /** * FilteredTransactionActions is a wrapper for array of TransactionAction * message from regular block * * @generated from message protos.FilteredTransactionActions */ type FilteredTransactionActions = Message<"protos.FilteredTransactionActions"> & { /** * @generated from field: repeated protos.FilteredChaincodeAction chaincode_actions = 1; */ chaincodeActions: FilteredChaincodeAction[]; }; /** * FilteredChaincodeAction is a minimal set of information about an action * within a transaction * * @generated from message protos.FilteredChaincodeAction */ type FilteredChaincodeAction = Message<"protos.FilteredChaincodeAction"> & { /** * @generated from field: protos.ChaincodeEvent chaincode_event = 1; */ chaincodeEvent?: ChaincodeEvent; }; interface FabricClientConfig { gatewayUrl: string; } interface BaseChaincodeParams { mspId: string; channelName: string; chaincodeName: string; } interface ProposalParams extends BaseChaincodeParams { functionName: string; args?: (string | Uint8Array)[]; } interface SubmitParams { channelName: string; txId: string; preparedTransaction: Uint8Array; } interface EvaluatedTransaction { readonly txId: string; readonly status: number; readonly message: string; readonly parsedData: any; } interface PreparedTransaction { readonly txId: string; readonly transactionEnvelope: Uint8Array; } interface SubmittedTransaction { readonly txId: string; readonly status: string; } interface EventServiceConfig { gatewayUrl: string; wsUrl: string; } interface BlockEventParams { mspId: string; channelName: string; targetPeer: string; targetHostname: string; startBlock?: number; stopBlock?: number; } interface ChaincodeEventParams { mspId: string; channelName: string; chaincodeName: string; } declare class IdentityService { private worker; constructor(); private request; /** * Constructs the active AppIdentity object. * @param cert The user's certificate PEM. * @returns An AppIdentity object with a live `sign` method. */ private buildActiveIdentity; doesHardwareIdentityExist(): Promise<Result<boolean>>; doesPasswordIdentityExist(): Promise<Result<boolean>>; createPasswordIdentity(options: PasswordCreateOptions): Promise<Result<PasswordCreateResult>>; createHardwareIdentity(options: { certPem: string; keyPem: string; }): Promise<Result<PasswordCreateResult>>; unlockIdentity(options: PasswordUnlockOptions, mode: "password-base" | "hardware-base"): Promise<Result<AppIdentity>>; verifyBiometrics(): Promise<Result<boolean>>; deleteIdentity(mode: "password-base" | "hardware-base"): Promise<Result<void>>; } declare class FabricClient { private readonly gatewayClient; constructor(config: FabricClientConfig); /** * Evalúa una transacción de solo lectura. La propuesta se envía a un peer, * pero no se envía al servicio de ordenamiento. * * @param params Los detalles de la propuesta de transacción. * @param identity La identidad del cliente para firmar la propuesta. * @returns Un Result con los datos de la transacción evaluada o un error. */ evaluateTransaction(params: ProposalParams, identity: AppIdentity): Promise<Result<EvaluatedTransaction>>; /** * Prepara (endorsa) una transacción para su posterior envío al orderer. * La propuesta se envía a los peers para su endoso según la política. * * @param params Los detalles de la propuesta de transacción. * @param identity La identidad del cliente para firmar la propuesta. * @returns Un Result con la transacción preparada (el envelope de la transacción) o un error. */ prepareTransaction(params: ProposalParams, identity: AppIdentity): Promise<Result<PreparedTransaction>>; /** * Envía una transacción previamente preparada y firmada al orderer para su commit en el ledger. * * @param params Los detalles de la transacción a enviar, incluyendo el envelope de `prepareTransaction`. * @param identity La identidad del cliente para firmar el envelope final. * @returns Un Result confirmando el envío exitoso o un error. */ submitSignedTransaction(params: SubmitParams, identity: AppIdentity): Promise<Result<SubmittedTransaction>>; } declare class EventService { private readonly gatewayClient; private readonly wsBaseUrl; constructor(config: EventServiceConfig); /** * Establece una conexión para escuchar eventos emitidos por un chaincode específico. * Devuelve un Generador Asíncrono que produce respuestas a medida que llegan. * * @param params Los detalles del canal y chaincode a escuchar. * @param identity La identidad del cliente para firmar la petición de eventos. * @param signal Un AbortSignal para cancelar la suscripción y cerrar el stream. * @yields {ChaincodeEventsResponse} Un objeto de respuesta por cada bloque que contenga eventos. */ listenToChaincodeEvents(params: ChaincodeEventParams, identity: AppIdentity, signal: AbortSignal): AsyncGenerator<ChaincodeEventsResponse>; /** * Establece una conexión WebSocket para escuchar eventos de bloque filtrados de un canal. * Devuelve un Generador Asíncrono que produce bloques a medida que son commiteados. * * @param params Los detalles del canal y peer a escuchar. * @param identity La identidad del cliente para firmar la petición de deliver. * @param signal Un AbortSignal para cancelar la suscripción y cerrar el WebSocket. * @yields {FilteredBlock} Un bloque filtrado cada vez que se commitea uno nuevo. */ listenToBlockEvents(params: BlockEventParams, identity: AppIdentity, signal: AbortSignal): AsyncGenerator<FilteredBlock>; private createSignedChaincodeEventsRequest; private waitForSocketOpen; private waitForSocketMessage; } export { type AppIdentity, type BlockEventParams, type ChaincodeEventParams, type ChaincodeEventsResponse, type EvaluatedTransaction, EventService, type EventServiceConfig, FabricClient, type FabricClientConfig, type Failure, type FilteredBlock, IdentityService, type PasswordCreateOptions, type PasswordCreateResult, type PasswordUnlockOptions, type PreparedTransaction, type ProposalParams, type Result, type SubmitParams, type SubmittedTransaction, type Success };