Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
199 lines (189 loc) · 8.25 KB
/
Copy pathindex.ts
File metadata and controls
199 lines (189 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import DbWorker from "./db.worker.ts";
import FiberWorker from "./fiber.worker.ts";
import { Mutex } from "async-mutex";
import { DbWorkerInitializationOptions, FiberInvokeRequest, FiberInvokeResponse, FiberWorkerInitializationOptions } from "./types/general.ts";
import { AbandonChannelParams, AcceptChannelParams, AcceptChannelResult, ListChannelsParams, ListChannelsResult, OpenChannelParams, OpenChannelResult, ShutdownChannelParams, UpdateChannelParams } from "./types/channel.ts";
import { GraphChannelsParams, GraphChannelsResult, GraphNodesParams, GraphNodesResult } from "./types/graph.ts";
import { NodeInfoResult } from "./types/info.ts";
import { GetInvoiceResult, InvoiceParams, InvoiceResult, NewInvoiceParams, ParseInvoiceParams, ParseInvoiceResult } from "./types/invoice.ts";
import { BuildPaymentRouterResult, BuildRouterParams, GetPaymentCommandParams, GetPaymentCommandResult, SendPaymentCommandParams, SendPaymentWithRouterParams } from "./types/payment.ts";
import { ConnectPeerParams, DisconnectPeerParams, ListPeerResult } from "./types/peer.ts";
const DEFAULT_BUFFER_SIZE = 50 * (1 << 20);
/**
* A Fiber Wasm instance
*/
class Fiber {
private dbWorker: Worker | null
private fiberWorker: Worker | null
private inputBuffer: SharedArrayBuffer
private outputBuffer: SharedArrayBuffer
private commandInvokeLock: Mutex;
/**
* Construct a Fiber Wasm instance.
* inputBuffer and outputBuffer are buffers used for transporting data between database and fiber wasm. Set them to appropriate sizes.
* @param inputBufferSize Size of inputBuffer
* @param outputBufferSize Size of outputBuffer
*/
constructor(inputBufferSize = DEFAULT_BUFFER_SIZE, outputBufferSize = DEFAULT_BUFFER_SIZE) {
this.dbWorker = new DbWorker();
this.fiberWorker = new FiberWorker();
this.inputBuffer = new SharedArrayBuffer(inputBufferSize);
this.outputBuffer = new SharedArrayBuffer(outputBufferSize);
this.commandInvokeLock = new Mutex();
}
/**
* Start the Fiber Wasm instance.
* @param config Config file for fiber
* @param fiberKeyPair keypair used for fiber
* @param ckbSecretKey secret key for CKB
* @param chainSpec Chain spec if chain is neither testnet nor mainnet
* @param logLevel log level, such as `trace`, `debug`, `info`, `error`
* @param databasePrefix Name prefix of IndexedDB store. Defaults to `/wasm`
*
*/
async start(
config: string,
fiberKeyPair: Uint8Array,
ckbSecretKey: Uint8Array,
chainSpec?: string,
logLevel: "trace" | "debug" | "info" | "error" = "info",
databasePrefix?: string) {
this.dbWorker.postMessage({
inputBuffer: this.inputBuffer,
outputBuffer: this.outputBuffer,
logLevel: logLevel
} as DbWorkerInitializationOptions);
this.fiberWorker.postMessage({
inputBuffer: this.inputBuffer,
outputBuffer: this.outputBuffer,
ckbSecretKey,
config,
fiberKeyPair,
logLevel,
chainSpec,
databasePrefix
} as FiberWorkerInitializationOptions);
await new Promise<void>((res, rej) => {
this.dbWorker. => res();
this.dbWorker. => rej(evt);
});
await new Promise<void>((res, rej) => {
this.fiberWorker. => res();
this.fiberWorker. => rej(evt);
});
}
invokeCommand(name: string, args?: any[]): Promise<any> {
// Why use lock here?
// fiber-wasm provided async APIs. Use lock here to avoid mixture of different calls
return this.commandInvokeLock.runExclusive(async () => {
this.fiberWorker.postMessage({
name,
args: args || []
} as FiberInvokeRequest);
return await new Promise((resolve, reject) => {
const clean = () => {
this.fiberWorker.removeEventListener("message", resolveFn);
this.fiberWorker.removeEventListener("error", errorFn);
}
const resolveFn = (evt: MessageEvent<FiberInvokeResponse>) => {
if (evt.data.ok === true) {
resolve(evt.data.data);
} else {
reject(evt.data.error);
}
clean();
};
const errorFn = (evt: ErrorEvent) => {
reject(evt);
clean();
};
this.fiberWorker.addEventListener("message", resolveFn);
this.fiberWorker.addEventListener("error", errorFn);
})
})
}
/**
* Stop the fiber instance.
*/
async stop() {
this.dbWorker.terminate();
this.fiberWorker.terminate();
}
async openChannel(params: OpenChannelParams): Promise<OpenChannelResult> {
return await this.invokeCommand("open_channel", [params]);
}
async acceptChannel(params: AcceptChannelParams): Promise<AcceptChannelResult> {
return await this.invokeCommand("accept_channel", [params]);
}
async abandonChannel(params: AbandonChannelParams): Promise<void> {
await this.invokeCommand("abandon_channel", [params]);
}
async listChannels(params: ListChannelsParams): Promise<ListChannelsResult> {
return await this.invokeCommand("list_channels", [params]);
}
async shutdownChannel(params: ShutdownChannelParams): Promise<void> {
await this.invokeCommand("shutdown_channel", [params]);
}
async updateChannel(params: UpdateChannelParams): Promise<void> {
await this.invokeCommand("update_channel", [params]);
}
async graphNodes(params: GraphNodesParams): Promise<GraphNodesResult> {
return await this.invokeCommand("graph_nodes", [params]);
}
async graphChannels(params: GraphChannelsParams): Promise<GraphChannelsResult> {
return await this.invokeCommand("graph_channels", [params]);
}
async nodeInfo(): Promise<NodeInfoResult> {
return await this.invokeCommand("node_info");
}
async newInvoice(params: NewInvoiceParams): Promise<InvoiceResult> {
return await this.invokeCommand("new_invoice", [params]);
}
async parseInvoice(params: ParseInvoiceParams): Promise<ParseInvoiceResult> {
return await this.invokeCommand("parse_invoice", [params]);
}
async getInvoice(params: InvoiceParams): Promise<GetInvoiceResult> {
return await this.invokeCommand("get_invoice", [params]);
}
async cancelInvoice(params: InvoiceParams): Promise<GetInvoiceResult> {
return await this.invokeCommand("cancel_invoice", [params]);
}
async sendPayment(params: SendPaymentCommandParams): Promise<GetPaymentCommandResult> {
return await this.invokeCommand("send_payment", [params]);
}
async getPayment(params: GetPaymentCommandParams): Promise<GetPaymentCommandResult> {
return await this.invokeCommand("get_payment", [params]);
}
async buildRouter(params: BuildRouterParams): Promise<BuildPaymentRouterResult> {
return await this.invokeCommand("build_router", [params]);
}
async sendPaymentWithRouter(params: SendPaymentWithRouterParams): Promise<GetPaymentCommandResult> {
return await this.invokeCommand("send_payment_with_router", [params]);
}
async connectPeer(params: ConnectPeerParams): Promise<void> {
await this.invokeCommand("connect_peer", [params]);
}
async disconnectPeer(params: DisconnectPeerParams): Promise<void> {
await this.invokeCommand("disconnect_peer", [params]);
}
async listPeers(): Promise<ListPeerResult> {
return await this.invokeCommand("list_peers");
}
}
export { Fiber };
/**
* Generate a random 32-byte secret key.
* @returns The secret key.
*/
export function randomSecretKey(): Uint8Array {
const arr = new Uint8Array(32);
crypto.getRandomValues(arr);
return arr;
}
export * from "./types/general.ts";
export * from "./types/channel.ts";
export * from "./types/graph.ts";
export * from "./types/info.ts";
export * from "./types/invoice.ts";
export * from "./types/payment.ts";
export * from "./types/peer.ts";