@ottochain/sdk 1.2.0 → 1.4.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 (103) hide show
  1. package/LICENSE +190 -0
  2. package/dist/cjs/index.js +34 -15
  3. package/dist/cjs/ottochain/index.js +20 -1
  4. package/dist/cjs/ottochain/metagraph-client.js +7 -8
  5. package/dist/cjs/ottochain/snapshot.js +3 -3
  6. package/dist/cjs/{metakit → ottochain}/transaction.js +4 -5
  7. package/dist/cjs/verify.js +17 -0
  8. package/dist/esm/apps/contracts/index.js +28 -10
  9. package/dist/esm/apps/corporate/index.js +79 -24
  10. package/dist/esm/apps/governance/index.js +85 -36
  11. package/dist/esm/apps/identity/constants.js +27 -22
  12. package/dist/esm/apps/identity/index.js +35 -7
  13. package/dist/esm/apps/index.js +32 -6
  14. package/dist/esm/apps/markets/index.js +27 -6
  15. package/dist/esm/apps/oracles/index.js +27 -7
  16. package/dist/esm/errors.js +19 -9
  17. package/dist/esm/generated/google/protobuf/struct.js +39 -33
  18. package/dist/esm/generated/google/protobuf/timestamp.js +9 -6
  19. package/dist/esm/generated/index.js +134 -10
  20. package/dist/esm/generated/ottochain/apps/contracts/v1/contract.js +54 -48
  21. package/dist/esm/generated/ottochain/apps/corporate/v1/corporate.js +357 -335
  22. package/dist/esm/generated/ottochain/apps/governance/v1/governance.js +299 -284
  23. package/dist/esm/generated/ottochain/apps/identity/v1/agent.js +47 -38
  24. package/dist/esm/generated/ottochain/apps/identity/v1/attestation.js +50 -44
  25. package/dist/esm/generated/ottochain/apps/markets/v1/market.js +86 -77
  26. package/dist/esm/generated/ottochain/apps/oracles/v1/oracle.js +72 -66
  27. package/dist/esm/generated/ottochain/v1/common.js +4 -1
  28. package/dist/esm/generated/ottochain/v1/fiber.js +96 -90
  29. package/dist/esm/generated/ottochain/v1/messages.js +82 -79
  30. package/dist/esm/generated/ottochain/v1/records.js +140 -137
  31. package/dist/esm/index.js +86 -20
  32. package/dist/esm/{metakit → ottochain}/drop-nulls.js +5 -1
  33. package/dist/esm/ottochain/index.js +56 -3
  34. package/dist/esm/ottochain/metagraph-client.js +16 -13
  35. package/dist/esm/{metakit → ottochain}/normalize.js +11 -4
  36. package/dist/esm/ottochain/snapshot.js +20 -10
  37. package/dist/esm/{metakit → ottochain}/transaction.js +25 -14
  38. package/dist/esm/ottochain/types.js +2 -1
  39. package/dist/esm/types.js +7 -2
  40. package/dist/esm/validation.js +76 -65
  41. package/dist/esm/verify.js +17 -0
  42. package/dist/types/index.d.ts +14 -7
  43. package/dist/types/ottochain/index.d.ts +4 -0
  44. package/dist/types/ottochain/metagraph-client.d.ts +1 -1
  45. package/dist/types/{metakit → ottochain}/transaction.d.ts +1 -1
  46. package/dist/types/validation.d.ts +8 -8
  47. package/dist/types/verify.d.ts +9 -0
  48. package/package.json +5 -3
  49. package/dist/cjs/metakit/binary.js +0 -58
  50. package/dist/cjs/metakit/canonicalize.js +0 -40
  51. package/dist/cjs/metakit/codec.js +0 -45
  52. package/dist/cjs/metakit/currency-transaction.js +0 -319
  53. package/dist/cjs/metakit/currency-types.js +0 -13
  54. package/dist/cjs/metakit/hash.js +0 -84
  55. package/dist/cjs/metakit/index.js +0 -86
  56. package/dist/cjs/metakit/network/client.js +0 -78
  57. package/dist/cjs/metakit/network/currency-l1-client.js +0 -101
  58. package/dist/cjs/metakit/network/data-l1-client.js +0 -76
  59. package/dist/cjs/metakit/network/index.js +0 -16
  60. package/dist/cjs/metakit/network/types.js +0 -20
  61. package/dist/cjs/metakit/sign.js +0 -120
  62. package/dist/cjs/metakit/signed-object.js +0 -100
  63. package/dist/cjs/metakit/types.js +0 -14
  64. package/dist/cjs/metakit/verify.js +0 -217
  65. package/dist/cjs/metakit/wallet.js +0 -127
  66. package/dist/esm/metakit/binary.js +0 -53
  67. package/dist/esm/metakit/canonicalize.js +0 -33
  68. package/dist/esm/metakit/codec.js +0 -38
  69. package/dist/esm/metakit/currency-transaction.js +0 -306
  70. package/dist/esm/metakit/currency-types.js +0 -10
  71. package/dist/esm/metakit/hash.js +0 -77
  72. package/dist/esm/metakit/index.js +0 -33
  73. package/dist/esm/metakit/network/client.js +0 -74
  74. package/dist/esm/metakit/network/currency-l1-client.js +0 -97
  75. package/dist/esm/metakit/network/data-l1-client.js +0 -72
  76. package/dist/esm/metakit/network/index.js +0 -9
  77. package/dist/esm/metakit/network/types.js +0 -16
  78. package/dist/esm/metakit/sign.js +0 -114
  79. package/dist/esm/metakit/signed-object.js +0 -94
  80. package/dist/esm/metakit/types.js +0 -11
  81. package/dist/esm/metakit/verify.js +0 -210
  82. package/dist/esm/metakit/wallet.js +0 -117
  83. package/dist/types/metakit/binary.d.ts +0 -38
  84. package/dist/types/metakit/canonicalize.d.ts +0 -26
  85. package/dist/types/metakit/codec.d.ts +0 -16
  86. package/dist/types/metakit/currency-transaction.d.ts +0 -157
  87. package/dist/types/metakit/currency-types.d.ts +0 -55
  88. package/dist/types/metakit/hash.d.ts +0 -50
  89. package/dist/types/metakit/index.d.ts +0 -26
  90. package/dist/types/metakit/network/client.d.ts +0 -23
  91. package/dist/types/metakit/network/currency-l1-client.d.ts +0 -71
  92. package/dist/types/metakit/network/data-l1-client.d.ts +0 -57
  93. package/dist/types/metakit/network/index.d.ts +0 -10
  94. package/dist/types/metakit/network/types.d.ts +0 -74
  95. package/dist/types/metakit/sign.d.ts +0 -65
  96. package/dist/types/metakit/signed-object.d.ts +0 -66
  97. package/dist/types/metakit/types.d.ts +0 -67
  98. package/dist/types/metakit/verify.d.ts +0 -55
  99. package/dist/types/metakit/wallet.d.ts +0 -70
  100. /package/dist/cjs/{metakit → ottochain}/drop-nulls.js +0 -0
  101. /package/dist/cjs/{metakit → ottochain}/normalize.js +0 -0
  102. /package/dist/types/{metakit → ottochain}/drop-nulls.d.ts +0 -0
  103. /package/dist/types/{metakit → ottochain}/normalize.d.ts +0 -0
