neozipkit 0.1.1 → 0.3.0

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 (330) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +371 -200
  3. package/contracts/ABI.txt +889 -0
  4. package/contracts/Bytecode.txt +1 -0
  5. package/contracts/COMPILATION_NOTES.md +59 -0
  6. package/contracts/QUICK_DEPLOY.md +286 -0
  7. package/contracts/README.md +256 -0
  8. package/contracts/VERIFICATION.md +308 -0
  9. package/contracts/deploy-interactive.js +448 -0
  10. package/contracts/deployment-arbitrum-sepolia.json +12 -0
  11. package/contracts/deployment-arbitrum.json +12 -0
  12. package/contracts/deployment-eth-sepolia.json +12 -0
  13. package/contracts/hardhat.config.js +114 -0
  14. package/contracts/package.json +20 -0
  15. package/contracts/scripts/compile-and-extract.js +119 -0
  16. package/contracts/scripts/verify-contract.js +223 -0
  17. package/contracts/src/{NZIP-NFT-Private.sol → NZIP-NFT-v2.0.sol} +66 -151
  18. package/contracts/src/NZIP-NFT.sol +9 -15
  19. package/dist/{browser → blockchain/browser}/TokenVerifierBrowser.d.ts +11 -20
  20. package/dist/blockchain/browser/TokenVerifierBrowser.d.ts.map +1 -0
  21. package/dist/{browser → blockchain/browser}/TokenVerifierBrowser.js +106 -92
  22. package/dist/blockchain/browser/TokenVerifierBrowser.js.map +1 -0
  23. package/dist/blockchain/browser/WalletManagerBrowser.d.ts +98 -0
  24. package/dist/blockchain/browser/WalletManagerBrowser.d.ts.map +1 -0
  25. package/dist/blockchain/browser/WalletManagerBrowser.js +434 -0
  26. package/dist/blockchain/browser/WalletManagerBrowser.js.map +1 -0
  27. package/dist/blockchain/browser/ZipkitMinterBrowser.d.ts +58 -0
  28. package/dist/blockchain/browser/ZipkitMinterBrowser.d.ts.map +1 -0
  29. package/dist/blockchain/browser/ZipkitMinterBrowser.js +317 -0
  30. package/dist/blockchain/browser/ZipkitMinterBrowser.js.map +1 -0
  31. package/dist/blockchain/browser/index.d.ts +11 -0
  32. package/dist/blockchain/browser/index.d.ts.map +1 -0
  33. package/dist/blockchain/browser/index.js +16 -0
  34. package/dist/blockchain/browser/index.js.map +1 -0
  35. package/dist/{server/blockchain/WalletAnalyzer.d.ts → blockchain/core/WalletManager.d.ts} +69 -26
  36. package/dist/blockchain/core/WalletManager.d.ts.map +1 -0
  37. package/dist/{server/blockchain/WalletAnalyzer.js → blockchain/core/WalletManager.js} +172 -160
  38. package/dist/blockchain/core/WalletManager.js.map +1 -0
  39. package/dist/blockchain/core/ZipkitMinter.d.ts +141 -0
  40. package/dist/blockchain/core/ZipkitMinter.d.ts.map +1 -0
  41. package/dist/blockchain/core/ZipkitMinter.js +548 -0
  42. package/dist/blockchain/core/ZipkitMinter.js.map +1 -0
  43. package/dist/blockchain/core/ZipkitOTS.d.ts +126 -0
  44. package/dist/blockchain/core/ZipkitOTS.d.ts.map +1 -0
  45. package/dist/blockchain/core/ZipkitOTS.js +506 -0
  46. package/dist/blockchain/core/ZipkitOTS.js.map +1 -0
  47. package/dist/blockchain/core/ZipkitVerifier.d.ts +177 -0
  48. package/dist/blockchain/core/ZipkitVerifier.d.ts.map +1 -0
  49. package/dist/blockchain/core/ZipkitVerifier.js +632 -0
  50. package/dist/blockchain/core/ZipkitVerifier.js.map +1 -0
  51. package/dist/blockchain/core/contracts.d.ts +83 -0
  52. package/dist/blockchain/core/contracts.d.ts.map +1 -0
  53. package/dist/blockchain/core/contracts.js +341 -0
  54. package/dist/blockchain/core/contracts.js.map +1 -0
  55. package/dist/blockchain/core/index.d.ts +12 -0
  56. package/dist/blockchain/core/index.d.ts.map +1 -0
  57. package/dist/blockchain/core/index.js +59 -0
  58. package/dist/blockchain/core/index.js.map +1 -0
  59. package/dist/blockchain/index.d.ts +11 -0
  60. package/dist/blockchain/index.d.ts.map +1 -0
  61. package/dist/blockchain/index.js +34 -0
  62. package/dist/blockchain/index.js.map +1 -0
  63. package/dist/blockchain/node/WalletManagerNode.d.ts +47 -0
  64. package/dist/blockchain/node/WalletManagerNode.d.ts.map +1 -0
  65. package/dist/blockchain/node/WalletManagerNode.js +203 -0
  66. package/dist/blockchain/node/WalletManagerNode.js.map +1 -0
  67. package/dist/blockchain/node/index.d.ts +12 -0
  68. package/dist/blockchain/node/index.d.ts.map +1 -0
  69. package/dist/blockchain/node/index.js +24 -0
  70. package/dist/blockchain/node/index.js.map +1 -0
  71. package/dist/browser/ZipkitBrowser.d.ts +27 -0
  72. package/dist/browser/ZipkitBrowser.d.ts.map +1 -0
  73. package/dist/browser/{ZipKitBrowser.js → ZipkitBrowser.js} +96 -43
  74. package/dist/browser/ZipkitBrowser.js.map +1 -0
  75. package/dist/browser/index.d.ts +12 -0
  76. package/dist/browser/index.d.ts.map +1 -0
  77. package/dist/browser/index.js +42 -0
  78. package/dist/browser/index.js.map +1 -0
  79. package/dist/browser-esm/index.d.ts +12 -0
  80. package/dist/browser-esm/index.js +59559 -0
  81. package/dist/browser-esm/index.js.map +7 -0
  82. package/dist/browser-umd/index.d.ts +12 -0
  83. package/dist/browser-umd/index.js +59576 -0
  84. package/dist/browser-umd/index.js.map +7 -0
  85. package/dist/browser-umd/index.min.js +63 -0
  86. package/dist/browser.d.ts +8 -17
  87. package/dist/browser.js +13 -29
  88. package/dist/core/ZipCompress.d.ts +99 -0
  89. package/dist/core/ZipCompress.d.ts.map +1 -0
  90. package/dist/core/ZipCompress.js +309 -0
  91. package/dist/core/ZipCompress.js.map +1 -0
  92. package/dist/core/ZipDecompress.d.ts +58 -0
  93. package/dist/core/ZipDecompress.d.ts.map +1 -0
  94. package/dist/core/ZipDecompress.js +172 -0
  95. package/dist/core/ZipDecompress.js.map +1 -0
  96. package/dist/{shared → core}/ZipEntry.d.ts +8 -1
  97. package/dist/core/ZipEntry.d.ts.map +1 -0
  98. package/dist/{shared → core}/ZipEntry.js +224 -81
  99. package/dist/core/ZipEntry.js.map +1 -0
  100. package/dist/core/Zipkit.d.ts +315 -0
  101. package/dist/core/Zipkit.d.ts.map +1 -0
  102. package/dist/core/Zipkit.js +647 -0
  103. package/dist/core/Zipkit.js.map +1 -0
  104. package/dist/core/components/HashCalculator.d.ts +138 -0
  105. package/dist/core/components/HashCalculator.d.ts.map +1 -0
  106. package/dist/core/components/HashCalculator.js +360 -0
  107. package/dist/core/components/HashCalculator.js.map +1 -0
  108. package/dist/core/components/Logger.d.ts +73 -0
  109. package/dist/core/components/Logger.d.ts.map +1 -0
  110. package/dist/core/components/Logger.js +156 -0
  111. package/dist/core/components/Logger.js.map +1 -0
  112. package/dist/core/components/ProgressTracker.d.ts +43 -0
  113. package/dist/core/components/ProgressTracker.d.ts.map +1 -0
  114. package/dist/core/components/ProgressTracker.js +112 -0
  115. package/dist/core/components/ProgressTracker.js.map +1 -0
  116. package/dist/{shared → core}/components/Support.d.ts +1 -0
  117. package/dist/core/components/Support.d.ts.map +1 -0
  118. package/dist/{shared → core}/components/Support.js +1 -0
  119. package/dist/core/components/Support.js.map +1 -0
  120. package/dist/{shared → core}/components/Util.d.ts +7 -2
  121. package/dist/core/components/Util.d.ts.map +1 -0
  122. package/dist/{shared → core}/components/Util.js +14 -34
  123. package/dist/core/components/Util.js.map +1 -0
  124. package/dist/{shared → core}/constants/Errors.d.ts +1 -2
  125. package/dist/core/constants/Errors.d.ts.map +1 -0
  126. package/dist/{shared → core}/constants/Errors.js +1 -3
  127. package/dist/core/constants/Errors.js.map +1 -0
  128. package/dist/{shared → core}/constants/Headers.d.ts +3 -0
  129. package/dist/core/constants/Headers.d.ts.map +1 -0
  130. package/dist/{shared → core}/constants/Headers.js +20 -17
  131. package/dist/core/constants/Headers.js.map +1 -0
  132. package/dist/core/encryption/Manager.d.ts +58 -0
  133. package/dist/core/encryption/Manager.d.ts.map +1 -0
  134. package/dist/core/encryption/Manager.js +121 -0
  135. package/dist/core/encryption/Manager.js.map +1 -0
  136. package/dist/core/encryption/ZipCrypto.d.ts +172 -0
  137. package/dist/core/encryption/ZipCrypto.d.ts.map +1 -0
  138. package/dist/core/encryption/ZipCrypto.js +554 -0
  139. package/dist/core/encryption/ZipCrypto.js.map +1 -0
  140. package/dist/core/encryption/index.d.ts +9 -0
  141. package/dist/core/encryption/index.d.ts.map +1 -0
  142. package/dist/core/encryption/index.js +17 -0
  143. package/dist/core/encryption/index.js.map +1 -0
  144. package/dist/core/encryption/types.d.ts +29 -0
  145. package/dist/core/encryption/types.d.ts.map +1 -0
  146. package/dist/core/encryption/types.js +12 -0
  147. package/dist/core/encryption/types.js.map +1 -0
  148. package/dist/core/index.d.ts +24 -0
  149. package/dist/core/index.d.ts.map +1 -0
  150. package/dist/core/index.js +57 -0
  151. package/dist/core/index.js.map +1 -0
  152. package/dist/{shared → core}/version.d.ts +1 -0
  153. package/dist/core/version.d.ts.map +1 -0
  154. package/dist/core/version.js +31 -0
  155. package/dist/core/version.js.map +1 -0
  156. package/dist/index.d.ts +8 -25
  157. package/dist/index.d.ts.map +1 -0
  158. package/dist/index.js +29 -47
  159. package/dist/index.js.map +1 -0
  160. package/dist/node/ZipCompressNode.d.ts +123 -0
  161. package/dist/node/ZipCompressNode.d.ts.map +1 -0
  162. package/dist/node/ZipCompressNode.js +576 -0
  163. package/dist/node/ZipCompressNode.js.map +1 -0
  164. package/dist/node/ZipDecompressNode.d.ts +120 -0
  165. package/dist/node/ZipDecompressNode.d.ts.map +1 -0
  166. package/dist/node/ZipDecompressNode.js +461 -0
  167. package/dist/node/ZipDecompressNode.js.map +1 -0
  168. package/dist/node/ZipkitNode.d.ts +406 -0
  169. package/dist/node/ZipkitNode.d.ts.map +1 -0
  170. package/dist/node/ZipkitNode.js +1305 -0
  171. package/dist/node/ZipkitNode.js.map +1 -0
  172. package/dist/node/index.d.ts +26 -0
  173. package/dist/node/index.d.ts.map +1 -0
  174. package/dist/node/index.js +65 -0
  175. package/dist/node/index.js.map +1 -0
  176. package/dist/types/index.d.ts +59 -0
  177. package/dist/types/index.d.ts.map +1 -0
  178. package/dist/types/index.js +36 -1
  179. package/dist/types/index.js.map +1 -0
  180. package/examples/README.md +269 -0
  181. package/examples/blockchain-tokenize.ts +354 -0
  182. package/examples/create-zip.ts +172 -0
  183. package/examples/extract-zip.ts +158 -0
  184. package/examples/list-zip.ts +161 -0
  185. package/examples/test-files/data.json +116 -0
  186. package/examples/test-files/document.md +80 -0
  187. package/examples/test-files/document.txt +2 -0
  188. package/examples/test-files/file1.txt +48 -0
  189. package/examples/test-files/file2.txt +80 -0
  190. package/examples/tsconfig.json +44 -0
  191. package/examples/unzip-token.ts +6 -3
  192. package/examples/verify-tokenized-zip.ts +305 -0
  193. package/package.json +117 -23
  194. package/src/blockchain/README.md +222 -0
  195. package/src/{browser → blockchain/browser}/TokenVerifierBrowser.ts +125 -79
  196. package/src/blockchain/browser/WalletManagerBrowser.ts +486 -0
  197. package/src/blockchain/browser/ZipkitMinterBrowser.ts +400 -0
  198. package/src/blockchain/browser/index.ts +13 -0
  199. package/src/blockchain/core/WalletManager.ts +436 -0
  200. package/src/blockchain/core/ZipkitMinter.ts +716 -0
  201. package/src/blockchain/core/ZipkitOTS.ts +588 -0
  202. package/src/blockchain/core/ZipkitVerifier.ts +853 -0
  203. package/src/blockchain/core/contracts.ts +370 -0
  204. package/src/blockchain/core/index.ts +71 -0
  205. package/src/blockchain/index.ts +27 -0
  206. package/src/blockchain/node/WalletManagerNode.ts +171 -0
  207. package/src/blockchain/node/index.ts +40 -0
  208. package/src/browser/{ZipKitBrowser.ts → ZipkitBrowser.ts} +104 -41
  209. package/src/browser/index.esm.ts +37 -0
  210. package/src/browser/index.ts +25 -0
  211. package/src/core/ZipCompress.ts +398 -0
  212. package/src/core/ZipDecompress.ts +212 -0
  213. package/src/{shared → core}/ZipEntry.ts +239 -89
  214. package/src/core/Zipkit.ts +794 -0
  215. package/src/core/components/HashCalculator.ts +384 -0
  216. package/src/core/components/Logger.ts +180 -0
  217. package/src/core/components/ProgressTracker.ts +134 -0
  218. package/src/{shared → core}/components/Util.ts +12 -34
  219. package/src/{shared → core}/constants/Errors.ts +0 -4
  220. package/src/{shared → core}/constants/Headers.ts +19 -17
  221. package/src/core/encryption/Manager.ts +137 -0
  222. package/src/core/encryption/ZipCrypto.ts +650 -0
  223. package/src/core/encryption/index.ts +15 -0
  224. package/src/core/encryption/types.ts +33 -0
  225. package/src/core/index.ts +34 -0
  226. package/src/core/version.ts +33 -0
  227. package/src/index.ts +54 -32
  228. package/src/node/ZipCompressNode.ts +632 -0
  229. package/src/node/ZipDecompressNode.ts +508 -0
  230. package/src/node/ZipkitNode.ts +1559 -0
  231. package/src/node/index.ts +69 -0
  232. package/src/types/index.ts +131 -1
  233. package/src/types/opentimestamps.d.ts +1 -23
  234. package/contracts/Lock.sol +0 -34
  235. package/contracts/bytecode.txt +0 -1
  236. package/contracts/compile-contract.js +0 -168
  237. package/contracts/deploy/deploy-both-contracts.js +0 -286
  238. package/contracts/deploy/deploy-enhanced-contract.js +0 -197
  239. package/contracts/deploy/deploy-private-contract.js +0 -190
  240. package/contracts/deploy/deploy-public-clean.js +0 -1063
  241. package/contracts/deploy/deploy-public-contract.js +0 -1107
  242. package/contracts/deployment.config.example.js +0 -25
  243. package/contracts/remix-compile.js +0 -222
  244. package/contracts/setup-deployment.js +0 -51
  245. package/contracts/src/ZipFileNFT-DEPRECATED-6field.sol +0 -260
  246. package/contracts/src/ZipFileNFT-DEPRECATED-Enhanced.sol +0 -289
  247. package/dist/browser/CertificateGeneratorBrowser.d.ts +0 -75
  248. package/dist/browser/CertificateGeneratorBrowser.js +0 -433
  249. package/dist/browser/ZipKitBrowser.d.ts +0 -18
  250. package/dist/browser/ZipKitStampBrowser.d.ts +0 -2
  251. package/dist/browser/ZipKitStampBrowser.js +0 -12
  252. package/dist/browser-index.d.ts +0 -21
  253. package/dist/browser-index.js +0 -58
  254. package/dist/server/blockchain/CertificateToken.d.ts +0 -48
  255. package/dist/server/blockchain/CertificateToken.js +0 -386
  256. package/dist/server/blockchain/NFTMinter.d.ts +0 -41
  257. package/dist/server/blockchain/NFTMinter.js +0 -323
  258. package/dist/server/blockchain/TokenQuerier.d.ts +0 -31
  259. package/dist/server/blockchain/TokenQuerier.js +0 -259
  260. package/dist/server/blockchain/TokenVerifier.d.ts +0 -20
  261. package/dist/server/blockchain/TokenVerifier.js +0 -395
  262. package/dist/server/blockchain/WalletFormatter.d.ts +0 -39
  263. package/dist/server/blockchain/WalletFormatter.js +0 -196
  264. package/dist/server/blockchain/WalletManager.d.ts +0 -46
  265. package/dist/server/blockchain/WalletManager.js +0 -294
  266. package/dist/server/blockchain/ZipMetadata.d.ts +0 -27
  267. package/dist/server/blockchain/ZipMetadata.js +0 -131
  268. package/dist/server/blockchain/ZipTokenProcessor.d.ts +0 -44
  269. package/dist/server/blockchain/ZipTokenProcessor.js +0 -204
  270. package/dist/server/blockchain/constants.d.ts +0 -102
  271. package/dist/server/blockchain/constants.js +0 -968
  272. package/dist/server/blockchain/index.d.ts +0 -9
  273. package/dist/server/blockchain/index.js +0 -44
  274. package/dist/server/blockchain/test-certificate.d.ts +0 -8
  275. package/dist/server/blockchain/test-certificate.js +0 -100
  276. package/dist/server/blockchain/types.d.ts +0 -69
  277. package/dist/server/blockchain/types.js +0 -51
  278. package/dist/server/platform/server/ZipKitServer.d.ts +0 -105
  279. package/dist/server/platform/server/ZipKitServer.js +0 -437
  280. package/dist/server/platform/servercomponents/ZipKitOTS.d.ts +0 -91
  281. package/dist/server/platform/servercomponents/ZipKitOTS.js +0 -271
  282. package/dist/shared/ZipKit.d.ts +0 -249
  283. package/dist/shared/ZipKit.js +0 -789
  284. package/dist/shared/components/CertificateOTS.d.ts +0 -15
  285. package/dist/shared/components/CertificateOTS.js +0 -116
  286. package/dist/shared/components/FileSys.d.ts +0 -2
  287. package/dist/shared/components/FileSys.js +0 -113
  288. package/dist/shared/components/HashAccumulator.d.ts +0 -55
  289. package/dist/shared/components/HashAccumulator.js +0 -100
  290. package/dist/shared/components/ZipCrypto.d.ts +0 -3
  291. package/dist/shared/components/ZipCrypto.js +0 -78
  292. package/dist/shared/components/merkleTree.d.ts +0 -66
  293. package/dist/shared/components/merkleTree.js +0 -136
  294. package/dist/shared/types/index.d.ts +0 -21
  295. package/dist/shared/types/index.js +0 -3
  296. package/dist/shared/types.d.ts +0 -33
  297. package/dist/shared/types.js +0 -8
  298. package/dist/shared/version.js +0 -7
  299. package/src/browser/CertificateGeneratorBrowser.ts +0 -498
  300. package/src/browser/ZipKitStampBrowser.ts +0 -9
  301. package/src/browser-index.ts +0 -36
  302. package/src/server/blockchain/CertificateToken.ts +0 -444
  303. package/src/server/blockchain/NFTMinter.ts +0 -357
  304. package/src/server/blockchain/TokenQuerier.ts +0 -287
  305. package/src/server/blockchain/TokenVerifier.ts +0 -453
  306. package/src/server/blockchain/WalletAnalyzer.ts +0 -397
  307. package/src/server/blockchain/WalletFormatter.ts +0 -206
  308. package/src/server/blockchain/WalletManager.ts +0 -294
  309. package/src/server/blockchain/ZipMetadata.ts +0 -117
  310. package/src/server/blockchain/ZipTokenProcessor.ts +0 -234
  311. package/src/server/blockchain/constants.ts +0 -969
  312. package/src/server/blockchain/index.ts +0 -42
  313. package/src/server/blockchain/test-certificate.ts +0 -137
  314. package/src/server/blockchain/types.ts +0 -134
  315. package/src/server/platform/server/ZipKitServer.ts +0 -459
  316. package/src/server/platform/servercomponents/ZipKitOTS.ts +0 -313
  317. package/src/server/platform/servercomponents/opentimestamps.d.ts +0 -23
  318. package/src/shared/ZipKit.ts +0 -899
  319. package/src/shared/components/CertificateOTS.ts +0 -132
  320. package/src/shared/components/FileSys.ts +0 -87
  321. package/src/shared/components/HashAccumulator.ts +0 -113
  322. package/src/shared/components/ZipCrypto.ts +0 -91
  323. package/src/shared/components/merkleTree.ts +0 -162
  324. package/src/shared/types/index.ts +0 -25
  325. package/src/shared/types/modules.d.ts +0 -22
  326. package/src/shared/types/opentimestamps.d.ts +0 -23
  327. package/src/shared/types.d.ts +0 -8
  328. package/src/shared/types.ts +0 -43
  329. package/src/shared/version.ts +0 -4
  330. /package/src/{shared → core}/components/Support.ts +0 -0
