web-dc-api 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/dc.min.js +1 -1
  3. package/dist/esm/index.js +1 -1
  4. package/dist/index.d.ts +934 -878
  5. package/package.json +4 -8
  6. package/dist/cjs/helia-core-B1Xqha7a.js +0 -1
  7. package/dist/cjs/helia-core-D8Uv1KjQ.js +0 -1
  8. package/dist/cjs/polkadot-api-7PhQf3ws.js +0 -1
  9. package/dist/cjs/polkadot-api-CtrJVWuZ.js +0 -1
  10. package/dist/esm/chunks/helia-core-BxMqyK2Y.js +0 -1
  11. package/dist/esm/chunks/helia-core-DMXRpcO-.js +0 -1
  12. package/dist/esm/chunks/polkadot-api-5Y9Bw8VT.js +0 -1
  13. package/dist/esm/chunks/polkadot-api-D69Ioun_.js +0 -1
  14. package/lib/common/blowfish/block.ts +0 -259
  15. package/lib/common/blowfish/cipher.ts +0 -144
  16. package/lib/common/blowfish/const.ts +0 -195
  17. package/lib/common/chain.ts +0 -469
  18. package/lib/common/commonclient.ts +0 -202
  19. package/lib/common/constants.ts +0 -55
  20. package/lib/common/dc-key/ed25519.ts +0 -343
  21. package/lib/common/dc-key/keyManager.ts +0 -424
  22. package/lib/common/dcapi.ts +0 -98
  23. package/lib/common/dcutil.ts +0 -627
  24. package/lib/common/define.ts +0 -70
  25. package/lib/common/error.ts +0 -67
  26. package/lib/common/grpc-dc.ts +0 -104
  27. package/lib/common/module-system.ts +0 -184
  28. package/lib/common/service-worker.ts +0 -234
  29. package/lib/common/types/types.ts +0 -344
  30. package/lib/dc.ts +0 -701
  31. package/lib/implements/account/client.ts +0 -185
  32. package/lib/implements/account/manager.ts +0 -683
  33. package/lib/implements/aiproxy/client.ts +0 -357
  34. package/lib/implements/aiproxy/manager.ts +0 -670
  35. package/lib/implements/cache/client.ts +0 -105
  36. package/lib/implements/cache/manager.ts +0 -127
  37. package/lib/implements/comment/client.ts +0 -982
  38. package/lib/implements/comment/manager.ts +0 -1151
  39. package/lib/implements/dc/client.ts +0 -51
  40. package/lib/implements/dc/manager.ts +0 -33
  41. package/lib/implements/file/client.ts +0 -253
  42. package/lib/implements/file/file-cache-manager.ts +0 -142
  43. package/lib/implements/file/manager.ts +0 -1240
  44. package/lib/implements/file/seekableFileStream.ts +0 -344
  45. package/lib/implements/file/streamwriter.ts +0 -322
  46. package/lib/implements/keyvalue/client.ts +0 -376
  47. package/lib/implements/keyvalue/manager.ts +0 -759
  48. package/lib/implements/message/client.ts +0 -250
  49. package/lib/implements/message/manager.ts +0 -215
  50. package/lib/implements/threaddb/cbor/coding.ts +0 -62
  51. package/lib/implements/threaddb/cbor/event.ts +0 -336
  52. package/lib/implements/threaddb/cbor/node.ts +0 -542
  53. package/lib/implements/threaddb/cbor/record.ts +0 -398
  54. package/lib/implements/threaddb/common/AsyncMutex.ts +0 -24
  55. package/lib/implements/threaddb/common/addrinfo.ts +0 -135
  56. package/lib/implements/threaddb/common/dispatcher.ts +0 -81
  57. package/lib/implements/threaddb/common/idbstore-adapter.ts +0 -260
  58. package/lib/implements/threaddb/common/json-patcher.ts +0 -204
  59. package/lib/implements/threaddb/common/key.ts +0 -290
  60. package/lib/implements/threaddb/common/level-adapter.ts +0 -235
  61. package/lib/implements/threaddb/common/lineReader.ts +0 -79
  62. package/lib/implements/threaddb/common/logstore.ts +0 -215
  63. package/lib/implements/threaddb/common/transformed-datastore.ts +0 -308
  64. package/lib/implements/threaddb/core/app.ts +0 -206
  65. package/lib/implements/threaddb/core/core.ts +0 -230
  66. package/lib/implements/threaddb/core/db.ts +0 -249
  67. package/lib/implements/threaddb/core/event.ts +0 -54
  68. package/lib/implements/threaddb/core/head.ts +0 -89
  69. package/lib/implements/threaddb/core/identity.ts +0 -171
  70. package/lib/implements/threaddb/core/logstore.ts +0 -137
  71. package/lib/implements/threaddb/core/options.ts +0 -14
  72. package/lib/implements/threaddb/core/record.ts +0 -54
  73. package/lib/implements/threaddb/db/collection.ts +0 -1910
  74. package/lib/implements/threaddb/db/db.ts +0 -698
  75. package/lib/implements/threaddb/db/json2Query.ts +0 -192
  76. package/lib/implements/threaddb/db/query.ts +0 -524
  77. package/lib/implements/threaddb/dbclient.ts +0 -543
  78. package/lib/implements/threaddb/dbmanager.ts +0 -1906
  79. package/lib/implements/threaddb/lsstoreds/addr_book.ts +0 -549
  80. package/lib/implements/threaddb/lsstoreds/cache.ts +0 -36
  81. package/lib/implements/threaddb/lsstoreds/cyclic_batch.ts +0 -87
  82. package/lib/implements/threaddb/lsstoreds/global.ts +0 -151
  83. package/lib/implements/threaddb/lsstoreds/headbook.ts +0 -373
  84. package/lib/implements/threaddb/lsstoreds/keybook.ts +0 -297
  85. package/lib/implements/threaddb/lsstoreds/logstore.ts +0 -29
  86. package/lib/implements/threaddb/lsstoreds/metadata.ts +0 -223
  87. package/lib/implements/threaddb/net/define.ts +0 -149
  88. package/lib/implements/threaddb/net/grpcClient.ts +0 -589
  89. package/lib/implements/threaddb/net/grpcserver.ts +0 -146
  90. package/lib/implements/threaddb/net/net.ts +0 -2047
  91. package/lib/implements/threaddb/pb/lstore.proto +0 -38
  92. package/lib/implements/threaddb/pb/lstore.ts +0 -393
  93. package/lib/implements/threaddb/pb/lstore_pb.d.ts +0 -433
  94. package/lib/implements/threaddb/pb/lstore_pb.js +0 -1085
  95. package/lib/implements/threaddb/pb/net.proto +0 -194
  96. package/lib/implements/threaddb/pb/net_pb.d.ts +0 -2349
  97. package/lib/implements/threaddb/pb/net_pb.js +0 -5525
  98. package/lib/implements/threaddb/pb/proto-custom-types.ts +0 -212
  99. package/lib/implements/util/client.ts +0 -72
  100. package/lib/implements/util/manager.ts +0 -146
  101. package/lib/implements/wallet/manager.ts +0 -671
  102. package/lib/index.ts +0 -57
  103. package/lib/interfaces/DCContext.ts +0 -51
  104. package/lib/interfaces/aiproxy-interface.ts +0 -145
  105. package/lib/interfaces/auth-interface.ts +0 -118
  106. package/lib/interfaces/cache-interface.ts +0 -22
  107. package/lib/interfaces/client-interface.ts +0 -11
  108. package/lib/interfaces/comment-interface.ts +0 -167
  109. package/lib/interfaces/components/news-component.ts +0 -0
  110. package/lib/interfaces/database-interface.ts +0 -169
  111. package/lib/interfaces/file-interface.ts +0 -120
  112. package/lib/interfaces/index.ts +0 -10
  113. package/lib/interfaces/keyvalue-interface.ts +0 -156
  114. package/lib/interfaces/message-interface.ts +0 -22
  115. package/lib/interfaces/util-interface.ts +0 -31
  116. package/lib/modules/aiproxy-module.ts +0 -246
  117. package/lib/modules/auth-module.ts +0 -753
  118. package/lib/modules/cache-module.ts +0 -99
  119. package/lib/modules/client-module.ts +0 -71
  120. package/lib/modules/comment-module.ts +0 -429
  121. package/lib/modules/components/news-components.ts +0 -390
  122. package/lib/modules/database-module.ts +0 -598
  123. package/lib/modules/file-module.ts +0 -291
  124. package/lib/modules/index.ts +0 -13
  125. package/lib/modules/keyvalue-module.ts +0 -379
  126. package/lib/modules/message-module.ts +0 -107
  127. package/lib/modules/util-module.ts +0 -148
  128. package/lib/polyfills/process-env-browser.ts +0 -1
  129. package/lib/proto/datasource.ts +0 -93
  130. package/lib/proto/dcnet.proto +0 -1601
  131. package/lib/proto/dcnet_proto.d.ts +0 -22857
  132. package/lib/proto/dcnet_proto.js +0 -55204
  133. package/lib/proto/dcnet_proto_sparse.js +0 -55166
  134. package/lib/proto/oidfetch.proto +0 -25
  135. package/lib/proto/oidfetch_proto.d.ts +0 -585
  136. package/lib/proto/oidfetch_proto.js +0 -1247
  137. package/lib/serverless/babel-browser.ts +0 -39
  138. package/lib/serverless/base_entity.ts +0 -78
  139. package/lib/serverless/base_repository.ts +0 -414
  140. package/lib/serverless/browser_schema_extractor.ts +0 -283
  141. package/lib/serverless/decorator_factory.ts +0 -322
  142. package/lib/util/BrowserLineReader.ts +0 -73
  143. package/lib/util/base64.ts +0 -105
  144. package/lib/util/bcrypt.ts +0 -206
  145. package/lib/util/curve25519Encryption.ts +0 -418
  146. package/lib/util/dccrypt.ts +0 -73
  147. package/lib/util/logger.ts +0 -104
  148. package/lib/util/utils.ts +0 -289