@@ -1,74 +0,0 @@
1
- /**
2
- * Base HTTP client for network operations
3
- *
4
- * @packageDocumentation
5
- */
6
- import { NetworkError } from './types.js';
7
- const DEFAULT_TIMEOUT = 30000;
8
- /**
9
- * Simple HTTP client using native fetch
10
- */
11
- export class HttpClient {
12
- constructor(baseUrl, timeout = DEFAULT_TIMEOUT) {
13
- this.baseUrl = baseUrl.replace(/\/$/, '');
14
- this.defaultTimeout = timeout;
15
- }
16
- /**
17
- * Make a GET request
18
- */
19
- async get(path, options = {}) {
20
- return this.request('GET', path, undefined, options);
21
- }
22
- /**
23
- * Make a POST request
24
- */
25
- async post(path, body, options = {}) {
26
- return this.request('POST', path, body, options);
27
- }
28
- async request(method, path, body, options = {}) {
29
- const url = `${this.baseUrl}${path}`;
30
- const timeout = options.timeout ?? this.defaultTimeout;
31
- const controller = new AbortController();
32
- const timeoutId = setTimeout(() => controller.abort(), timeout);
33
- try {
34
- const headers = {
35
- 'Content-Type': 'application/json',
36
- Accept: 'application/json',
37
- ...options.headers,
38
- };
39
- const response = await fetch(url, {
40
- method,
41
- headers,
42
- body: body ? JSON.stringify(body) : undefined,
43
- signal: controller.signal,
44
- });
45
- clearTimeout(timeoutId);
46
- const text = await response.text();
47
- if (!response.ok) {
48
- throw new NetworkError(`HTTP ${response.status}: ${response.statusText}`, response.status, text);
49
- }
50
- if (!text) {
51
- return undefined;
52
- }
53
- try {
54
- return JSON.parse(text);
55
- }
56
- catch {
57
- return text;
58
- }
59
- }
60
- catch (error) {
61
- clearTimeout(timeoutId);
62
- if (error instanceof NetworkError) {
63
- throw error;
64
- }
65
- if (error instanceof Error) {
66
- if (error.name === 'AbortError') {
67
- throw new NetworkError(`Request timeout after ${timeout}ms`);
68
- }
69
- throw new NetworkError(error.message);
70
- }
71
- throw new NetworkError('Unknown network error');
72
- }
73
- }
74
- }
@@ -1,97 +0,0 @@
1
- /**
2
- * Currency L1 client for submitting and querying transactions
3
- *
4
- * @packageDocumentation
5
- */
6
- import { HttpClient } from './client.js';
7
- import { NetworkError } from './types.js';
8
- /**
9
- * Client for interacting with Currency L1 nodes
10
- *
11
- * @example
12
- * ```typescript
13
- * const client = new CurrencyL1Client({ l1Url: 'http://localhost:9010' });
14
- *
15
- * // Get last reference for an address
16
- * const lastRef = await client.getLastReference('DAG...');
17
- *
18
- * // Submit a transaction
19
- * const result = await client.postTransaction(signedTx);
20
- *
21
- * // Check transaction status
22
- * const pending = await client.getPendingTransaction(result.hash);
23
- * ```
24
- */
25
- export class CurrencyL1Client {
26
- /**
27
- * Create a new CurrencyL1Client
28
- *
29
- * @param config - Network configuration with l1Url
30
- * @throws Error if l1Url is not provided
31
- */
32
- constructor(config) {
33
- if (!config.l1Url) {
34
- throw new Error('l1Url is required for CurrencyL1Client');
35
- }
36
- this.client = new HttpClient(config.l1Url, config.timeout);
37
- }
38
- /**
39
- * Get the last accepted transaction reference for an address
40
- *
41
- * This is needed to create a new transaction that chains from
42
- * the address's most recent transaction.
43
- *
44
- * @param address - DAG address to query
45
- * @param options - Request options
46
- * @returns Transaction reference with hash and ordinal
47
- */
48
- async getLastReference(address, options) {
49
- return this.client.get(`/transactions/last-reference/${address}`, options);
50
- }
51
- /**
52
- * Submit a signed currency transaction to the L1 network
53
- *
54
- * @param transaction - Signed currency transaction
55
- * @param options - Request options
56
- * @returns Response containing the transaction hash
57
- */
58
- async postTransaction(transaction, options) {
59
- return this.client.post('/transactions', transaction, options);
60
- }
61
- /**
62
- * Get a pending transaction by hash
63
- *
64
- * Use this to poll for transaction status after submission.
65
- * Returns null if the transaction is not found (already confirmed or invalid).
66
- *
67
- * @param hash - Transaction hash
68
- * @param options - Request options
69
- * @returns Pending transaction details or null if not found
70
- */
71
- async getPendingTransaction(hash, options) {
72
- try {
73
- return await this.client.get(`/transactions/${hash}`, options);
74
- }
75
- catch (error) {
76
- if (error instanceof NetworkError && error.statusCode === 404) {
77
- return null;
78
- }
79
- throw error;
80
- }
81
- }
82
- /**
83
- * Check the health/availability of the L1 node
84
- *
85
- * @param options - Request options
86
- * @returns True if the node is healthy
87
- */
88
- async checkHealth(options) {
89
- try {
90
- await this.client.get('/cluster/info', options);
91
- return true;
92
- }
93
- catch {
94
- return false;
95
- }
96
- }
97
- }
@@ -1,72 +0,0 @@
1
- /**
2
- * Data L1 client for submitting data transactions to metagraphs
3
- *
4
- * @packageDocumentation
5
- */
6
- import { HttpClient } from './client.js';
7
- /**
8
- * Client for interacting with Data L1 nodes (metagraphs)
9
- *
10
- * @example
11
- * ```typescript
12
- * const client = new DataL1Client({ dataL1Url: 'http://localhost:8080' });
13
- *
14
- * // Estimate fee for data submission
15
- * const feeInfo = await client.estimateFee(signedData);
16
- *
17
- * // Submit data
18
- * const result = await client.postData(signedData);
19
- * ```
20
- */
21
- export class DataL1Client {
22
- /**
23
- * Create a new DataL1Client
24
- *
25
- * @param config - Network configuration with dataL1Url
26
- * @throws Error if dataL1Url is not provided
27
- */
28
- constructor(config) {
29
- if (!config.dataL1Url) {
30
- throw new Error('dataL1Url is required for DataL1Client');
31
- }
32
- this.client = new HttpClient(config.dataL1Url, config.timeout);
33
- }
34
- /**
35
- * Estimate the fee for submitting data
36
- *
37
- * Some metagraphs charge fees for data submissions.
38
- * Call this before postData to know the required fee.
39
- *
40
- * @param data - Signed data object to estimate fee for
41
- * @param options - Request options
42
- * @returns Fee estimate with amount and destination address
43
- */
44
- async estimateFee(data, options) {
45
- return this.client.post('/data/estimate-fee', data, options);
46
- }
47
- /**
48
- * Submit signed data to the Data L1 node
49
- *
50
- * @param data - Signed data object to submit
51
- * @param options - Request options
52
- * @returns Response containing the data hash
53
- */
54
- async postData(data, options) {
55
- return this.client.post('/data', data, options);
56
- }
57
- /**
58
- * Check the health/availability of the Data L1 node
59
- *
60
- * @param options - Request options
61
- * @returns True if the node is healthy
62
- */
63
- async checkHealth(options) {
64
- try {
65
- await this.client.get('/cluster/info', options);
66
- return true;
67
- }
68
- catch {
69
- return false;
70
- }
71
- }
72
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Network operations for L1 node interactions
3
- *
4
- * @packageDocumentation
5
- */
6
- export { CurrencyL1Client } from './currency-l1-client.js';
7
- export { DataL1Client } from './data-l1-client.js';
8
- export { HttpClient } from './client.js';
9
- export { NetworkError } from './types.js';
@@ -1,16 +0,0 @@
1
- /**
2
- * Network types for L1 client operations
3
- *
4
- * @packageDocumentation
5
- */
6
- /**
7
- * Network error with status code and response details
8
- */
9
- export class NetworkError extends Error {
10
- constructor(message, statusCode, responseBody) {
11
- super(message);
12
- this.name = 'NetworkError';
13
- this.statusCode = statusCode;
14
- this.responseBody = responseBody;
15
- }
16
- }
@@ -1,114 +0,0 @@
1
- /**
2
- * Signing Functions
3
- *
4
- * ECDSA signing using secp256k1 curve via dag4js.
5
- * Implements the Constellation signature protocol.
6
- */
7
- import { dag4 } from '@stardust-collective/dag4';
8
- import { sha256 } from 'js-sha256';
9
- import { canonicalize } from './canonicalize.js';
10
- /**
11
- * Sign data using the regular Constellation protocol (non-DataUpdate)
12
- *
13
- * Protocol:
14
- * 1. Canonicalize JSON (RFC 8785)
15
- * 2. SHA-256 hash the canonical JSON string
16
- * 3. Sign using dag4.keyStore.sign
17
- *
18
- * @param data - Any JSON-serializable object
19
- * @param privateKey - Private key in hex format
20
- * @returns SignatureProof with public key ID and signature
21
- *
22
- * @example
23
- * ```typescript
24
- * const proof = await sign({ action: 'test' }, privateKeyHex);
25
- * console.log(proof.id); // public key (128 chars)
26
- * console.log(proof.signature); // DER signature
27
- * ```
28
- */
29
- export async function sign(data, privateKey) {
30
- // Step 1: Canonicalize JSON (RFC 8785)
31
- const canonicalJson = canonicalize(data);
32
- // Step 2-3: UTF-8 encode and SHA-256 hash (sha256 handles UTF-8 encoding internally)
33
- // Returns 64-character hex string
34
- const hashHex = sha256(canonicalJson);
35
- // Step 4-6: dag4.keyStore.sign internally:
36
- // 4. Treats hashHex as UTF-8 bytes
37
- // 5. SHA-512 hashes those bytes, truncates to 32 bytes
38
- // 6. Signs with ECDSA secp256k1
39
- const signature = await dag4.keyStore.sign(privateKey, hashHex);
40
- // Get public key ID (without 04 prefix)
41
- const publicKey = dag4.keyStore.getPublicKeyFromPrivate(privateKey, false);
42
- const id = normalizePublicKeyId(publicKey);
43
- return { id, signature };
44
- }
45
- /**
46
- * Sign data as a DataUpdate (with Constellation prefix)
47
- *
48
- * Protocol:
49
- * 1. Canonicalize JSON (RFC 8785)
50
- * 2. Base64 encode the canonical JSON
51
- * 3. Sign using dag4.keyStore.dataSign (adds Constellation prefix internally)
52
- *
53
- * @param data - Any JSON-serializable object
54
- * @param privateKey - Private key in hex format
55
- * @returns SignatureProof
56
- */
57
- export async function signDataUpdate(data, privateKey) {
58
- // Step 1: Canonicalize JSON
59
- const canonicalJson = canonicalize(data);
60
- // Step 2: Base64 encode for dataSign
61
- const base64String = Buffer.from(canonicalJson, 'utf-8').toString('base64');
62
- // Step 3: Sign using dag4's dataSign (handles Constellation prefix internally)
63
- const signature = await dag4.keyStore.dataSign(privateKey, base64String);
64
- // Get public key ID
65
- const publicKey = dag4.keyStore.getPublicKeyFromPrivate(privateKey, false);
66
- const id = normalizePublicKeyId(publicKey);
67
- return { id, signature };
68
- }
69
- /**
70
- * Sign a pre-computed SHA-256 hash
71
- *
72
- * This is the low-level signing function. Use `sign()` or `signDataUpdate()`
73
- * for most use cases.
74
- *
75
- * Protocol (performed by dag4.keyStore.sign):
76
- * 1. Treat hashHex as UTF-8 bytes (64 ASCII characters = 64 bytes)
77
- * 2. SHA-512 hash those bytes (produces 64 bytes)
78
- * 3. Truncate to first 32 bytes (for secp256k1 curve order)
79
- * 4. Sign with ECDSA secp256k1
80
- * 5. Return DER-encoded signature
81
- *
82
- * @param hashHex - SHA-256 hash as 64-character hex string
83
- * @param privateKey - Private key in hex format (64 characters)
84
- * @returns DER-encoded signature in hex format
85
- *
86
- * @example
87
- * ```typescript
88
- * // Compute your own hash
89
- * const hashHex = sha256(myData);
90
- * const signature = await signHash(hashHex, privateKey);
91
- * ```
92
- */
93
- export async function signHash(hashHex, privateKey) {
94
- // dag4.keyStore.sign performs:
95
- // 1. SHA-512 of hashHex (treating 64 hex chars as UTF-8 bytes)
96
- // 2. Truncation to 32 bytes (handled internally by crypto library)
97
- // 3. ECDSA signing with secp256k1
98
- return dag4.keyStore.sign(privateKey, hashHex);
99
- }
100
- /**
101
- * Normalize public key to ID format (without 04 prefix, 128 chars)
102
- */
103
- function normalizePublicKeyId(publicKey) {
104
- // If 130 chars (with 04 prefix), remove prefix
105
- if (publicKey.length === 130 && publicKey.startsWith('04')) {
106
- return publicKey.substring(2);
107
- }
108
- // If 128 chars (without prefix), return as-is
109
- if (publicKey.length === 128) {
110
- return publicKey;
111
- }
112
- // Otherwise return as-is and let validation catch issues
113
- return publicKey;
114
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * High-Level Signed Object API
3
- *
4
- * Convenience functions for creating and managing signed objects.
5
- */
6
- import { sign, signDataUpdate } from './sign.js';
7
- /**
8
- * Create a signed object with a single signature
9
- *
10
- * @param value - Any JSON-serializable object
11
- * @param privateKey - Private key in hex format
12
- * @param options - Signing options
13
- * @returns Signed object ready for submission
14
- *
15
- * @example
16
- * ```typescript
17
- * // Sign a regular data object
18
- * const signed = await createSignedObject(myData, privateKey);
19
- *
20
- * // Sign as DataUpdate for L1 submission
21
- * const signedUpdate = await createSignedObject(myData, privateKey, { isDataUpdate: true });
22
- * ```
23
- */
24
- export async function createSignedObject(value, privateKey, options = {}) {
25
- const { isDataUpdate = false } = options;
26
- const proof = isDataUpdate
27
- ? await signDataUpdate(value, privateKey)
28
- : await sign(value, privateKey);
29
- return {
30
- value,
31
- proofs: [proof],
32
- };
33
- }
34
- /**
35
- * Add an additional signature to an existing signed object
36
- *
37
- * This allows building multi-signature objects where multiple parties
38
- * need to sign the same data.
39
- *
40
- * @param signed - Existing signed object
41
- * @param privateKey - Private key in hex format
42
- * @param options - Signing options (must match original signing)
43
- * @returns New signed object with additional proof
44
- *
45
- * @example
46
- * ```typescript
47
- * // First party signs
48
- * let signed = await createSignedObject(data, party1Key);
49
- *
50
- * // Second party adds signature
51
- * signed = await addSignature(signed, party2Key);
52
- *
53
- * // Now has 2 proofs
54
- * console.log(signed.proofs.length); // 2
55
- * ```
56
- */
57
- export async function addSignature(signed, privateKey, options = {}) {
58
- const { isDataUpdate = false } = options;
59
- const newProof = isDataUpdate
60
- ? await signDataUpdate(signed.value, privateKey)
61
- : await sign(signed.value, privateKey);
62
- return {
63
- value: signed.value,
64
- proofs: [...signed.proofs, newProof],
65
- };
66
- }
67
- /**
68
- * Create a signed object with multiple signatures at once
69
- *
70
- * Useful when you have access to multiple private keys and want
71
- * to create a multi-sig object in one operation.
72
- *
73
- * @param value - Any JSON-serializable object
74
- * @param privateKeys - Array of private keys in hex format
75
- * @param options - Signing options
76
- * @returns Signed object with multiple proofs
77
- *
78
- * @example
79
- * ```typescript
80
- * const signed = await batchSign(data, [key1, key2, key3]);
81
- * console.log(signed.proofs.length); // 3
82
- * ```
83
- */
84
- export async function batchSign(value, privateKeys, options = {}) {
85
- if (privateKeys.length === 0) {
86
- throw new Error('At least one private key is required');
87
- }
88
- const { isDataUpdate = false } = options;
89
- const proofs = await Promise.all(privateKeys.map((key) => (isDataUpdate ? signDataUpdate(value, key) : sign(value, key))));
90
- return {
91
- value,
92
- proofs,
93
- };
94
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * Core type definitions for the Ottochain SDK
3
- */
4
- /**
5
- * Supported signature algorithm
6
- */
7
- export const ALGORITHM = 'SECP256K1_RFC8785_V1';
8
- /**
9
- * Constellation prefix for DataUpdate signing
10
- */
11
- export const CONSTELLATION_PREFIX = '\x19Constellation Signed Data:\n';
@@ -1,210 +0,0 @@
1
- /**
2
- * Signature Verification
3
- *
4
- * Verify ECDSA signatures using secp256k1 curve via dag4js.
5
- */
6
- import { dag4 } from '@stardust-collective/dag4';
7
- import { sha256 } from 'js-sha256';
8
- import { toBytes } from './binary.js';
9
- // secp256k1 curve order (n) for signature normalization
10
- const SECP256K1_N = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
11
- const SECP256K1_HALF_N = SECP256K1_N / 2n;
12
- /**
13
- * Verify a signed object
14
- *
15
- * @param signed - Signed object with value and proofs
16
- * @param isDataUpdate - Whether the value was signed as a DataUpdate
17
- * @returns VerificationResult with valid/invalid proof lists
18
- *
19
- * @example
20
- * ```typescript
21
- * const result = await verify(signedObject);
22
- * if (result.isValid) {
23
- * console.log('All signatures valid');
24
- * }
25
- * ```
26
- */
27
- export async function verify(signed, isDataUpdate = false) {
28
- // Compute the hash that should have been signed
29
- const bytes = toBytes(signed.value, isDataUpdate);
30
- const hashHex = sha256.hex(bytes);
31
- const validProofs = [];
32
- const invalidProofs = [];
33
- for (const proof of signed.proofs) {
34
- try {
35
- const isValid = await verifyHash(hashHex, proof.signature, proof.id);
36
- if (isValid) {
37
- validProofs.push(proof);
38
- }
39
- else {
40
- invalidProofs.push(proof);
41
- }
42
- }
43
- catch {
44
- // Verification error = invalid
45
- invalidProofs.push(proof);
46
- }
47
- }
48
- return {
49
- isValid: invalidProofs.length === 0 && validProofs.length > 0,
50
- validProofs,
51
- invalidProofs,
52
- };
53
- }
54
- /**
55
- * Verify a signature against a SHA-256 hash
56
- *
57
- * Protocol:
58
- * 1. Treat hash hex as UTF-8 bytes (NOT hex decode)
59
- * 2. SHA-512 hash
60
- * 3. Truncate to 32 bytes (handled internally by dag4)
61
- * 4. Verify ECDSA signature
62
- *
63
- * @param hashHex - SHA-256 hash as 64-character hex string
64
- * @param signature - DER-encoded signature in hex format
65
- * @param publicKeyId - Public key in hex (with or without 04 prefix)
66
- * @returns true if signature is valid
67
- */
68
- export async function verifyHash(hashHex, signature, publicKeyId) {
69
- try {
70
- // Normalize public key (add 04 prefix if needed)
71
- const fullPublicKey = normalizePublicKey(publicKeyId);
72
- // Normalize signature to low-S form for BIP 62/146 compatibility
73
- // Some signing implementations produce high-S signatures which are
74
- // mathematically valid but rejected by strict implementations
75
- const normalizedSignature = normalizeSignatureToLowS(signature);
76
- // Use dag4's verify which handles:
77
- // 1. SHA-512 of hashHex (treating as UTF-8)
78
- // 2. Internal truncation to 32 bytes
79
- // 3. ECDSA verification
80
- return dag4.keyStore.verify(fullPublicKey, hashHex, normalizedSignature);
81
- }
82
- catch {
83
- return false;
84
- }
85
- }
86
- /**
87
- * Verify a single signature proof against data
88
- *
89
- * @param data - The original data that was signed
90
- * @param proof - The signature proof to verify
91
- * @param isDataUpdate - Whether data was signed as DataUpdate
92
- * @returns true if signature is valid
93
- */
94
- export async function verifySignature(data, proof, isDataUpdate = false) {
95
- const bytes = toBytes(data, isDataUpdate);
96
- const hashHex = sha256.hex(bytes);
97
- return verifyHash(hashHex, proof.signature, proof.id);
98
- }
99
- /**
100
- * Normalize public key to full format (with 04 prefix)
101
- */
102
- function normalizePublicKey(publicKey) {
103
- // If 128 chars (without 04 prefix), add prefix
104
- if (publicKey.length === 128) {
105
- return '04' + publicKey;
106
- }
107
- // If 130 chars (with 04 prefix), return as-is
108
- if (publicKey.length === 130 && publicKey.startsWith('04')) {
109
- return publicKey;
110
- }
111
- // Otherwise return as-is
112
- return publicKey;
113
- }
114
- /**
115
- * Normalize a DER-encoded signature to use low-S value.
116
- *
117
- * BIP 62/146 requires S values to be in the lower half of the curve order.
118
- * Some signing implementations produce high-S signatures which are mathematically
119
- * valid but rejected by strict verifiers. This normalizes high-S to low-S by
120
- * computing S' = N - S where N is the curve order.
121
- */
122
- export function normalizeSignatureToLowS(signatureHex) {
123
- const bytes = hexToBytes(signatureHex);
124
- // Parse DER signature: 0x30 <total_len> 0x02 <r_len> <r> 0x02 <s_len> <s>
125
- if (bytes[0] !== 0x30) {
126
- return signatureHex; // Not a valid DER signature
127
- }
128
- let offset = 2; // Skip 0x30 and total length
129
- // Parse R
130
- if (bytes[offset] !== 0x02) {
131
- return signatureHex;
132
- }
133
- const rLen = bytes[offset + 1];
134
- const rStart = offset + 2;
135
- const rEnd = rStart + rLen;
136
- offset = rEnd;
137
- // Parse S
138
- if (bytes[offset] !== 0x02) {
139
- return signatureHex;
140
- }
141
- const sLen = bytes[offset + 1];
142
- const sStart = offset + 2;
143
- const sEnd = sStart + sLen;
144
- // Extract S value
145
- const sBytes = bytes.slice(sStart, sEnd);
146
- const s = bytesToBigInt(sBytes);
147
- // Check if S is high (> N/2)
148
- if (s <= SECP256K1_HALF_N) {
149
- return signatureHex; // Already low-S
150
- }
151
- // Compute low-S: S' = N - S
152
- const lowS = SECP256K1_N - s;
153
- const lowSBytes = bigIntToBytes(lowS);
154
- // Ensure proper DER encoding (no leading zeros unless needed for sign bit)
155
- const normalizedSBytes = normalizeDerInteger(lowSBytes);
156
- // Build new signature
157
- const rBytes = bytes.slice(rStart, rEnd);
158
- const normalizedRBytes = normalizeDerInteger(rBytes);
159
- const newSigContent = new Uint8Array([
160
- 0x02,
161
- normalizedRBytes.length,
162
- ...normalizedRBytes,
163
- 0x02,
164
- normalizedSBytes.length,
165
- ...normalizedSBytes,
166
- ]);
167
- const newSig = new Uint8Array([0x30, newSigContent.length, ...newSigContent]);
168
- return bytesToHex(newSig);
169
- }
170
- /**
171
- * Normalize a byte array for DER integer encoding
172
- */
173
- function normalizeDerInteger(bytes) {
174
- // Remove leading zeros, but keep one if the high bit is set
175
- let start = 0;
176
- while (start < bytes.length - 1 && bytes[start] === 0 && (bytes[start + 1] & 0x80) === 0) {
177
- start++;
178
- }
179
- // Add leading zero if high bit is set (to indicate positive number)
180
- if (bytes[start] & 0x80) {
181
- const result = new Uint8Array(bytes.length - start + 1);
182
- result[0] = 0;
183
- result.set(bytes.slice(start), 1);
184
- return result;
185
- }
186
- return bytes.slice(start);
187
- }
188
- function hexToBytes(hex) {
189
- const bytes = new Uint8Array(hex.length / 2);
190
- for (let i = 0; i < hex.length; i += 2) {
191
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
192
- }
193
- return bytes;
194
- }
195
- function bytesToHex(bytes) {
196
- return Array.from(bytes)
197
- .map((b) => b.toString(16).padStart(2, '0'))
198
- .join('');
199
- }
200
- function bytesToBigInt(bytes) {
201
- let result = 0n;
202
- for (const byte of bytes) {
203
- result = (result << 8n) | BigInt(byte);
204
- }
205
- return result;
206
- }
207
- function bigIntToBytes(n) {
208
- const hex = n.toString(16).padStart(64, '0'); // 32 bytes = 64 hex chars
209
- return hexToBytes(hex);
210
- }