@@ -0,0 +1,384 @@
1
+ // ======================================
2
+ // HashCalculator.ts - Unified Hash Component
3
+ // Combines StreamHashCalculator, HashAccumulator, and MerkleTree functionality
4
+ // ======================================
5
+
6
+ import * as crypto from 'crypto';
7
+ import { crc32update } from '../encryption/ZipCrypto';
8
+
9
+ /**
10
+ * Configuration options for Merkle tree construction
11
+ */
12
+ interface MerkleTreeOptions {
13
+ hashLeaves: boolean; // Whether to hash the leaf nodes before adding to tree
14
+ sortLeaves: boolean; // Whether to sort leaf nodes for consistent trees
15
+ sortPairs: boolean; // Whether to sort each pair before hashing
16
+ duplicateOdd: boolean; // Whether to duplicate last leaf when odd number of leaves
17
+ }
18
+
19
+ /**
20
+ * Unified hash calculator supporting:
21
+ * - Incremental CRC-32 and SHA-256 calculation from raw data chunks
22
+ * - Accumulation of pre-computed SHA-256 hashes with XOR and Merkle tree operations
23
+ * - Merkle tree construction, proof generation, and verification
24
+ *
25
+ * Usage examples:
26
+ *
27
+ * Incremental hash calculation:
28
+ * ```typescript
29
+ * const calculator = new HashCalculator({ useSHA256: true });
30
+ * calculator.update(dataChunk);
31
+ * const crc32 = calculator.finalizeCRC32();
32
+ * const sha256 = calculator.finalizeSHA256();
33
+ * ```
34
+ *
35
+ * Hash accumulation:
36
+ * ```typescript
37
+ * const calculator = new HashCalculator({ enableAccumulation: true });
38
+ * calculator.addHash(sha256Hash1);
39
+ * calculator.addHash(sha256Hash2);
40
+ * const xor = calculator.xorHash();
41
+ * const merkle = calculator.merkleRoot();
42
+ * ```
43
+ */
44
+ export class HashCalculator {
45
+ // Incremental hash calculation state (from StreamHashCalculator)
46
+ private crc32State: number = ~0;
47
+ private sha256Hash: crypto.Hash | null = null;
48
+ private useSHA256: boolean = false;
49
+
50
+ // Hash accumulation state (from HashAccumulator)
51
+ private hashes: Buffer[] = [];
52
+ private xorResult: Buffer = Buffer.alloc(32, 0);
53
+ private enableAccumulation: boolean = false;
54
+
55
+ // Merkle tree state (from MerkleTree)
56
+ private merkleLeaves: Buffer[] = [];
57
+ private merkleLayers: Buffer[][] = [];
58
+ private merkleOptions: MerkleTreeOptions = {
59
+ hashLeaves: false,
60
+ sortLeaves: true,
61
+ sortPairs: true,
62
+ duplicateOdd: true
63
+ };
64
+
65
+ /**
66
+ * Creates a new HashCalculator instance
67
+ * @param options - Configuration options:
68
+ * - useSHA256: Enable SHA-256 calculation for incremental mode (default: false)
69
+ * - enableAccumulation: Enable hash accumulation mode (default: false)
70
+ */
71
+ constructor(options?: {
72
+ useSHA256?: boolean;
73
+ enableAccumulation?: boolean;
74
+ }) {
75
+ this.useSHA256 = options?.useSHA256 || false;
76
+ this.enableAccumulation = options?.enableAccumulation || false;
77
+
78
+ if (this.useSHA256) {
79
+ this.sha256Hash = crypto.createHash('sha256');
80
+ }
81
+ }
82
+
83
+ // ============================================================================
84
+ // Incremental Hash Calculation Methods (from StreamHashCalculator)
85
+ // ============================================================================
86
+
87
+ /**
88
+ * Update hash state with a new chunk of data
89
+ * Updates both CRC-32 and SHA-256 (if enabled) incrementally
90
+ * @param chunk - Data chunk to process
91
+ */
92
+ update(chunk: Buffer): void {
93
+ // Update CRC-32 incrementally using existing crc32update function
94
+ for (let i = 0; i < chunk.length; i++) {
95
+ this.crc32State = crc32update(this.crc32State, chunk[i]);
96
+ }
97
+
98
+ // Update SHA-256 incrementally
99
+ if (this.sha256Hash) {
100
+ this.sha256Hash.update(chunk);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Get final CRC-32 value
106
+ * @returns Final CRC-32 value as unsigned 32-bit integer
107
+ */
108
+ finalizeCRC32(): number {
109
+ return ~this.crc32State >>> 0; // Finalize with ~0 like the existing crc32 function
110
+ }
111
+
112
+ /**
113
+ * Get final SHA-256 hash as hex string
114
+ * @returns SHA-256 hash as hex string, or null if SHA-256 not enabled
115
+ */
116
+ finalizeSHA256(): string | null {
117
+ if (this.sha256Hash) {
118
+ return this.sha256Hash.digest('hex');
119
+ }
120
+ return null;
121
+ }
122
+
123
+ /**
124
+ * Reset the incremental hash calculation state
125
+ */
126
+ reset(): void {
127
+ this.crc32State = ~0;
128
+ if (this.sha256Hash) {
129
+ this.sha256Hash = crypto.createHash('sha256');
130
+ }
131
+ }
132
+
133
+ // ============================================================================
134
+ // Hash Accumulation Methods (from HashAccumulator)
135
+ // ============================================================================
136
+
137
+ /**
138
+ * Adds a pre-computed SHA-256 hash to both the XOR accumulation and hash array
139
+ * @param hash - Hash value as hex string or Buffer (must be 32 bytes for SHA-256)
140
+ */
141
+ addHash(hash: string | Buffer): void {
142
+ if (!this.enableAccumulation) {
143
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
144
+ }
145
+
146
+ // Convert hash to Buffer if it's a string
147
+ const hashBuffer = typeof hash === 'string'
148
+ ? Buffer.from(hash, 'hex')
149
+ : hash;
150
+
151
+ // Add to array for Merkle tree
152
+ this.hashes.push(hashBuffer);
153
+ this.merkleLeaves.push(hashBuffer);
154
+
155
+ // XOR accumulation
156
+ for (let i = 0; i < 32; i++) {
157
+ this.xorResult[i] ^= hashBuffer[i];
158
+ }
159
+
160
+ // Rebuild Merkle tree when hash is added
161
+ this.rebuildMerkleTree();
162
+ }
163
+
164
+ /**
165
+ * Gets the accumulated XOR of all added hashes
166
+ * @returns Hex string of XOR result
167
+ */
168
+ xorHash(): string {
169
+ if (!this.enableAccumulation) {
170
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
171
+ }
172
+ return this.xorResult.toString('hex');
173
+ }
174
+
175
+ /**
176
+ * Creates a Merkle tree from accumulated hashes and returns the root
177
+ * @returns Hex string of Merkle root, or null if no hashes added
178
+ */
179
+ merkleRoot(): string | null {
180
+ if (!this.enableAccumulation) {
181
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
182
+ }
183
+
184
+ if (this.merkleLeaves.length === 0) {
185
+ return null;
186
+ }
187
+
188
+ // If Merkle tree not built yet, build it
189
+ if (this.merkleLayers.length === 0) {
190
+ this.rebuildMerkleTree();
191
+ }
192
+
193
+ const root = this.merkleLayers[this.merkleLayers.length - 1];
194
+ if (root && root.length > 0) {
195
+ return root[0].toString('hex');
196
+ }
197
+
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * Gets the number of hashes accumulated
203
+ * @returns Number of accumulated hashes
204
+ */
205
+ leafCount(): number {
206
+ if (!this.enableAccumulation) {
207
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
208
+ }
209
+ return this.hashes.length;
210
+ }
211
+
212
+ /**
213
+ * Clears the accumulated hashes and resets XOR buffer
214
+ */
215
+ clear(): void {
216
+ if (!this.enableAccumulation) {
217
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
218
+ }
219
+ this.hashes = [];
220
+ this.merkleLeaves = [];
221
+ this.merkleLayers = [];
222
+ this.xorResult = Buffer.alloc(32, 0);
223
+ }
224
+
225
+ /**
226
+ * Combines multiple hash results into a single Merkle root
227
+ * Static method for combining results from multiple HashCalculator instances
228
+ * @param results - Array of objects containing merkleRoot properties
229
+ * @returns Combined Merkle root as hex string, or null if no valid roots
230
+ */
231
+ static combineResults(results: { merkleRoot?: string }[]): string | null {
232
+ const calculator = new HashCalculator({ enableAccumulation: true });
233
+
234
+ // Combine all hashes
235
+ for (const result of results) {
236
+ if (result.merkleRoot) {
237
+ calculator.addHash(result.merkleRoot);
238
+ }
239
+ }
240
+
241
+ return calculator.merkleRoot();
242
+ }
243
+
244
+ // ============================================================================
245
+ // Merkle Tree Methods (from MerkleTree)
246
+ // ============================================================================
247
+
248
+ /**
249
+ * Computes SHA-256 hash of input data
250
+ * @param data - Data to hash
251
+ * @returns Buffer containing hash
252
+ */
253
+ private hash(data: Buffer): Buffer {
254
+ return crypto.createHash('sha256').update(data).digest();
255
+ }
256
+
257
+ /**
258
+ * Combines two child hashes to create parent hash
259
+ * @param left - Left child hash
260
+ * @param right - Right child hash
261
+ * @returns Combined hash of children
262
+ */
263
+ private combinedHash(left: Buffer, right: Buffer): Buffer {
264
+ if (this.merkleOptions.sortPairs && Buffer.compare(left, right) > 0) {
265
+ [left, right] = [right, left];
266
+ }
267
+ return this.hash(Buffer.concat([left, right]));
268
+ }
269
+
270
+ /**
271
+ * Builds the Merkle tree by creating successive layers of hashes
272
+ * @param nodes - Array of nodes in current layer
273
+ */
274
+ private createHashes(nodes: Buffer[]): void {
275
+ while (nodes.length > 1) {
276
+ const layerIndex = this.merkleLayers.length;
277
+ this.merkleLayers.push([]);
278
+
279
+ // Process pairs of nodes
280
+ for (let i = 0; i < nodes.length - 1; i += 2) {
281
+ const left = nodes[i];
282
+ const right = nodes[i + 1];
283
+ const hash = this.combinedHash(left, right);
284
+ this.merkleLayers[layerIndex].push(hash);
285
+ }
286
+
287
+ // Handle odd number of nodes
288
+ if (nodes.length % 2 === 1) {
289
+ const last = nodes[nodes.length - 1];
290
+ if (this.merkleOptions.duplicateOdd) {
291
+ // Duplicate the last node if odd
292
+ const hash = this.combinedHash(last, last);
293
+ this.merkleLayers[layerIndex].push(hash);
294
+ } else {
295
+ // Push last node up to next layer
296
+ this.merkleLayers[layerIndex].push(last);
297
+ }
298
+ }
299
+
300
+ nodes = this.merkleLayers[layerIndex];
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Rebuilds the Merkle tree from current leaves
306
+ */
307
+ private rebuildMerkleTree(): void {
308
+ if (this.merkleLeaves.length === 0) {
309
+ this.merkleLayers = [];
310
+ return;
311
+ }
312
+
313
+ // Process leaves according to options
314
+ const processedLeaves = this.merkleLeaves.map(leaf => {
315
+ if (this.merkleOptions.hashLeaves) {
316
+ return this.hash(leaf);
317
+ }
318
+ return Buffer.isBuffer(leaf) ? leaf : Buffer.from(leaf);
319
+ });
320
+
321
+ if (this.merkleOptions.sortLeaves) {
322
+ processedLeaves.sort(Buffer.compare);
323
+ }
324
+
325
+ this.merkleLayers = [processedLeaves];
326
+ this.createHashes(processedLeaves);
327
+ }
328
+
329
+ /**
330
+ * Generates a proof of inclusion for a leaf node
331
+ * @param leaf - The leaf node to generate proof for
332
+ * @returns Array of sibling hashes needed to reconstruct root
333
+ * @throws Error if leaf not found in tree or accumulation not enabled
334
+ */
335
+ getProof(leaf: Buffer): Buffer[] {
336
+ if (!this.enableAccumulation) {
337
+ throw new Error('Hash accumulation not enabled. Set enableAccumulation: true in constructor.');
338
+ }
339
+
340
+ if (this.merkleLayers.length === 0) {
341
+ this.rebuildMerkleTree();
342
+ }
343
+
344
+ let index = this.merkleLeaves.findIndex(item => item.equals(leaf));
345
+ if (index === -1) {
346
+ throw new Error('Leaf not found in tree');
347
+ }
348
+
349
+ return this.merkleLayers.reduce((proof, layer) => {
350
+ if (layer.length === 1) return proof;
351
+
352
+ const pairIndex = index % 2 === 0 ? index + 1 : index - 1;
353
+ if (pairIndex < layer.length) {
354
+ proof.push(layer[pairIndex]);
355
+ }
356
+
357
+ index = Math.floor(index / 2);
358
+ return proof;
359
+ }, [] as Buffer[]);
360
+ }
361
+
362
+ /**
363
+ * Verifies a proof of inclusion for a leaf node
364
+ * @param proof - Array of sibling hashes from getProof()
365
+ * @param targetHash - Hash of the leaf node being verified
366
+ * @param root - Expected root hash
367
+ * @returns boolean indicating if proof is valid
368
+ */
369
+ verify(proof: Buffer[], targetHash: Buffer, root: Buffer): boolean {
370
+ let computedHash = targetHash;
371
+
372
+ for (const proofElement of proof) {
373
+ computedHash = Buffer.compare(computedHash, proofElement) <= 0
374
+ ? this.combinedHash(computedHash, proofElement)
375
+ : this.combinedHash(proofElement, computedHash);
376
+ }
377
+
378
+ return computedHash.equals(root);
379
+ }
380
+ }
381
+
382
+ // Default export
383
+ export default HashCalculator;
384
+
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Global Logger Utility for NeoZipKit
3
+ * Provides centralized console control with configurable log levels
4
+ */
5
+
6
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
7
+
8
+ export interface LoggerConfig {
9
+ enabled: boolean;
10
+ level: LogLevel;
11
+ }
12
+
13
+ /**
14
+ * Global Logger class for controlling console output throughout NeoZipKit
15
+ */
16
+ export class Logger {
17
+ private static config: LoggerConfig = {
18
+ enabled: true,
19
+ level: 'info'
20
+ };
21
+
22
+ private static originalConsole = {
23
+ log: console.log,
24
+ error: console.error,
25
+ warn: console.warn,
26
+ debug: console.debug,
27
+ info: console.info
28
+ };
29
+
30
+ /**
31
+ * Configure the logger
32
+ */
33
+ static configure(config: Partial<LoggerConfig>): void {
34
+ this.config = { ...this.config, ...config };
35
+ }
36
+
37
+ /**
38
+ * Get current logger configuration
39
+ */
40
+ static getConfig(): LoggerConfig {
41
+ return { ...this.config };
42
+ }
43
+
44
+ /**
45
+ * Enable logging
46
+ */
47
+ static enable(): void {
48
+ this.config.enabled = true;
49
+ }
50
+
51
+ /**
52
+ * Disable all logging
53
+ */
54
+ static disable(): void {
55
+ this.config.enabled = false;
56
+ }
57
+
58
+ /**
59
+ * Set log level
60
+ */
61
+ static setLevel(level: LogLevel): void {
62
+ this.config.level = level;
63
+ }
64
+
65
+
66
+ /**
67
+ * Check if a log level should be output
68
+ */
69
+ private static shouldLog(level: LogLevel): boolean {
70
+ if (!this.config.enabled) return false;
71
+
72
+ const levels: LogLevel[] = ['debug', 'info', 'warn', 'error', 'silent'];
73
+ const currentLevelIndex = levels.indexOf(this.config.level);
74
+ const requestedLevelIndex = levels.indexOf(level);
75
+
76
+ return requestedLevelIndex >= currentLevelIndex;
77
+ }
78
+
79
+ /**
80
+ * Log a message
81
+ */
82
+ static log(...args: any[]): void {
83
+ if (this.shouldLog('info')) {
84
+ this.originalConsole.log(...args);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Log an error message
90
+ */
91
+ static error(...args: any[]): void {
92
+ if (this.shouldLog('error')) {
93
+ this.originalConsole.error(...args);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Log a warning message
99
+ */
100
+ static warn(...args: any[]): void {
101
+ if (this.shouldLog('warn')) {
102
+ this.originalConsole.warn(...args);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Log a debug message
108
+ */
109
+ static debug(...args: any[]): void {
110
+ if (this.shouldLog('debug')) {
111
+ // Use console.log for debug messages to ensure they're visible
112
+ this.originalConsole.log(...args);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Log an info message
118
+ */
119
+ static info(...args: any[]): void {
120
+ if (this.shouldLog('info')) {
121
+ this.originalConsole.info(...args);
122
+ }
123
+ }
124
+
125
+
126
+ /**
127
+ * Override console methods globally (use with caution)
128
+ */
129
+ static overrideConsole(): void {
130
+ console.log = (...args: any[]) => this.log(...args);
131
+ console.error = (...args: any[]) => this.error(...args);
132
+ console.warn = (...args: any[]) => this.warn(...args);
133
+ console.debug = (...args: any[]) => this.debug(...args);
134
+ console.info = (...args: any[]) => this.info(...args);
135
+ }
136
+
137
+ /**
138
+ * Restore original console methods
139
+ */
140
+ static restoreConsole(): void {
141
+ console.log = this.originalConsole.log;
142
+ console.error = this.originalConsole.error;
143
+ console.warn = this.originalConsole.warn;
144
+ console.debug = this.originalConsole.debug;
145
+ console.info = this.originalConsole.info;
146
+ }
147
+
148
+ }
149
+
150
+ /**
151
+ * Environment-based configuration
152
+ */
153
+ export function configureLoggerFromEnvironment(): void {
154
+ const env = typeof process !== 'undefined' ? process.env : {};
155
+
156
+ // Check for NEOZIP_DEBUG environment variable
157
+ if (env.NEOZIP_DEBUG === 'false') {
158
+ Logger.disable();
159
+ } else if (env.NEOZIP_DEBUG === 'true') {
160
+ Logger.enable();
161
+ Logger.setLevel('debug');
162
+ }
163
+
164
+ // Check for NEOZIP_LOG_LEVEL
165
+ if (env.NEOZIP_LOG_LEVEL) {
166
+ const level = env.NEOZIP_LOG_LEVEL as LogLevel;
167
+ if (['debug', 'info', 'warn', 'error', 'silent'].includes(level)) {
168
+ Logger.setLevel(level);
169
+ }
170
+ }
171
+
172
+ // Check for NODE_ENV
173
+ if (env.NODE_ENV === 'production') {
174
+ Logger.setLevel('error');
175
+ }
176
+ }
177
+
178
+ // Auto-configure from environment on import
179
+ // Only run in Node.js environment
180
+ configureLoggerFromEnvironment();
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Progress tracker for streaming operations
3
+ * Provides real-time progress updates and ETA calculations
4
+ */
5
+ export class ProgressTracker {
6
+ private startTime: number;
7
+ private lastUpdateTime: number;
8
+ private totalBytes: number;
9
+ private processedBytes: number;
10
+ private fileName: string;
11
+ private lastReportedPercent: number = -1;
12
+
13
+ constructor(fileName: string, totalBytes: number) {
14
+ this.fileName = fileName;
15
+ this.totalBytes = totalBytes;
16
+ this.processedBytes = 0;
17
+ this.startTime = Date.now();
18
+ this.lastUpdateTime = this.startTime;
19
+ }
20
+
21
+ /**
22
+ * Update progress with bytes processed
23
+ * @param bytesProcessed - Number of bytes processed in this update
24
+ */
25
+ update(bytesProcessed: number): void {
26
+ this.processedBytes += bytesProcessed;
27
+ this.reportProgress();
28
+ }
29
+
30
+ /**
31
+ * Set total bytes (useful when file size changes)
32
+ */
33
+ setTotalBytes(totalBytes: number): void {
34
+ this.totalBytes = totalBytes;
35
+ }
36
+
37
+ /**
38
+ * Report progress if enough time has passed or significant progress made
39
+ */
40
+ private reportProgress(): void {
41
+ const now = Date.now();
42
+ const percent = Math.floor((this.processedBytes / this.totalBytes) * 100);
43
+
44
+ // Report if:
45
+ // 1. 1% or more progress made, OR
46
+ // 2. 500ms have passed since last report
47
+ const shouldReport =
48
+ percent > this.lastReportedPercent ||
49
+ (now - this.lastUpdateTime) > 500;
50
+
51
+ if (shouldReport) {
52
+ this.lastReportedPercent = percent;
53
+ this.lastUpdateTime = now;
54
+ this.printProgress();
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Print progress information
60
+ */
61
+ private printProgress(): void {
62
+ const elapsed = (Date.now() - this.startTime) / 1000;
63
+ const rate = this.processedBytes / elapsed;
64
+ const eta = this.totalBytes > this.processedBytes
65
+ ? (this.totalBytes - this.processedBytes) / rate
66
+ : 0;
67
+ const percent = Math.floor((this.processedBytes / this.totalBytes) * 100);
68
+
69
+ const formatBytes = (bytes: number): string => {
70
+ const units = ['B', 'KB', 'MB', 'GB'];
71
+ let size = bytes;
72
+ let unitIndex = 0;
73
+
74
+ while (size >= 1024 && unitIndex < units.length - 1) {
75
+ size /= 1024;
76
+ unitIndex++;
77
+ }
78
+
79
+ return `${size.toFixed(1)}${units[unitIndex]}`;
80
+ };
81
+
82
+ const formatTime = (seconds: number): string => {
83
+ if (seconds < 60) return `${seconds.toFixed(0)}s`;
84
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${(seconds % 60).toFixed(0)}s`;
85
+ return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
86
+ };
87
+
88
+ process.stdout.write(
89
+ `\r${this.fileName}: ${percent}% (${formatBytes(this.processedBytes)}/${formatBytes(this.totalBytes)}) ` +
90
+ `[${formatBytes(rate)}/s] ETA: ${formatTime(eta)}`
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Complete progress tracking
96
+ */
97
+ complete(): void {
98
+ const elapsed = (Date.now() - this.startTime) / 1000;
99
+ const rate = this.processedBytes / elapsed;
100
+
101
+ const formatBytes = (bytes: number): string => {
102
+ const units = ['B', 'KB', 'MB', 'GB'];
103
+ let size = bytes;
104
+ let unitIndex = 0;
105
+
106
+ while (size >= 1024 && unitIndex < units.length - 1) {
107
+ size /= 1024;
108
+ unitIndex++;
109
+ }
110
+
111
+ return `${size.toFixed(1)}${units[unitIndex]}`;
112
+ };
113
+
114
+ console.log(
115
+ `\r${this.fileName}: 100% (${formatBytes(this.processedBytes)}) ` +
116
+ `[${formatBytes(rate)}/s] completed in ${elapsed.toFixed(1)}s`
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Get current progress percentage
122
+ */
123
+ getProgressPercent(): number {
124
+ return Math.floor((this.processedBytes / this.totalBytes) * 100);
125
+ }
126
+
127
+ /**
128
+ * Get processing rate in bytes per second
129
+ */
130
+ getProcessingRate(): number {
131
+ const elapsed = (Date.now() - this.startTime) / 1000;
132
+ return this.processedBytes / elapsed;
133
+ }
134
+ }