neozipkit 0.1.1 → 0.2.1

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 (115) hide show
  1. package/README.md +52 -105
  2. package/contracts/INTEGRATION.md +338 -0
  3. package/contracts/NETWORKS.md +156 -0
  4. package/contracts/README.md +152 -0
  5. package/{src/server/blockchain → contracts}/constants.ts +5 -22
  6. package/contracts/deploy-bytecode.mjs +94 -0
  7. package/dist/blockchain/ZipKitMinter.d.ts +106 -0
  8. package/dist/blockchain/ZipKitMinter.js +347 -0
  9. package/dist/blockchain/ZipKitNFT.d.ts +3 -0
  10. package/dist/blockchain/ZipKitNFT.js +7 -0
  11. package/dist/blockchain/ZipKitOTS.d.ts +135 -0
  12. package/dist/blockchain/ZipKitOTS.js +564 -0
  13. package/dist/blockchain/ZipKitVerifier.d.ts +69 -0
  14. package/dist/blockchain/ZipKitVerifier.js +289 -0
  15. package/dist/{server/blockchain/WalletAnalyzer.d.ts → blockchain/ZipKitWallet.d.ts} +31 -43
  16. package/dist/{server/blockchain/WalletAnalyzer.js → blockchain/ZipKitWallet.js} +193 -161
  17. package/dist/blockchain/contracts.d.ts +14 -0
  18. package/dist/blockchain/contracts.js +77 -0
  19. package/dist/blockchain/index.d.ts +7 -0
  20. package/dist/blockchain/index.js +50 -0
  21. package/dist/{server/blockchain → blockchain}/types.d.ts +12 -34
  22. package/dist/{server/blockchain → blockchain}/types.js +1 -22
  23. package/dist/browser-index.d.ts +0 -3
  24. package/dist/browser-index.js +4 -5
  25. package/dist/browser.d.ts +0 -3
  26. package/dist/browser.js +4 -5
  27. package/dist/index.d.ts +8 -15
  28. package/dist/index.js +12 -24
  29. package/dist/server/{platform/server/ZipKitServer.d.ts → ZipKitServer.d.ts} +4 -35
  30. package/dist/server/{platform/server/ZipKitServer.js → ZipKitServer.js} +55 -182
  31. package/dist/shared/ZipEntry.js +1 -1
  32. package/dist/shared/ZipKit.d.ts +0 -6
  33. package/dist/shared/ZipKit.js +1 -18
  34. package/dist/shared/types.js +2 -2
  35. package/dist/shared/version.d.ts +2 -4
  36. package/dist/shared/version.js +4 -5
  37. package/package.json +13 -3
  38. package/src/blockchain/README.md +229 -0
  39. package/src/blockchain/ZipKitMinter.ts +470 -0
  40. package/src/blockchain/ZipKitNFT.ts +12 -0
  41. package/src/blockchain/ZipKitOTS.ts +622 -0
  42. package/src/blockchain/ZipKitVerifier.ts +382 -0
  43. package/src/blockchain/ZipKitWallet.ts +338 -0
  44. package/src/blockchain/contracts.ts +88 -0
  45. package/src/blockchain/index.ts +61 -0
  46. package/src/blockchain/types.ts +91 -0
  47. package/src/browser/{TokenVerifierBrowser.ts → TokenVerifierBrowser.ts-remove} +1 -1
  48. package/src/browser-index.ts +3 -3
  49. package/src/index.ts +10 -17
  50. package/src/server/README.md +25 -0
  51. package/src/server/ZipKitServer.ts +305 -0
  52. package/src/shared/ZipEntry.ts +1 -1
  53. package/src/shared/ZipKit.ts +1 -19
  54. package/src/shared/types.ts +3 -3
  55. package/src/shared/version.ts +3 -4
  56. package/src/types/modules.d.ts +11 -1
  57. package/contracts/Lock.sol +0 -34
  58. package/contracts/compile-contract.js +0 -168
  59. package/contracts/deploy/deploy-both-contracts.js +0 -286
  60. package/contracts/deploy/deploy-enhanced-contract.js +0 -197
  61. package/contracts/deploy/deploy-private-contract.js +0 -190
  62. package/contracts/deploy/deploy-public-clean.js +0 -1063
  63. package/contracts/deploy/deploy-public-contract.js +0 -1107
  64. package/contracts/deployment.config.example.js +0 -25
  65. package/contracts/remix-compile.js +0 -222
  66. package/contracts/setup-deployment.js +0 -51
  67. package/contracts/src/ZipFileNFT-DEPRECATED-6field.sol +0 -260
  68. package/contracts/src/ZipFileNFT-DEPRECATED-Enhanced.sol +0 -289
  69. package/dist/browser/CertificateGeneratorBrowser.d.ts +0 -75
  70. package/dist/browser/CertificateGeneratorBrowser.js +0 -433
  71. package/dist/browser/TokenVerifierBrowser.d.ts +0 -76
  72. package/dist/browser/TokenVerifierBrowser.js +0 -299
  73. package/dist/server/blockchain/NFTMinter.d.ts +0 -41
  74. package/dist/server/blockchain/NFTMinter.js +0 -323
  75. package/dist/server/blockchain/TokenQuerier.d.ts +0 -31
  76. package/dist/server/blockchain/TokenQuerier.js +0 -259
  77. package/dist/server/blockchain/TokenVerifier.d.ts +0 -20
  78. package/dist/server/blockchain/TokenVerifier.js +0 -395
  79. package/dist/server/blockchain/WalletFormatter.d.ts +0 -39
  80. package/dist/server/blockchain/WalletFormatter.js +0 -196
  81. package/dist/server/blockchain/WalletManager.d.ts +0 -46
  82. package/dist/server/blockchain/WalletManager.js +0 -294
  83. package/dist/server/blockchain/ZipMetadata.d.ts +0 -27
  84. package/dist/server/blockchain/ZipMetadata.js +0 -131
  85. package/dist/server/blockchain/ZipTokenProcessor.d.ts +0 -44
  86. package/dist/server/blockchain/ZipTokenProcessor.js +0 -204
  87. package/dist/server/blockchain/constants.d.ts +0 -102
  88. package/dist/server/blockchain/constants.js +0 -968
  89. package/dist/server/blockchain/index.d.ts +0 -9
  90. package/dist/server/blockchain/index.js +0 -44
  91. package/dist/server/blockchain/test-certificate.d.ts +0 -8
  92. package/dist/server/blockchain/test-certificate.js +0 -100
  93. package/dist/server/platform/servercomponents/ZipKitOTS.d.ts +0 -91
  94. package/dist/server/platform/servercomponents/ZipKitOTS.js +0 -271
  95. package/examples/unzip-token.ts +0 -488
  96. package/examples/zip-token.ts +0 -604
  97. package/src/server/blockchain/NFTMinter.ts +0 -357
  98. package/src/server/blockchain/TokenQuerier.ts +0 -287
  99. package/src/server/blockchain/TokenVerifier.ts +0 -453
  100. package/src/server/blockchain/WalletAnalyzer.ts +0 -397
  101. package/src/server/blockchain/WalletFormatter.ts +0 -206
  102. package/src/server/blockchain/WalletManager.ts +0 -294
  103. package/src/server/blockchain/ZipMetadata.ts +0 -117
  104. package/src/server/blockchain/ZipTokenProcessor.ts +0 -234
  105. package/src/server/blockchain/index.ts +0 -42
  106. package/src/server/blockchain/test-certificate.ts +0 -137
  107. package/src/server/blockchain/types.ts +0 -134
  108. package/src/server/platform/server/ZipKitServer.ts +0 -459
  109. package/src/server/platform/servercomponents/ZipKitOTS.ts +0 -313
  110. package/src/server/platform/servercomponents/opentimestamps.d.ts +0 -23
  111. /package/contracts/{bytecode.txt → NZIP-NFT-bytecode.txt} +0 -0
  112. /package/dist/{server/blockchain → blockchain}/CertificateToken.d.ts +0 -0
  113. /package/dist/{server/blockchain → blockchain}/CertificateToken.js +0 -0
  114. /package/src/{server/blockchain → blockchain}/CertificateToken.ts +0 -0
  115. /package/src/browser/{CertificateGeneratorBrowser.ts → CertificateGeneratorBrowser.ts-remove} +0 -0
