///
import EventEmitter from 'events';
import { Multiaddr } from '@multiformats/multiaddr';
import BN from 'bn.js';
import type { Libp2p as Libp2pType } from 'libp2p';
import type { PeerId } from '@libp2p/interface-peer-id';
import type { Components } from '@libp2p/interfaces/components';
import { type Address, Balance, type ChannelEntry, ChannelStatus, type DialOpts, type Hash, type HoprDB, type LibP2PHandlerFunction, NativeBalance, PublicKey, type Ticket } from '@hoprnet/hopr-utils';
import { PeerStatus, PeerOrigin, Health, health_to_string } from '../lib/core_network.js';
import { findPath } from './path/index.js';
import HoprCoreEthereum, { type Indexer } from '@hoprnet/hopr-core-ethereum';
import { type ChannelStrategyInterface, isStrategy, SaneDefaults, Strategy, StrategyFactory, StrategyTickResult } from './channel-strategy.js';
import type { ResolvedEnvironment } from './environment.js';
import type { EventEmitter as Libp2pEmitter } from '@libp2p/interfaces/events';
type Libp2p = Libp2pType & {
components: Components;
};
interface NetOptions {
ip: string;
port: number;
}
export type HoprOptions = {
environment: ResolvedEnvironment;
announce: boolean;
dataPath: string;
createDbIfNotExist: boolean;
forceCreateDB: boolean;
allowLocalConnections: boolean;
allowPrivateConnections: boolean;
password: string;
connector?: HoprCoreEthereum;
strategy: ChannelStrategyInterface;
hosts: {
ip4?: NetOptions;
ip6?: NetOptions;
};
heartbeatInterval?: number;
heartbeatThreshold?: number;
heartbeatVariance?: number;
networkQualityThreshold?: number;
onChainConfirmations?: number;
checkUnrealizedBalance?: boolean;
maxParallelConnections?: number;
noRelay?: boolean;
testing?: {
announceLocalAddresses?: boolean;
preferLocalAddresses?: boolean;
noDirectConnections?: boolean;
localModeStun?: boolean;
noWebRTCUpgrade?: boolean;
useMockedLibp2p?: boolean;
mockedDHT?: Map;
mockedNetwork?: Libp2pEmitter;
};
};
export type NodeStatus = 'UNINITIALIZED' | 'INITIALIZING' | 'RUNNING' | 'DESTROYED';
export type Subscribe = ((protocols: string | string[], handler: LibP2PHandlerFunction>, includeReply: true, errHandler: (err: any) => void) => void) & ((protocol: string | string[], handler: LibP2PHandlerFunction | void>, includeReply: false, errHandler: (err: any) => void) => void);
export type SendMessage = ((dest: PeerId, protocols: string | string[], msg: Uint8Array, includeReply: true, opts?: DialOpts) => Promise) & ((dest: PeerId, protocols: string | string[], msg: Uint8Array, includeReply: false, opts?: DialOpts) => Promise);
declare class Hopr extends EventEmitter {
private id;
db: HoprDB;
private options;
private publicNodesEmitter;
status: NodeStatus;
private stopPeriodicCheck;
private strategy;
private networkPeers;
private heartbeat;
private forward;
private acknowledgements;
private libp2pComponents;
private stopLibp2p;
private pubKey;
private knownPublicNodesCache;
environment: ResolvedEnvironment;
indexer: Indexer;
/**
* Create an uninitialized Hopr Node
*
* @constructor
*
* @param id PeerId to use, determines node address
* @param db used to persist protocol state
* @param connector an instance of the blockchain wrapper
* @param options
* @param publicNodesEmitter used to pass information about newly announced nodes to transport module
*/
constructor(id: PeerId, db: HoprDB, options: HoprOptions, publicNodesEmitter?: import("@hoprnet/hopr-connect").PublicNodesEmitter);
/**
* Start node
*
* The node has a fairly complex lifecycle. This method should do all setup
* required for a node to be functioning.
*
* If the node is not funded, it will throw.
*
* - Create a link to the ethereum blockchain
* - Finish indexing previous blocks [SLOW]
* - Find publicly accessible relays
*
* - Start LibP2P and work out our network configuration.
* - Pass the list of relays from the indexer
*
* - Wait for wallet to be funded with ETH [requires user interaction]
*
* - Announce address, pubkey, and multiaddr on chain.
*
* - Start heartbeat, automatic strategies, etc..
*
* @param __testingLibp2p use simulated libp2p instance for testing
*/
start(__initialNodes?: {
id: PeerId;
multiaddrs: Multiaddr[];
}[], __testingLibp2p?: Libp2p): Promise;
/**
* Pretty-print available addresses
*/
private printAvailableAddresses;
/**
* Pretty-print available addresses
*/
private printAvailableProtocols;
/**
* Checks if we are announcing public addresses to the DHT.
* If so, switch DHT to `server`-mode such that the node will
* reply to DHT queries of other nodes
*/
private maybeEnableDhtServerMode;
private maybeLogProfilingToGCloud;
private onChannelWaitingForCommitment;
private onOwnChannelUpdated;
/**
* If error provided is considered an out of funds error
* - it will emit that the node is out of funds
* @param error error thrown by an ethereum transaction
*/
private maybeEmitFundsEmptyEvent;
/**
* Called whenever a peer is announced
* @param peer newly announced peer
*/
private onPeerAnnouncement;
private strategyOpenChannel;
private strategyCloseChannel;
private updateChannelMetrics;
private tickChannelStrategy;
/**
* Returns the version of hopr-core.
*/
getVersion(): string;
/**
* Recalculates and retrieves the current connectivity health indicator.
*/
getConnectivityHealth(): number;
/**
* Shuts down the node and saves keys and peerBook in the database
*/
stop(): Promise;
/**
* Gets the peer ID of this HOPR node.
*/
getId(): PeerId;
/**
* List of addresses that is announced to other nodes
* @dev returned list can change at runtime
* @param peer peer to query for, default self
* @param _timeout [optional] custom timeout for DHT query
*/
getAddressesAnnouncedToDHT(peer?: PeerId, _timeout?: number): Promise;
/**
* List the addresses on which the node is listening
*/
getListeningAddresses(): Multiaddr[];
/**
* Gets the observed addresses of a given peer.
* @param peer peer to query for
*/
getObservedAddresses(peer: PeerId): Promise;
/**
* Validates the manual intermediate path by checking if it does not contain
* channels that are not opened.
* Throws an error if some channel is not opened.
* @param intermediatePath
*/
private validateIntermediatePath;
/**
* @param msg message to send
* @param destination PeerId of the destination
* @param intermediatePath optional set path manually
* @param hops optional number of required intermediate nodes
* @returns hex representation of ack challenge
*/
sendMessage(msg: Uint8Array, destination: PeerId, intermediatePath?: PublicKey[], hops?: number): Promise;
/**
* Ping a node.
* @param destination PeerId of the node
* @returns latency
*/
ping(destination: PeerId): Promise<{
info?: string;
latency: number;
}>;
/**
* @returns a list connected peerIds
*/
getConnectedPeers(): Iterable;
/**
* Takes a look into the indexer.
* @returns a list of announced multi addresses
*/
getAddressesAnnouncedOnChain(): AsyncGenerator;
/**
* @param peerId of the node we want to get the connection info for
* @returns various information about the connection
*/
getConnectionInfo(peerId: PeerId): PeerStatus | undefined;
/**
* Closes all open connections to a peer. Used to temporarily or permanently
* disconnect from a peer.
* Similar to `libp2p.hangUp` but catching all errors.
* @param peer PeerId of the peer from whom we want to disconnect
*/
private closeConnectionsTo;
/**
* @deprecated Used by API v1
* @returns a string describing the connection status between
* us and various nodes
*/
connectionReport(): Promise;
subscribeOnConnector(event: string, callback: () => void): void;
emitOnConnector(event: string): void;
startPeriodicStrategyCheck(): void;
/**
* Announces address of node on-chain to be reachable by other nodes.
* @dev Promise resolves before own announcement appears in the indexer
* @param announceRoutableAddress publish routable address if true
* @returns a Promise that resolves once announce transaction has been published
*/
private announce;
setChannelStrategy(strategy: ChannelStrategyInterface): void;
getChannelStrategy(): ChannelStrategyInterface;
getBalance(): Promise;
getNativeBalance(): Promise;
smartContractInfo(): {
network: string;
hoprTokenAddress: string;
hoprChannelsAddress: string;
hoprNetworkRegistryAddress: string;
channelClosureSecs: number;
};
/**
* Open a payment channel
*
* @param counterparty the counterparty's peerId
* @param amountToFund the amount to fund in HOPR(wei)
*/
openChannel(counterparty: PeerId, amountToFund: BN): Promise<{
channelId: Hash;
receipt: string;
}>;
/**
* Fund a payment channel
*
* @param counterparty the counter party's peerId
* @param myFund the amount to fund the channel in my favor HOPR(wei)
* @param counterpartyFund the amount to fund the channel in counterparty's favor HOPR(wei)
*/
fundChannel(counterparty: PeerId, myFund: BN, counterpartyFund: BN): Promise;
closeChannel(counterparty: PeerId, direction: 'incoming' | 'outgoing'): Promise<{
receipt: string;
status: ChannelStatus;
}>;
getAllTickets(): Promise;
getTickets(peerId: PeerId): Promise;
getTicketStatistics(): Promise<{
pending: number;
losing: number;
winProportion: number;
unredeemed: number;
unredeemedValue: Balance;
redeemed: number;
redeemedValue: Balance;
neglected: number;
rejected: number;
rejectedValue: Balance;
}>;
redeemAllTickets(): Promise;
redeemTicketsInChannel(peerId: PeerId): Promise;
/**
* Get the channel entry between source and destination node.
* @param src PeerId
* @param dest PeerId
* @returns the channel entry of those two nodes
*/
getChannel(src: PeerId, dest: PeerId): Promise;
getAllChannels(): Promise;
getChannelsFrom(addr: Address): Promise;
getChannelsTo(addr: Address): Promise;
getPublicKeyOf(addr: Address): Promise;
getEntryNodes(): Promise<{
id: PeerId;
multiaddrs: Multiaddr[];
}[]>;
signMessage(message: Uint8Array): Uint8Array;
getEthereumAddress(): Address;
/**
* Withdraw on-chain assets to a given address
* @param currency either native currency or HOPR tokens
* @param recipient the account where the assets should be transferred to
* @param amount how many tokens to be transferred
* @returns
*/
withdraw(currency: 'NATIVE' | 'HOPR', recipient: string, amount: string): Promise;
/**
* @param id the peer id of the account we want to check if it's allowed access to the network
* @returns true if allowed access
*/
isAllowedAccessToNetwork(id: PeerId): Promise;
/**
* Takes a destination, and optionally the desired number of hops,
* and samples randomly intermediate nodes
* that will relay that message before it reaches its destination.
*
* @param destination instance of peerInfo that contains the peerId of the destination
* @param hops optional number of required intermediate nodes (must be an integer 1,2,...MAX_HOPS inclusive)
*/
private getIntermediateNodes;
/**
* This is a utility method to wait until the node is funded.
* A backoff is implemented, if node has not been funded and
* MAX_DELAY is reached, this function will reject.
*/
waitForFunds(): Promise;
waitForRunning(): Promise;
}
export default Hopr;
export * from './constants.js';
export { createHoprNode } from './main.js';
export { Strategy, StrategyFactory, StrategyTickResult, isStrategy, SaneDefaults, findPath, PeerOrigin, PeerStatus, Health, health_to_string, type ChannelStrategyInterface };
export { resolveEnvironment, supportedEnvironments, type ResolvedEnvironment } from './environment.js';
export { CORE_CONSTANTS as CONSTANTS } from '../lib/core_misc.js';
export { sampleOptions } from './index.mock.js';
//# sourceMappingURL=index.d.ts.map