@@ -1,469 +0,0 @@
1
- /**
2
- * 区块链相关的方法
3
- */
4
-
5
- import { Multiaddr, multiaddr } from "@multiformats/multiaddr";
6
- import { ApiPromise, WsProvider } from "@polkadot/api";
7
-
8
- import { isUser, sha256,hexToAscii } from "../util/utils";
9
- import { IAppInfo, User,PeerStatus } from "./types/types";
10
-
11
- import { hexToBytes } from "@noble/curves/abstract/utils";
12
- import { base32 } from "multiformats/bases/base32";
13
- import * as buffer from "buffer/";
14
- import { Ed25519PubKey } from "./dc-key/ed25519";
15
- import { UnibaseDecoder } from "multiformats";
16
- const { Buffer } = buffer;
17
-
18
- export interface StoreunitInfo {
19
- size: number;
20
- utype: number;
21
- peers: Set<string>;
22
- users: Set<string>;
23
- mbusers: Set<string>;//base32 编码的用户
24
- logs: Set<string>;
25
- }
26
-
27
-
28
-
29
- export class ChainUtil {
30
- dcchainapi: ApiPromise | undefined;
31
- // 连接链节点
32
- create = async (blockChainAddr: string) => {
33
- const chainProvider = new WsProvider(blockChainAddr);
34
- this.dcchainapi = await ApiPromise.create({
35
- provider: chainProvider,
36
- throwOnConnect: true,
37
- throwOnUnknown: true,
38
- });
39
- if (!this.dcchainapi) {
40
- console.error("dcchainapi init failed");
41
- return false;
42
- }
43
- return true;
44
- };
45
-
46
- // 获取区块高度
47
- async getBlockHeight(): Promise<number> {
48
- const lastBlock = await this.dcchainapi?.rpc.chain.getBlock();
49
- const blockHeight = lastBlock?.block.header.number.toNumber();
50
- return blockHeight || 0;
51
- }
52
- // 获取用户钱包信息
53
- async getUserInfoWithAccount(account: string): Promise<User> {
54
- const walletAccountStorage =
55
- await (this.dcchainapi?.query as any).dcNode.walletAccountStorage(account);
56
- if (!walletAccountStorage) {
57
- throw new Error("walletAccountStorage is null");
58
- }
59
- let userInfo = walletAccountStorage.toJSON();
60
- if (userInfo === null) {
61
- throw new Error("userInfo is null");
62
- }
63
-
64
-
65
- if (!isUser(userInfo)) {
66
- throw new Error("walletAccountStorage is not user");
67
- }
68
- if (userInfo?.parentAccount !== account) {
69
- const parentWalletAccountStorage =
70
- await (this.dcchainapi?.query as any).dcNode.walletAccountStorage(
71
- userInfo?.parentAccount
72
- );
73
- if (!parentWalletAccountStorage) {
74
- throw new Error("parentWalletAccountStorage is null");
75
- }
76
- const parentUserInfo = parentWalletAccountStorage?.toJSON();
77
- if (!parentUserInfo || !isUser(parentUserInfo)) {
78
- return userInfo;
79
- }
80
- userInfo.requestPeers = parentUserInfo.requestPeers;
81
- if (userInfo.peers?.length == 0) {
82
- //If the sub-account does not have account backup node information (this will happen if the sub-account is not bound to an nft account), the backup node information of the parent account will be obtained.
83
- userInfo.peers = parentUserInfo.peers;
84
- }
85
- userInfo.subscribeSpace = parentUserInfo.subscribeSpace;
86
- userInfo.usedSpace = parentUserInfo.usedSpace;
87
- userInfo.expireNumber = parentUserInfo.expireNumber;
88
- userInfo.purchaseNumber = parentUserInfo.purchaseNumber;
89
- // 冻结不为0则更新
90
- if(parentUserInfo.commentFrozenStatus != 0){
91
- userInfo.commentFrozenStatus = parentUserInfo.commentFrozenStatus;
92
- }
93
- if(parentUserInfo.spamFrozenStatus != 0){
94
- userInfo.spamFrozenStatus = parentUserInfo.spamFrozenStatus;
95
- }
96
-
97
- }
98
- //peers 进行统一处理
99
- for (let i = 0; i < userInfo.peers.length; i++) {
100
- userInfo.peers[i] = hexToAscii(userInfo.peers[i]!);
101
- }
102
- for (let i = 0; i < userInfo.requestPeers.length; i++) {
103
- userInfo.requestPeers[i] = hexToAscii(userInfo.requestPeers[i]!);
104
- }
105
- if (userInfo.dbConfig.length <= 2) {
106
- userInfo.dbConfig = ""; // 如果 dbConfig 为空,则设置为 ""
107
- }else{
108
- userInfo.dbConfigRaw = hexToBytes(userInfo.dbConfig.slice(2));
109
- }
110
- if (userInfo.encNftAccount.length <= 2) {
111
- userInfo.encNftAccount = "";
112
- }
113
- // 对 userInfo.peers 按与用户公钥的 XOR 距离进行排序
114
- if (userInfo.peers && Array.isArray(userInfo.peers) && account) {
115
- userInfo.peers.sort((peerA, peerB) => {
116
- // 将 peer 字符串转换为 Uint8Array (如果需要)
117
- const peerABytes = typeof peerA === 'string' ? new TextEncoder().encode(peerA) : peerA;
118
- const peerBBytes = typeof peerB === 'string' ? new TextEncoder().encode(peerB) : peerB;
119
- //account 是一个0x开头的16进制字符串转换为 Uint8Array
120
- const accountBytes = hexToBytes(account.slice(2));
121
- // 计算每个 peer 与公钥的 XOR 距离
122
- const distance1 = this.calculateDistance(peerABytes, accountBytes);
123
- const distance2 = this.calculateDistance(peerBBytes, accountBytes);
124
- if (distance1 < distance2) return -1;
125
- if (distance1 > distance2) return 1;
126
- return 0;
127
- });
128
- }
129
- return userInfo;
130
- }
131
- // 获取用户钱包信息
132
- async getUserInfoWithNftHex(nftHexAccount: string): Promise<User> {
133
- const walletAccount =
134
- await (this.dcchainapi?.query as any).dcNode.nftToWalletAccount(nftHexAccount);
135
- if (!walletAccount || !walletAccount.toString()) {
136
- throw new Error("walletAccount is null");
137
- }
138
- const userInfo = await this.getUserInfoWithAccount(
139
- walletAccount.toString()
140
- );
141
- return userInfo;
142
- }
143
-
144
- /**
145
- * 计算两个字节数组之间的XOR距离
146
- * @param key1 第一个字节数组
147
- * @param key2 第二个字节数组
148
- * @returns 两个键之间的XOR距离,以BigInt表示
149
- */
150
- calculateDistance(key1: Uint8Array, key2: Uint8Array): bigint {
151
- // 使用两个字节数组的最小长度
152
- const minLen = Math.min(key1.length, key2.length);
153
-
154
- // 创建结果数组存储XOR结果
155
- const result = new Uint8Array(minLen);
156
-
157
- // 按字节计算XOR距离
158
- for (let i = 0; i < minLen; i++) {
159
- result[i] = key1[i]! ^ key2[i]!;
160
- }
161
-
162
- // 将结果转换为BigInt用于比较
163
- // 首先转换为十六进制字符串以处理大数值
164
- let hexString = '0x';
165
- for (let i = 0; i < result.length; i++) {
166
- hexString += result[i]!.toString(16).padStart(2, '0');
167
- }
168
-
169
- // 如果结果为空(全零),返回0n
170
- if (hexString === '0x') {
171
- return BigInt(0);
172
- }
173
-
174
- return BigInt(hexString);
175
- }
176
-
177
- // 获取用户钱包信息
178
- async getUserInfoWithNft(nftAccount: string): Promise<User | null> {
179
- console.log("=========nftAccount", nftAccount);
180
- const accountBytes = new TextEncoder().encode(nftAccount);
181
- const accountHash = await sha256(accountBytes);
182
-
183
- const nftHexAccount = "0x" + Buffer.from(accountHash).toString("hex");
184
- const userInfo = await this.getUserInfoWithNftHex(nftHexAccount);
185
- return userInfo;
186
- }
187
-
188
-
189
- async getUserWalletAccount(nftAccount: string): Promise<string | null> {
190
- const accountBytes = new TextEncoder().encode(nftAccount);
191
- const accountHash = await sha256(accountBytes);
192
- const nftHexAccount = "0x" + Buffer.from(accountHash).toString("hex");
193
- const walletAccount =
194
- await (this.dcchainapi?.query as any).dcNode.nftToWalletAccount(nftHexAccount);
195
- if (!walletAccount || !walletAccount.toString()) {
196
- throw new Error("walletAccount is null");
197
- }
198
- return walletAccount.toString();
199
- }
200
-
201
- // 获取所有文件存储节点
202
- getObjNodes = async (cid: string): Promise<string[] | undefined> => {
203
- const fileInfo = (await (this.dcchainapi?.query as any).dcNode.files(cid)) || null;
204
- const fileInfoJSON = fileInfo?.toJSON();
205
- if (
206
- !fileInfoJSON ||
207
- typeof fileInfoJSON !== "object" ||
208
- (fileInfoJSON as { peers: string[] }).peers.length == 0
209
- ) {
210
- return;
211
- }
212
- const peers = (fileInfoJSON as { peers: string[] }).peers || [];
213
- return peers;
214
- };
215
-
216
- // 获取用户节点列表
217
- getAccountPeers = async (account: Uint8Array): Promise<string[] | null> => {
218
- try {
219
- const hexAccount = "0x" + Buffer.from(account).toString("hex");
220
- const userInfo = await this.getUserInfoWithAccount(hexAccount);
221
- if (!userInfo || !isUser(userInfo)) {
222
- return null;
223
- }
224
- const peers = userInfo.peers;
225
- return peers;
226
- }catch (error) {
227
- console.error("getAccountPeers error:", error);
228
- return null;
229
- }
230
- };
231
-
232
- // 链上查询节点信息
233
- // getDcNodeAddr = async (peerid: string) => {
234
- // const peerInfo = await (this.dcchainapi?.query as any).dcNode.peers(peerid);
235
- // const peerInfoJson = peerInfo?.toJSON();
236
- // if (
237
- // !peerInfoJson ||
238
- // typeof peerInfoJson !== "object" ||
239
- // (peerInfoJson as { ipAddress: string }).ipAddress == ""
240
- // ) {
241
- // console.log("no ip address found for peer: ", peerid);
242
- // return;
243
- // }
244
- // let nodeAddr = Buffer.from(
245
- // (peerInfoJson as { ipAddress: string }).ipAddress.slice(2),
246
- // "hex"
247
- // ).toString("utf8");
248
- // let addrParts = nodeAddr.split(",");
249
- // nodeAddr = addrParts[0];
250
- // //节点ws监听端口号在原来的tcp监听的基础上加10
251
- // let newNodeAddr = "";
252
- // const parts = nodeAddr.split("/");
253
- // for (let i = 0; i < parts.length; i++) {
254
- // if (parts[i] == "tcp" && i < parts.length - 1) {
255
- // const newPort = parseInt(parts[i + 1]) + 10;
256
- // newNodeAddr += parts[i] + "/" + newPort + "/";
257
- // i++;
258
- // } else if (parts[i] == "p2p") {
259
- // newNodeAddr += "ws/" + parts[i] + "/";
260
- // } else {
261
- // newNodeAddr += parts[i] + "/";
262
- // }
263
- // }
264
- // const addr = multiaddr(newNodeAddr);
265
- // console.log("newNodeAddr", newNodeAddr);
266
- // return addr;
267
- // };
268
- // 链上查询节点webrtc direct的地址信息,
269
- // peerid: 节点的peerid
270
- // 直接连接节点的地址
271
- getDcNodeWebrtcDirectAddr = async (peerid: string): Promise<[Multiaddr | null, PeerStatus]> => {
272
- const peerInfo = await (this.dcchainapi?.query as any).dcNode.peers(peerid);
273
- const peerInfoJson = peerInfo?.toJSON();
274
- if (
275
- !peerInfoJson ||
276
- typeof peerInfoJson !== "object" ||
277
- (peerInfoJson as { ipAddress: string }).ipAddress == ""
278
- ) {
279
- console.error("no ip address found for peer: ", peerid);
280
- return [null, PeerStatus.PeerStatusOffline];
281
- }
282
- let nodeAddr = Buffer.from(
283
- (peerInfoJson as { ipAddress: string }).ipAddress.slice(2),
284
- "hex"
285
- ).toString("utf8");
286
- let addrParts = nodeAddr.split(",");
287
- if (addrParts.length < 2) {
288
- return [null, PeerStatus.PeerStatusOffline];
289
- }
290
- const addr = multiaddr(addrParts[1]);
291
- const peerStatus = (peerInfoJson as { status: number }).status || PeerStatus.PeerStatusOffline;
292
- return [addr, peerStatus];
293
- };
294
-
295
- // 链上查询节点列表
296
- getDcNodeList = async (): Promise<string[]> => {
297
- const peerList = await (this.dcchainapi?.query as any).dcNode.onlineNodesAddress();
298
- const peerListJson = peerList?.toJSON();
299
- console.log(
300
- "peerListJson================================================",
301
- peerListJson
302
- );
303
- if (!peerListJson || typeof peerListJson !== "object") {
304
- console.error("no peer list found");
305
- return [];
306
- }
307
- let peers: string[] = [];
308
- if (Array.isArray(peerListJson)) {
309
- for (let i = 0; i < peerListJson.length; i++) {
310
- const peer = peerListJson[i];
311
- if (typeof peer === "string") {
312
- const peerJson = Buffer.from(peer.slice(2), "hex").toString(
313
- "utf8"
314
- );
315
- peers = peers.concat(peerJson);
316
- }
317
- }
318
- }
319
- console.log("peers", peers);
320
- return peers;
321
- };
322
-
323
- objectState = async (cid: string): Promise<[StoreunitInfo | null, Error|null]> =>{
324
- if (!this.dcchainapi) {
325
- return [null, new Error("dcchainapi is not initialized")];
326
- }
327
-
328
- const fileInfo = await (this.dcchainapi.query as any).dcNode.files(cid);
329
-
330
- if (!fileInfo || fileInfo.isEmpty) {
331
- return [null, new Error(`File with CID ${cid} not found`)];
332
- }
333
-
334
- const data = fileInfo.toJSON();
335
-
336
- if (!data) {
337
- return [null, new Error(`File with CID ${cid} not found`)];
338
- }
339
- // 构造返回数据
340
- if (typeof data === "object" && data !== null && !Array.isArray(data)) {
341
- return [{
342
- size: Number((data as any)['fileSize'] || 0),
343
- utype: Number((data as any)['fileType'] || 0),
344
- peers: new Set(
345
- Array.isArray((data as any)['peers'])
346
- ? (data as any)['peers'].map((peer: any) => {
347
- try {
348
- return hexToAscii(String(peer));
349
- } catch (e) {
350
- console.warn('Failed to convert peer ID format:', e);
351
- return String(peer); // 如果转换失败,保留原格式
352
- }
353
- })
354
- : []
355
- ),
356
- users: new Set(Array.isArray((data as any)['users']) ? (data as any)['users'].map(String) : []),
357
- mbusers: new Set(
358
- Array.isArray((data as any)['users'])
359
- ? (data as any)['users'].map((user: any) => {
360
- try {
361
- const userBytes = hexToBytes(user.slice(2));
362
- const mbUser = base32.encode(userBytes);
363
- return mbUser
364
- } catch (e) {
365
- console.warn('Failed to convert peer ID format:', e);
366
- return String(user); // 如果转换失败,保留原格式
367
- }
368
- })
369
- : []
370
- ),
371
- logs: new Set(
372
- Array.isArray((data as any)['dbLog'])
373
- ? (data as any)['dbLog'].map((log: any) => {
374
- try {
375
- return hexToAscii(String(log));
376
- } catch (e) {
377
- console.warn('Failed to convert peer ID format:', e);
378
- return String(log); // 如果转换失败,保留原格式
379
- }
380
- })
381
- : []
382
- ),
383
- }, null];
384
- }
385
- return [null, new Error(`File with CID ${cid} not found`)];
386
- }
387
-
388
- ifEnoughUserSpace = async (
389
- pubkeyRaw: Uint8Array,
390
- needSize?: number
391
- ): Promise<boolean> => {
392
- const hexAccount = "0x" + Buffer.from(pubkeyRaw).toString("hex");
393
- // 获取用户存储空间
394
- const userInfo = await this.getUserInfoWithAccount(
395
- hexAccount
396
- );
397
- if (!userInfo) {
398
- throw new Error("get user info error");
399
- }
400
-
401
- // 用户冻结
402
- if (userInfo.commentFrozenStatus != 0 || userInfo.spamFrozenStatus != 0) {
403
- return false
404
- }
405
-
406
- // 过期高度判断
407
- const blockHeight = (await this.getBlockHeight()) || 0;
408
- if (userInfo.expireNumber > 0 && userInfo.expireNumber < blockHeight) {
409
- return false
410
- }
411
-
412
- // 用户存储空间判断
413
- const needSizeNumber = needSize || 1024 * 1024; // 1M
414
- if (userInfo.subscribeSpace - userInfo.usedSpace < needSizeNumber) {
415
- return false
416
- }
417
-
418
- return true
419
- };
420
- refreshUserInfo = async (pubkeyRaw: Uint8Array): Promise<User> => {
421
- const hexAccount = "0x" + Buffer.from(pubkeyRaw).toString("hex");
422
- const userInfo = await this.getUserInfoWithAccount(hexAccount);
423
- return userInfo;
424
- };
425
-
426
-
427
-
428
- // 获取应用信息
429
- getAPPInfo = async (appId: string): Promise<IAppInfo> => {
430
- if (!this.dcchainapi || !this.dcchainapi.isReady) {
431
- throw new Error("dcchainapi is not initialized");
432
- }
433
- const appIdBytes = new TextEncoder().encode(appId);
434
- const appIdHex = "0x" + Buffer.from(appIdBytes).toString("hex");
435
- const appInfoStr = await (this.dcchainapi?.query as any).dcNode.appsInfo(appIdHex);
436
- if (!appInfoStr || appInfoStr.isEmpty) {
437
- throw new Error(`App info for ${appId} not found`);
438
- }
439
- const appJsonInfo = appInfoStr.toJSON() as any;
440
- if (!appJsonInfo || typeof appJsonInfo !== "object") {
441
- throw new Error(`App info for ${appId} is not valid`);
442
- }
443
- //将 ownerAccount 转换为 Ed25519PubKey
444
- const ownerBytes = hexToBytes(appJsonInfo?.ownerAccount.slice(2));
445
- const owner = new Ed25519PubKey(ownerBytes);
446
- const rewarder = appJsonInfo?.rewardedStash;
447
-
448
- let domain = ""
449
- if (appJsonInfo?.domain && appJsonInfo?.domain.length > 0) {
450
- const domainBytes = hexToBytes(appJsonInfo?.domain.slice(2));
451
- domain = new TextDecoder().decode(domainBytes).toString();
452
- }
453
-
454
- let fid = "";
455
- if (appJsonInfo?.fileId && appJsonInfo?.fileId.length > 0) {
456
- const fidBytes = hexToBytes(appJsonInfo?.fileId.slice(2));
457
- fid = new TextDecoder().decode(fidBytes).toString();
458
- }
459
- const appInfo :IAppInfo = {
460
- appId: appId,
461
- domain: domain,
462
- owner: owner.string(),
463
- rewarder: rewarder,
464
- fid: fid,
465
- }
466
- return appInfo ;
467
- };
468
-
469
- }
@@ -1,202 +0,0 @@
1
- // common/commonClient.ts
2
- import type { Multiaddr } from "@multiformats/multiaddr";
3
- import type { Client } from "./dcapi";
4
- import { keys } from "@libp2p/crypto";
5
- import { Ed25519PubKey } from "./dc-key/ed25519";
6
- import {
7
- extractPeerIdFromMultiaddr,
8
- generateSymKeyForPrikey,
9
- extractPublicKeyFromPeerId,
10
- } from "./dc-key/keyManager";
11
- import { sha256, getRandomBytes, concatenateUint8Arrays } from "../util/utils";
12
- import { Encryption } from "../util/curve25519Encryption";
13
- import { decryptContent } from "../util/dccrypt";
14
- import { toString as uint8ArrayToString } from "uint8arrays/to-string";
15
- import { PeerId } from "@libp2p/interface";
16
- import { Libp2pGrpcClient } from "grpc-libp2p-client";
17
-
18
- import { dcnet } from "../proto/dcnet_proto";
19
-
20
- interface AccountLoginRequest {
21
- accounthashencrypt: Uint8Array;
22
- pubkeyencrypt: Uint8Array;
23
- loginkeyrandencrypt: Uint8Array;
24
- }
25
-
26
- export class CommonClient {
27
- client: Client;
28
-
29
- constructor(dcClient: Client) {
30
- this.client = dcClient;
31
- }
32
-
33
- // 登陆
34
- async accountLogin(
35
- nftAccount: string,
36
- password: string,
37
- safecode: string,
38
- ): Promise<string> {
39
- //登录
40
- const prikey = await this._accountDoLogin(
41
- nftAccount,
42
- password,
43
- safecode,
44
- this.client.peerAddr
45
- );
46
- let mnemonic = "";
47
- if (prikey.startsWith("mnemonic:")) {
48
- mnemonic = prikey.slice(9);
49
- return mnemonic;
50
- }
51
- return '';
52
- }
53
-
54
- async _accountDoLogin(
55
- account: string,
56
- password: string,
57
- seccode: string,
58
- peerAddr: Multiaddr
59
- ): Promise<string> {
60
- if (this.client.p2pNode == null || this.client.p2pNode.peerId == null) {
61
- throw new Error("p2pNode is null or node privateKey is null");
62
- }
63
- //生成临时ed25519公私钥对
64
- const keyPair = await keys.generateKeyPair("Ed25519");
65
- // 获取私钥
66
- const privateKeyRaw = keyPair.raw;
67
- // 获取公钥
68
- const publicKey = keyPair.publicKey;
69
- const tempEdPubkey = Ed25519PubKey.formEd25519PublicKey(publicKey);
70
- //multiaddr 中提取peerid
71
- const peerId = await extractPeerIdFromMultiaddr(peerAddr);
72
- console.log("peerId:", peerId.toString());
73
- // 获取当前节点的peerID,并且获取节点的公钥
74
- const localPubkeyBytes = this.client.p2pNode.peerId.publicKey;
75
- const req = await generateAccountLoginRequestWithPeerId(
76
- peerId,
77
- account,
78
- password,
79
- seccode,
80
- tempEdPubkey
81
- );
82
- const prikeyencrypt2 = await this._accountloginApi(
83
- req.accounthashencrypt,
84
- req.pubkeyencrypt,
85
- req.loginkeyrandencrypt,
86
- peerAddr
87
- );
88
- //从返回的数据中解析出私钥
89
- //Decrypt with private key
90
- const prikeyEncrypt = await Encryption.decrypt(
91
- privateKeyRaw,
92
- prikeyencrypt2
93
- );
94
- const aeskey = await generateSymKeyForPrikey(account, password);
95
- //Aes gcm解密
96
- const prikey = await decryptContent(prikeyEncrypt, aeskey.raw);
97
- return uint8ArrayToString(prikey);
98
- }
99
-
100
- async _accountloginApi(
101
- accounthashencrypt: Uint8Array,
102
- pubkeyencrypt: Uint8Array,
103
- loginkeyrandencrypt: Uint8Array,
104
- peerAddr: Multiaddr
105
- ): Promise<Uint8Array> {
106
- try {
107
- const grpcClient = new Libp2pGrpcClient(
108
- this.client.p2pNode,
109
- peerAddr || this.client.peerAddr,
110
- this.client.token,
111
- this.client.protocol
112
- );
113
- const message = new dcnet.pb.AccountLoginRequest({});
114
- message.accounthashencrypt = accounthashencrypt;
115
- message.pubkeyencrypt = pubkeyencrypt;
116
- message.loginkeyrandencrypt = loginkeyrandencrypt;
117
- const messageBytes =
118
- dcnet.pb.AccountLoginRequest.encode(message).finish();
119
- const responseData = await grpcClient.unaryCall(
120
- "/dcnet.pb.Service/AccountLogin",
121
- messageBytes,
122
- 30000
123
- );
124
- const decoded = dcnet.pb.AccountLoginReply.decode(responseData);
125
- const prikeyencrypt2 = decoded.prikeyencrypt2;
126
- return prikeyencrypt2;
127
- } catch (err) {
128
- console.error("AccountLogin error:", err);
129
- throw err;
130
- }
131
- }
132
- }
133
-
134
- /**
135
- * 生成账户登录请求
136
- * @param peerId - 节点ID
137
- * @param account - 账户名
138
- * @param password - 密码
139
- * @param seccode - 安全码
140
- * @param pk - 返回数据加密用的公钥
141
- * @returns 登录请求对象
142
- */
143
- async function generateAccountLoginRequestWithPeerId(
144
- peerId: PeerId,
145
- account: string,
146
- password: string,
147
- seccode: string,
148
- pk: Ed25519PubKey
149
- ): Promise<AccountLoginRequest> {
150
- try {
151
- // 获取节点公钥
152
- const peerPubkey = await extractPublicKeyFromPeerId(peerId);
153
- const serverPubkey = peerPubkey; // 假设已经做了适当的转换
154
-
155
- // 计算账户哈希
156
- const accountBytes = new TextEncoder().encode(account);
157
- const accountHash = await sha256(accountBytes);
158
-
159
- // 使用节点公钥加密账户哈希
160
- const accountHashCrypt = await Encryption.encrypt(
161
- serverPubkey.raw,
162
- accountHash
163
- );
164
- // 获取并加密公钥
165
- const pkBytes = pk.raw;
166
- const pubkeyEncrypt = await Encryption.encrypt(serverPubkey.raw, pkBytes);
167
-
168
- // 生成随机密钥
169
- const randKey = getRandomBytes(32);
170
-
171
- // 计算密码哈希
172
- const passwordBytes = new TextEncoder().encode(password);
173
- const passwordSlice = passwordBytes.slice(0, 2);
174
- const passwordHash = await sha256(passwordSlice);
175
- const passwordHashLast2 = passwordHash.slice(-2);
176
-
177
- // 计算登录密钥
178
- const seccodeBytes = new TextEncoder().encode(seccode);
179
- const loginKeySeed = concatenateUint8Arrays(
180
- accountHash,
181
- passwordHashLast2,
182
- seccodeBytes
183
- );
184
- const loginkey = await sha256(loginKeySeed);
185
-
186
- // 加密登录密钥和随机密钥
187
- const loginkeyRand = concatenateUint8Arrays(loginkey, randKey);
188
- const loginkeyRandEncrypt = await Encryption.encrypt(
189
- serverPubkey.raw,
190
- loginkeyRand
191
- );
192
-
193
- // 返回登录请求对象
194
- return {
195
- accounthashencrypt: accountHashCrypt,
196
- pubkeyencrypt: pubkeyEncrypt,
197
- loginkeyrandencrypt: loginkeyRandEncrypt,
198
- };
199
- } catch (error: any) {
200
- throw new Error(`Failed to generate login request: ${error.message}`);
201
- }
202
- }