@@ -1,9 +0,0 @@
1
- export * from './types';
2
- export { WalletManager } from './WalletManager';
3
- export { NFTMinter } from './NFTMinter';
4
- export { ZipTokenProcessor } from './ZipTokenProcessor';
5
- export { ZipMetadata } from './ZipMetadata';
6
- export { checkForTokenization, TokenVerificationOptions, TokenVerificationResult } from './TokenVerifier';
7
- export { queryBlockchainForExistingToken, queryWalletTokens, ExistingTokenInfo, TokenQueryOptions } from './TokenQuerier';
8
- export { WalletAnalyzer, TokenInfo, NZipTokenDetails, WalletBasicInfo, TokenScanResult, CommonTokenConfig } from './WalletAnalyzer';
9
- export { WalletFormatter } from './WalletFormatter';
@@ -1,44 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.WalletFormatter = exports.WalletAnalyzer = exports.queryWalletTokens = exports.queryBlockchainForExistingToken = exports.checkForTokenization = exports.ZipMetadata = exports.ZipTokenProcessor = exports.NFTMinter = exports.WalletManager = void 0;
18
- // Export all types
19
- __exportStar(require("./types"), exports);
20
- // Export wallet management
21
- var WalletManager_1 = require("./WalletManager");
22
- Object.defineProperty(exports, "WalletManager", { enumerable: true, get: function () { return WalletManager_1.WalletManager; } });
23
- // Export NFT minting
24
- var NFTMinter_1 = require("./NFTMinter");
25
- Object.defineProperty(exports, "NFTMinter", { enumerable: true, get: function () { return NFTMinter_1.NFTMinter; } });
26
- // Export main processor
27
- var ZipTokenProcessor_1 = require("./ZipTokenProcessor");
28
- Object.defineProperty(exports, "ZipTokenProcessor", { enumerable: true, get: function () { return ZipTokenProcessor_1.ZipTokenProcessor; } });
29
- // Export ZIP metadata utilities
30
- var ZipMetadata_1 = require("./ZipMetadata");
31
- Object.defineProperty(exports, "ZipMetadata", { enumerable: true, get: function () { return ZipMetadata_1.ZipMetadata; } });
32
- // Export token verification utilities
33
- var TokenVerifier_1 = require("./TokenVerifier");
34
- Object.defineProperty(exports, "checkForTokenization", { enumerable: true, get: function () { return TokenVerifier_1.checkForTokenization; } });
35
- // Export token querying utilities
36
- var TokenQuerier_1 = require("./TokenQuerier");
37
- Object.defineProperty(exports, "queryBlockchainForExistingToken", { enumerable: true, get: function () { return TokenQuerier_1.queryBlockchainForExistingToken; } });
38
- Object.defineProperty(exports, "queryWalletTokens", { enumerable: true, get: function () { return TokenQuerier_1.queryWalletTokens; } });
39
- // Export wallet analysis utilities
40
- var WalletAnalyzer_1 = require("./WalletAnalyzer");
41
- Object.defineProperty(exports, "WalletAnalyzer", { enumerable: true, get: function () { return WalletAnalyzer_1.WalletAnalyzer; } });
42
- // Export wallet formatting utilities
43
- var WalletFormatter_1 = require("./WalletFormatter");
44
- Object.defineProperty(exports, "WalletFormatter", { enumerable: true, get: function () { return WalletFormatter_1.WalletFormatter; } });
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Test/Demo script for CertificateToken functionality
4
- *
5
- * This demonstrates how to generate certificates for tokenized ZIP files
6
- * independently of the neozipkit integration.
7
- */
8
- export {};
@@ -1,100 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * Test/Demo script for CertificateToken functionality
5
- *
6
- * This demonstrates how to generate certificates for tokenized ZIP files
7
- * independently of the neozipkit integration.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- const CertificateToken_1 = require("./CertificateToken");
11
- const constants_1 = require("./constants");
12
- // Example token information
13
- const sampleTokenInfo = {
14
- tokenId: "10",
15
- contractAddress: constants_1.CURRENT_DEPLOYMENT.address, // NZIP NFT Contract v2.0
16
- network: "Base Sepolia",
17
- transactionHash: "0x403331e67051b70c92af413ad9424e70f4e4cacb5512a2f6e6af46a6cb198340",
18
- wallet: "0x1234567890123456789012345678901234567890",
19
- timestamp: Math.floor(Date.now() / 1000),
20
- note: "Test tokenized ZIP file for demonstration"
21
- };
22
- // Example blockchain verification results
23
- const sampleVerification = {
24
- merkleRootMatches: true,
25
- blockchainMerkleRoot: "abc123def456789012345678901234567890123456789012345678901234567890",
26
- calculatedMerkleRoot: "abc123def456789012345678901234567890123456789012345678901234567890",
27
- verificationStatus: 'PASSED',
28
- verificationTime: Math.floor(Date.now() / 1000),
29
- blockNumber: 12345678
30
- };
31
- // Example wallet information
32
- const sampleWalletInfo = {
33
- address: "0x1234567890123456789012345678901234567890",
34
- network: "Base Sepolia",
35
- balance: "1.234 ETH",
36
- ensName: "demo.eth"
37
- };
38
- // Example file information
39
- const sampleFiles = [
40
- {
41
- filename: "README.md",
42
- size: 1024,
43
- date: "2025-01-10 12:00:00 UTC",
44
- hash: "a1b2c3d4e5f6789012345678901234567890123456789012345678901234567890"
45
- },
46
- {
47
- filename: "document.pdf",
48
- size: 2048576,
49
- date: "2025-01-10 11:30:00 UTC",
50
- hash: "b2c3d4e5f6a7890123456789012345678901234567890123456789012345678901"
51
- },
52
- {
53
- filename: "image.jpg",
54
- size: 512000,
55
- date: "2025-01-10 10:15:00 UTC",
56
- hash: "c3d4e5f6a7b8901234567890123456789012345678901234567890123456789012"
57
- }
58
- ];
59
- function testCertificateGeneration() {
60
- console.log('🧪 Testing Certificate Generation...');
61
- console.log('=====================================');
62
- try {
63
- // Test with full information
64
- console.log('1. Generating certificate with full information...');
65
- const fullCertificate = (0, CertificateToken_1.createTokenCertificate)(sampleTokenInfo, 'test-archive.zip', sampleVerification, sampleWalletInfo, sampleFiles);
66
- const fullCertPath = (0, CertificateToken_1.saveCertificate)('test-archive.zip', fullCertificate, './certificates');
67
- console.log(`✅ Full certificate saved: ${fullCertPath}`);
68
- // Test with minimal information
69
- console.log('\n2. Generating certificate with minimal information...');
70
- const minimalVerification = {
71
- merkleRootMatches: false,
72
- blockchainMerkleRoot: "different123456789012345678901234567890123456789012345678901234567890",
73
- calculatedMerkleRoot: "calculated123456789012345678901234567890123456789012345678901234567890",
74
- verificationStatus: 'FAILED'
75
- };
76
- const minimalCertificate = (0, CertificateToken_1.createTokenCertificate)(sampleTokenInfo, 'minimal-archive.zip', minimalVerification);
77
- const minimalCertPath = (0, CertificateToken_1.saveCertificate)('minimal-archive.zip', minimalCertificate, './blockchain/output');
78
- console.log(`✅ Minimal certificate saved: ${minimalCertPath}`);
79
- // Test with unavailable verification
80
- console.log('\n3. Generating certificate with unavailable verification...');
81
- const unavailableVerification = {
82
- merkleRootMatches: false,
83
- blockchainMerkleRoot: "N/A",
84
- calculatedMerkleRoot: "calculated123456789012345678901234567890123456789012345678901234567890",
85
- verificationStatus: 'UNAVAILABLE'
86
- };
87
- const unavailableCertificate = (0, CertificateToken_1.createTokenCertificate)(sampleTokenInfo, 'unavailable-archive.zip', unavailableVerification, sampleWalletInfo);
88
- const unavailableCertPath = (0, CertificateToken_1.saveCertificate)('unavailable-archive.zip', unavailableCertificate, './blockchain/output');
89
- console.log(`✅ Unavailable verification certificate saved: ${unavailableCertPath}`);
90
- console.log('\n🎉 All certificate tests completed successfully!');
91
- console.log('Check the ./blockchain/output directory for generated certificates.');
92
- }
93
- catch (error) {
94
- console.error('❌ Error during certificate generation:', error);
95
- }
96
- }
97
- // Run the test
98
- if (require.main === module) {
99
- testCertificateGeneration();
100
- }
@@ -1,91 +0,0 @@
1
- declare global {
2
- var _bitcore: any;
3
- }
4
- /**
5
- * ZipKitOTS - OpenTimestamps utilities for NeoZip
6
- *
7
- * This module provides functions for creating and verifying OpenTimestamps
8
- * proofs for ZIP archives and their contents. It includes utilities for timestamp
9
- * creation, verification, and serialization/deserialization.
10
- */
11
- /**
12
- * Interface for timestamp verification results
13
- * Contains all necessary information about a verified timestamp
14
- */
15
- export interface TimestampResult {
16
- merkleRoot: string | null;
17
- ots: ArrayBuffer | null;
18
- verified: boolean;
19
- results: any | null;
20
- error: string | null;
21
- attestations: any | null;
22
- upgradedOts: ArrayBuffer | null;
23
- }
24
- export interface TimestampInfo {
25
- message: string;
26
- results: string[];
27
- attestDate: Date | null;
28
- attestHeight: number | null;
29
- submittedUri: string | null;
30
- otsUpgraded: boolean;
31
- }
32
- /**
33
- * Verifies a timestamp proof against a file hash
34
- *
35
- * @param hashDigest - SHA-256 hash digest of the file or merkle root (hex string)
36
- * @param otsData - The OpenTimestamps proof data
37
- * @returns Promise with verification result or null on critical failure
38
- *
39
- * @example
40
- * // Verify a timestamp proof
41
- * const hashDigest = "8a9d..."; // SHA-256 digest in hex format
42
- * const result = await verifyTimestamp(hashDigest, otsBuffer);
43
- *
44
- * if (result) {
45
- * if (result.error) {
46
- * console.error("Verification failed:", result.error);
47
- * } else {
48
- * console.log("Verification succeeded:", result.verified);
49
- *
50
- * if (result.upgradedOts) {
51
- * // Save the upgraded timestamp
52
- * }
53
- * }
54
- * }
55
- */
56
- export declare function verifyTimestamp(hashDigest: string | null, ots: ArrayBuffer | null): Promise<TimestampResult | {
57
- error: string;
58
- } | null>;
59
- /**
60
- * Creates a timestamp proof for a file hash using OpenTimestamps
61
- *
62
- * @param hashDigest - SHA-256 hash digest of the file or merkle root (hex string)
63
- * @returns Promise containing the OpenTimestamps proof or null on failure
64
- *
65
- * @example
66
- * // Create a timestamp for a file hash
67
- * const hashDigest = "8a9d..."; // SHA-256 digest in hex format
68
- * const timestampProof = await createTimestamp(hashDigest);
69
- *
70
- * if (timestampProof) {
71
- * // Save the timestamp proof to storage
72
- * }
73
- */
74
- export declare function createTimestamp(hashDigest: string | null): Promise<Buffer | null>;
75
- /**
76
- * Result of deserializing an OpenTimestamps proof
77
- */
78
- export interface DeserializeOtsResult {
79
- attestStr: string | null;
80
- needsUpdateMsg: string | null;
81
- attestationValues: any[];
82
- }
83
- /**
84
- * Deserializes timestamp metadata to extract attestation information
85
- * Used for generating timestamp certificates and displaying verification details
86
- *
87
- * @param tsResult - Timestamp verification result to deserialize
88
- * @returns JSON string of deserialized data or null on failure
89
- */
90
- export declare function deserializeOts(tsResult: TimestampResult): Promise<string | null>;
91
- export declare function parseVerifyResult(verifyResult: TimestampResult): Promise<TimestampInfo>;
@@ -1,271 +0,0 @@
1
- // ======================================
2
- // ZipKitOTS.ts
3
- // Copyright (c) 2025 NeoWare, Inc. All rights reserved.
4
- // ======================================
5
- // ZipKit OpenTimestamps Routines
6
- "use server";
7
- "use strict";
8
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- var desc = Object.getOwnPropertyDescriptor(m, k);
11
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
- desc = { enumerable: true, get: function() { return m[k]; } };
13
- }
14
- Object.defineProperty(o, k2, desc);
15
- }) : (function(o, m, k, k2) {
16
- if (k2 === undefined) k2 = k;
17
- o[k2] = m[k];
18
- }));
19
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
- Object.defineProperty(o, "default", { enumerable: true, value: v });
21
- }) : function(o, v) {
22
- o["default"] = v;
23
- });
24
- var __importStar = (this && this.__importStar) || (function () {
25
- var ownKeys = function(o) {
26
- ownKeys = Object.getOwnPropertyNames || function (o) {
27
- var ar = [];
28
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
- return ar;
30
- };
31
- return ownKeys(o);
32
- };
33
- return function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- })();
41
- var __importDefault = (this && this.__importDefault) || function (mod) {
42
- return (mod && mod.__esModule) ? mod : { "default": mod };
43
- };
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.verifyTimestamp = verifyTimestamp;
46
- exports.createTimestamp = createTimestamp;
47
- exports.deserializeOts = deserializeOts;
48
- exports.parseVerifyResult = parseVerifyResult;
49
- const moment_timezone_1 = __importDefault(require("moment-timezone"));
50
- if (global._bitcore)
51
- delete global._bitcore;
52
- let OTSInstance = null;
53
- async function getOTS() {
54
- if (!OTSInstance) {
55
- OTSInstance = (await Promise.resolve().then(() => __importStar(require('opentimestamps')))).default;
56
- }
57
- return OTSInstance;
58
- }
59
- /**
60
- * Verifies a timestamp proof against a file hash
61
- *
62
- * @param hashDigest - SHA-256 hash digest of the file or merkle root (hex string)
63
- * @param otsData - The OpenTimestamps proof data
64
- * @returns Promise with verification result or null on critical failure
65
- *
66
- * @example
67
- * // Verify a timestamp proof
68
- * const hashDigest = "8a9d..."; // SHA-256 digest in hex format
69
- * const result = await verifyTimestamp(hashDigest, otsBuffer);
70
- *
71
- * if (result) {
72
- * if (result.error) {
73
- * console.error("Verification failed:", result.error);
74
- * } else {
75
- * console.log("Verification succeeded:", result.verified);
76
- *
77
- * if (result.upgradedOts) {
78
- * // Save the upgraded timestamp
79
- * }
80
- * }
81
- * }
82
- */
83
- async function verifyTimestamp(hashDigest, ots) {
84
- if (!hashDigest || !ots) {
85
- console.error('verifyTimestamp - Invalid parameters');
86
- return null;
87
- }
88
- const tsResult = {
89
- merkleRoot: hashDigest,
90
- ots: ots,
91
- verified: false,
92
- results: null,
93
- error: null,
94
- attestations: null,
95
- upgradedOts: null,
96
- };
97
- try {
98
- const OpenTimestamps = await getOTS();
99
- // Convert the base64 string to a Buffer
100
- // const _otsBuffer = Buffer.from(ots, 'base64');
101
- const _otsBuffer = Buffer.from(ots);
102
- const detachedOts = OpenTimestamps.DetachedTimestampFile.deserialize(_otsBuffer);
103
- const digest = Buffer.from(hashDigest, 'hex');
104
- const hashOts = OpenTimestamps.DetachedTimestampFile.fromHash(new OpenTimestamps.Ops.OpSHA256(), digest);
105
- // Check if the MetaStamp should be upgraded
106
- const upgrade = await OpenTimestamps.upgrade(detachedOts);
107
- if (upgrade) {
108
- console.log('verifyTimestamp === Timestamp should be upgraded!');
109
- tsResult.upgradedOts = detachedOts.serializeToBytes();
110
- }
111
- // Verify the MetaStamp
112
- tsResult.results = await OpenTimestamps.verify(detachedOts, hashOts, {
113
- ignoreBitcoinNode: true, // Don't check for local Bitcoin node
114
- timeout: 5000
115
- });
116
- var _attest = [];
117
- detachedOts.timestamp.allAttestations().forEach((attestation) => {
118
- if (attestation instanceof OpenTimestamps.Notary.UnknownAttestation) {
119
- console.log('Unknown attestation type');
120
- }
121
- else {
122
- // console.log(attestation);
123
- _attest.push(attestation);
124
- }
125
- });
126
- tsResult.attestations = JSON.stringify(_attest);
127
- // Check if the results show a verified timestamp
128
- if (Object.keys(tsResult.results).length < 1) {
129
- tsResult.results = null;
130
- tsResult.verified = false;
131
- }
132
- else {
133
- tsResult.verified = true;
134
- }
135
- console.log('verifyTimestamp === tsResult: ', tsResult);
136
- return tsResult;
137
- }
138
- catch (error) {
139
- let errMsg = error?.message || 'Timestamp Verification Failed!';
140
- if (errMsg.indexOf('ESOCKETTIMEDOUT') != -1) {
141
- errMsg = 'Server timed out, Try again in a few minutes.';
142
- }
143
- else if (errMsg.indexOf('502') != -1) {
144
- errMsg = 'Server failed to respond, Try again in a few minutes.';
145
- }
146
- else if (errMsg.indexOf('ECONNRESET') != -1) {
147
- errMsg = 'Server connection reset, Try again in a few minutes.';
148
- }
149
- return { error: errMsg };
150
- }
151
- }
152
- /**
153
- * Creates a timestamp proof for a file hash using OpenTimestamps
154
- *
155
- * @param hashDigest - SHA-256 hash digest of the file or merkle root (hex string)
156
- * @returns Promise containing the OpenTimestamps proof or null on failure
157
- *
158
- * @example
159
- * // Create a timestamp for a file hash
160
- * const hashDigest = "8a9d..."; // SHA-256 digest in hex format
161
- * const timestampProof = await createTimestamp(hashDigest);
162
- *
163
- * if (timestampProof) {
164
- * // Save the timestamp proof to storage
165
- * }
166
- */
167
- async function createTimestamp(hashDigest) {
168
- if (!hashDigest)
169
- return null;
170
- try {
171
- const OpenTimestamps = await getOTS();
172
- // Convert hex string to Buffer
173
- const hashBuffer = Buffer.from(hashDigest, 'hex');
174
- // Create detached timestamp file
175
- const detached = OpenTimestamps.DetachedTimestampFile.fromHash(new OpenTimestamps.Ops.OpSHA256(), hashBuffer);
176
- // Create the timestamp
177
- await OpenTimestamps.stamp(detached);
178
- // Return the serialized timestamp
179
- return Buffer.from(detached.serializeToBytes());
180
- }
181
- catch (error) {
182
- console.error('Error creating timestamp:', error);
183
- throw new Error('Error creating timestamp');
184
- }
185
- }
186
- /**
187
- * Deserializes timestamp metadata to extract attestation information
188
- * Used for generating timestamp certificates and displaying verification details
189
- *
190
- * @param tsResult - Timestamp verification result to deserialize
191
- * @returns JSON string of deserialized data or null on failure
192
- */
193
- async function deserializeOts(tsResult) {
194
- let result = {
195
- attestStr: null,
196
- needsUpdateMsg: null,
197
- attestationValues: [],
198
- };
199
- for (const chain in tsResult.results) {
200
- let _results = tsResult.results[chain];
201
- const _attestDate = (0, moment_timezone_1.default)(_results.timestamp * 1000).tz(moment_timezone_1.default.tz.guess()).format('MM-DD-YYYY hh:mma z');
202
- const blockchain = chain.charAt(0).toUpperCase() + chain.slice(1);
203
- result.attestStr = `<b>${blockchain} block ${_results.height}</b> attests existence as of <b>${_attestDate}</b>`;
204
- }
205
- ;
206
- let timestamp = tsResult.ots;
207
- if (tsResult.upgradedOts != null) {
208
- result.needsUpdateMsg = "This Zip file requires updated Timestamp Metadata!";
209
- // Use the updated timestamp metadata
210
- timestamp = tsResult.upgradedOts;
211
- }
212
- // Extract the attestation values from the timestamp metadata
213
- if (!timestamp)
214
- return null;
215
- const OpenTimestamps = await getOTS();
216
- const detached = OpenTimestamps.DetachedTimestampFile.deserialize(Buffer.from(timestamp));
217
- const infoResult = OpenTimestamps.info(detached);
218
- // Extract all transaction IDs using a regular expression
219
- const transactionIdMatches = [...infoResult.matchAll(/transaction id ([a-f0-9]+)/gi)];
220
- const transactionIds = transactionIdMatches.map(match => match[1]);
221
- // Extract the value inside the parentheses using a regular expression
222
- const blockHeightMatches = [...infoResult.matchAll(/verify BitcoinBlockHeaderAttestation\((\d+)\)/g)];
223
- const blockHeights = blockHeightMatches.map(match => match[1]);
224
- // Extract all values after "block merkle root" using a regular expression
225
- const merkleRootMatches = [...infoResult.matchAll(/block merkle root ([a-f0-9]+)/gi)];
226
- const merkleRoots = merkleRootMatches.map(match => match[1]);
227
- // Group the values in a loop
228
- result.attestationValues = [];
229
- if (transactionIds.length === blockHeights.length && transactionIds.length === merkleRoots.length) {
230
- for (let i = 0; i < transactionIds.length; i++) {
231
- result.attestationValues.push({
232
- blockHeight: blockHeights[i],
233
- transactionId: transactionIds[i],
234
- merkleRoot: merkleRoots[i]
235
- });
236
- }
237
- // Sort the grouped values by blockHeight in ascending order
238
- result.attestationValues.sort((a, b) => a.blockHeight - b.blockHeight);
239
- }
240
- return JSON.stringify(result);
241
- }
242
- // Parse the verifyResult into a TimestampInfo object
243
- async function parseVerifyResult(verifyResult) {
244
- let tsInfo = {
245
- message: '',
246
- results: [],
247
- attestDate: null,
248
- attestHeight: null,
249
- submittedUri: null,
250
- otsUpgraded: false
251
- };
252
- for (const chain in verifyResult?.results) {
253
- let _results = verifyResult.results[chain];
254
- const _date = (0, moment_timezone_1.default)(_results.timestamp * 1000)
255
- .tz('UTC')
256
- .format('MM-DD-YYYY hh:mma z');
257
- const _blockchain = chain.charAt(0).toUpperCase() + chain.slice(1);
258
- tsInfo.message = 'Validated - ' + _blockchain + ' block ' + _results.height + ' attests existence as of ' + _date;
259
- if (tsInfo.attestHeight == null) {
260
- tsInfo.attestDate = new Date(_results.timestamp * 1000);
261
- tsInfo.attestHeight = _results.height;
262
- }
263
- tsInfo.results.push(tsInfo.message);
264
- }
265
- ;
266
- if (verifyResult?.upgradedOts) {
267
- tsInfo.otsUpgraded = true;
268
- tsInfo.results.push('Notice: Please select "Upgrade Timestamp" to save the upgraded timestamp.');
269
- }
270
- return tsInfo;
271
- }