openclaw-overlay-plugin 0.8.14 → 0.8.16

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 (190) hide show
  1. package/dist/index.js +6705 -326
  2. package/dist/index.js.map +7 -0
  3. package/dist/src/cli.js +7498 -11
  4. package/dist/src/cli.js.map +7 -0
  5. package/index.ts +1 -1
  6. package/openclaw.plugin.json +1 -1
  7. package/package.json +8 -8
  8. package/src/scripts/messaging/handlers.ts +1 -1
  9. package/src/scripts/overlay/advertisement.ts +1 -1
  10. package/src/scripts/overlay/registration.ts +1 -1
  11. package/src/scripts/overlay/services.ts +1 -1
  12. package/src/scripts/overlay/transaction.ts +1 -1
  13. package/src/scripts/payment/build.ts +1 -1
  14. package/src/scripts/payment/commands.ts +1 -1
  15. package/src/scripts/wallet/balance.ts +1 -1
  16. package/src/scripts/wallet/setup.ts +1 -1
  17. package/src/test/identity-consistency.test.ts +1 -1
  18. package/src/test/wallet.test.ts +1 -2
  19. package/dist/index.d.ts +0 -9
  20. package/dist/src/cli-main.d.ts +0 -7
  21. package/dist/src/cli-main.js +0 -202
  22. package/dist/src/cli.d.ts +0 -8
  23. package/dist/src/compatibility.test.d.ts +0 -4
  24. package/dist/src/compatibility.test.js +0 -41
  25. package/dist/src/core/config.d.ts +0 -11
  26. package/dist/src/core/config.js +0 -15
  27. package/dist/src/core/index.d.ts +0 -25
  28. package/dist/src/core/index.js +0 -26
  29. package/dist/src/core/payment.d.ts +0 -16
  30. package/dist/src/core/payment.js +0 -94
  31. package/dist/src/core/types.d.ts +0 -94
  32. package/dist/src/core/types.js +0 -4
  33. package/dist/src/core/verify.d.ts +0 -28
  34. package/dist/src/core/verify.js +0 -104
  35. package/dist/src/core/wallet.d.ts +0 -105
  36. package/dist/src/core/wallet.js +0 -256
  37. package/dist/src/scripts/baemail/commands.d.ts +0 -35
  38. package/dist/src/scripts/baemail/commands.js +0 -282
  39. package/dist/src/scripts/baemail/handler.d.ts +0 -36
  40. package/dist/src/scripts/baemail/handler.js +0 -284
  41. package/dist/src/scripts/baemail/index.d.ts +0 -5
  42. package/dist/src/scripts/baemail/index.js +0 -5
  43. package/dist/src/scripts/config.d.ts +0 -52
  44. package/dist/src/scripts/config.js +0 -75
  45. package/dist/src/scripts/index.d.ts +0 -7
  46. package/dist/src/scripts/index.js +0 -7
  47. package/dist/src/scripts/messaging/connect.d.ts +0 -8
  48. package/dist/src/scripts/messaging/connect.js +0 -168
  49. package/dist/src/scripts/messaging/handlers.d.ts +0 -21
  50. package/dist/src/scripts/messaging/handlers.js +0 -334
  51. package/dist/src/scripts/messaging/inbox.d.ts +0 -11
  52. package/dist/src/scripts/messaging/inbox.js +0 -51
  53. package/dist/src/scripts/messaging/index.d.ts +0 -8
  54. package/dist/src/scripts/messaging/index.js +0 -8
  55. package/dist/src/scripts/messaging/poll.d.ts +0 -7
  56. package/dist/src/scripts/messaging/poll.js +0 -52
  57. package/dist/src/scripts/messaging/send.d.ts +0 -7
  58. package/dist/src/scripts/messaging/send.js +0 -43
  59. package/dist/src/scripts/output.d.ts +0 -13
  60. package/dist/src/scripts/output.js +0 -28
  61. package/dist/src/scripts/overlay/advertisement.d.ts +0 -16
  62. package/dist/src/scripts/overlay/advertisement.js +0 -122
  63. package/dist/src/scripts/overlay/discover.d.ts +0 -7
  64. package/dist/src/scripts/overlay/discover.js +0 -74
  65. package/dist/src/scripts/overlay/index.d.ts +0 -7
  66. package/dist/src/scripts/overlay/index.js +0 -7
  67. package/dist/src/scripts/overlay/registration.d.ts +0 -19
  68. package/dist/src/scripts/overlay/registration.js +0 -176
  69. package/dist/src/scripts/overlay/services.d.ts +0 -29
  70. package/dist/src/scripts/overlay/services.js +0 -167
  71. package/dist/src/scripts/overlay/transaction.d.ts +0 -42
  72. package/dist/src/scripts/overlay/transaction.js +0 -103
  73. package/dist/src/scripts/payment/build.d.ts +0 -24
  74. package/dist/src/scripts/payment/build.js +0 -54
  75. package/dist/src/scripts/payment/commands.d.ts +0 -15
  76. package/dist/src/scripts/payment/commands.js +0 -73
  77. package/dist/src/scripts/payment/index.d.ts +0 -6
  78. package/dist/src/scripts/payment/index.js +0 -6
  79. package/dist/src/scripts/payment/types.d.ts +0 -56
  80. package/dist/src/scripts/payment/types.js +0 -4
  81. package/dist/src/scripts/services/index.d.ts +0 -6
  82. package/dist/src/scripts/services/index.js +0 -6
  83. package/dist/src/scripts/services/queue.d.ts +0 -11
  84. package/dist/src/scripts/services/queue.js +0 -28
  85. package/dist/src/scripts/services/request.d.ts +0 -7
  86. package/dist/src/scripts/services/request.js +0 -82
  87. package/dist/src/scripts/services/respond.d.ts +0 -11
  88. package/dist/src/scripts/services/respond.js +0 -132
  89. package/dist/src/scripts/types.d.ts +0 -107
  90. package/dist/src/scripts/types.js +0 -4
  91. package/dist/src/scripts/utils/index.d.ts +0 -6
  92. package/dist/src/scripts/utils/index.js +0 -6
  93. package/dist/src/scripts/utils/merkle.d.ts +0 -12
  94. package/dist/src/scripts/utils/merkle.js +0 -47
  95. package/dist/src/scripts/utils/storage.d.ts +0 -66
  96. package/dist/src/scripts/utils/storage.js +0 -211
  97. package/dist/src/scripts/utils/woc.d.ts +0 -26
  98. package/dist/src/scripts/utils/woc.js +0 -91
  99. package/dist/src/scripts/wallet/balance.d.ts +0 -22
  100. package/dist/src/scripts/wallet/balance.js +0 -240
  101. package/dist/src/scripts/wallet/identity.d.ts +0 -71
  102. package/dist/src/scripts/wallet/identity.js +0 -152
  103. package/dist/src/scripts/wallet/index.d.ts +0 -6
  104. package/dist/src/scripts/wallet/index.js +0 -6
  105. package/dist/src/scripts/wallet/setup.d.ts +0 -19
  106. package/dist/src/scripts/wallet/setup.js +0 -119
  107. package/dist/src/scripts/x-verification/commands.d.ts +0 -27
  108. package/dist/src/scripts/x-verification/commands.js +0 -222
  109. package/dist/src/scripts/x-verification/index.d.ts +0 -4
  110. package/dist/src/scripts/x-verification/index.js +0 -4
  111. package/dist/src/services/built-in/api-proxy/index.d.ts +0 -6
  112. package/dist/src/services/built-in/api-proxy/index.js +0 -23
  113. package/dist/src/services/built-in/code-develop/index.d.ts +0 -6
  114. package/dist/src/services/built-in/code-develop/index.js +0 -23
  115. package/dist/src/services/built-in/code-review/index.d.ts +0 -10
  116. package/dist/src/services/built-in/code-review/index.js +0 -51
  117. package/dist/src/services/built-in/image-analysis/index.d.ts +0 -6
  118. package/dist/src/services/built-in/image-analysis/index.js +0 -33
  119. package/dist/src/services/built-in/memory-store/index.d.ts +0 -6
  120. package/dist/src/services/built-in/memory-store/index.js +0 -22
  121. package/dist/src/services/built-in/roulette/index.d.ts +0 -6
  122. package/dist/src/services/built-in/roulette/index.js +0 -27
  123. package/dist/src/services/built-in/summarize/index.d.ts +0 -6
  124. package/dist/src/services/built-in/summarize/index.js +0 -21
  125. package/dist/src/services/built-in/tell-joke/handler.d.ts +0 -7
  126. package/dist/src/services/built-in/tell-joke/handler.js +0 -122
  127. package/dist/src/services/built-in/tell-joke/index.d.ts +0 -9
  128. package/dist/src/services/built-in/tell-joke/index.js +0 -31
  129. package/dist/src/services/built-in/translate/index.d.ts +0 -6
  130. package/dist/src/services/built-in/translate/index.js +0 -21
  131. package/dist/src/services/built-in/web-research/index.d.ts +0 -9
  132. package/dist/src/services/built-in/web-research/index.js +0 -51
  133. package/dist/src/services/index.d.ts +0 -13
  134. package/dist/src/services/index.js +0 -14
  135. package/dist/src/services/loader.d.ts +0 -77
  136. package/dist/src/services/loader.js +0 -292
  137. package/dist/src/services/manager.d.ts +0 -86
  138. package/dist/src/services/manager.js +0 -255
  139. package/dist/src/services/registry.d.ts +0 -98
  140. package/dist/src/services/registry.js +0 -204
  141. package/dist/src/services/types.d.ts +0 -230
  142. package/dist/src/services/types.js +0 -30
  143. package/dist/src/test/cli.test.d.ts +0 -7
  144. package/dist/src/test/cli.test.js +0 -330
  145. package/dist/src/test/comprehensive-overlay.test.d.ts +0 -13
  146. package/dist/src/test/comprehensive-overlay.test.js +0 -593
  147. package/dist/src/test/identity-consistency.test.d.ts +0 -6
  148. package/dist/src/test/identity-consistency.test.js +0 -60
  149. package/dist/src/test/key-derivation.test.d.ts +0 -12
  150. package/dist/src/test/key-derivation.test.js +0 -86
  151. package/dist/src/test/network-address.test.d.ts +0 -9
  152. package/dist/src/test/network-address.test.js +0 -37
  153. package/dist/src/test/overlay-submit.test.d.ts +0 -10
  154. package/dist/src/test/overlay-submit.test.js +0 -460
  155. package/dist/src/test/request-response-flow.test.d.ts +0 -5
  156. package/dist/src/test/request-response-flow.test.js +0 -210
  157. package/dist/src/test/service-system.test.d.ts +0 -5
  158. package/dist/src/test/service-system.test.js +0 -190
  159. package/dist/src/test/taskflow.test.d.ts +0 -7
  160. package/dist/src/test/taskflow.test.js +0 -82
  161. package/dist/src/test/utils/server-logic.d.ts +0 -98
  162. package/dist/src/test/utils/server-logic.js +0 -286
  163. package/dist/src/test/wallet.test.d.ts +0 -7
  164. package/dist/src/test/wallet.test.js +0 -146
  165. package/src/core/README.md +0 -246
  166. package/src/core/config.d.ts +0 -12
  167. package/src/core/config.d.ts.map +0 -1
  168. package/src/core/config.js +0 -14
  169. package/src/core/config.js.map +0 -1
  170. package/src/core/config.ts +0 -22
  171. package/src/core/index.ts +0 -42
  172. package/src/core/payment.d.ts +0 -17
  173. package/src/core/payment.d.ts.map +0 -1
  174. package/src/core/payment.js +0 -95
  175. package/src/core/payment.js.map +0 -1
  176. package/src/core/payment.ts +0 -111
  177. package/src/core/types.d.ts +0 -95
  178. package/src/core/types.d.ts.map +0 -1
  179. package/src/core/types.js +0 -5
  180. package/src/core/types.js.map +0 -1
  181. package/src/core/types.ts +0 -102
  182. package/src/core/verify.d.ts +0 -29
  183. package/src/core/verify.d.ts.map +0 -1
  184. package/src/core/verify.js +0 -105
  185. package/src/core/verify.js.map +0 -1
  186. package/src/core/verify.ts +0 -119
  187. package/src/core/wallet.d.ts +0 -100
  188. package/src/core/wallet.d.ts.map +0 -1
  189. package/src/core/wallet.js.map +0 -1
  190. package/src/core/wallet.ts +0 -323
@@ -1,26 +0,0 @@
1
- /**
2
- * WhatsOnChain API helpers with retry logic and rate limiting.
3
- */
4
- /**
5
- * Fetch from WhatsonChain with optional API key auth and retry logic.
6
- * Retries on 429 (rate limit) and 5xx errors with exponential backoff.
7
- * Includes timeout to prevent hanging indefinitely.
8
- */
9
- export declare function wocFetch(urlPath: string, options?: RequestInit, maxRetries?: number, timeoutMs?: number): Promise<Response>;
10
- /**
11
- * Fetch with timeout using AbortController.
12
- */
13
- export declare function fetchWithTimeout(url: string, options?: RequestInit, timeoutMs?: number): Promise<Response>;
14
- /**
15
- * Fetch a pre-built BEEF from WhatsonChain for a given txid.
16
- * WoC returns raw binary BEEF that includes the full source chain and merkle proofs.
17
- */
18
- export declare function fetchBeefFromWoC(txid: string): Promise<Uint8Array | null>;
19
- /**
20
- * Get the WoC base URL for the current network.
21
- */
22
- export declare function getWocBaseUrl(): string;
23
- /**
24
- * Get the explorer base URL for the current network.
25
- */
26
- export declare function getExplorerBaseUrl(): string;
@@ -1,91 +0,0 @@
1
- /**
2
- * WhatsOnChain API helpers with retry logic and rate limiting.
3
- */
4
- import { NETWORK, WOC_API_KEY } from '../config.js';
5
- /**
6
- * Fetch from WhatsonChain with optional API key auth and retry logic.
7
- * Retries on 429 (rate limit) and 5xx errors with exponential backoff.
8
- * Includes timeout to prevent hanging indefinitely.
9
- */
10
- export async function wocFetch(urlPath, options = {}, maxRetries = 3, timeoutMs = 30000) {
11
- const wocNet = NETWORK === 'mainnet' ? 'main' : 'test';
12
- const base = `https://api.whatsonchain.com/v1/bsv/${wocNet}`;
13
- const url = urlPath.startsWith('http') ? urlPath : `${base}${urlPath}`;
14
- const headers = { ...(options.headers || {}) };
15
- if (WOC_API_KEY) {
16
- headers['Authorization'] = `Bearer ${WOC_API_KEY}`;
17
- }
18
- let lastError;
19
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
20
- try {
21
- const controller = new AbortController();
22
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
23
- const resp = await fetch(url, { ...options, headers, signal: controller.signal });
24
- clearTimeout(timeout);
25
- // Retry on 429 (rate limit) or 5xx (server error)
26
- if ((resp.status === 429 || resp.status >= 500) && attempt < maxRetries) {
27
- const delayMs = Math.min(1000 * Math.pow(2, attempt), 8000);
28
- await new Promise(r => setTimeout(r, delayMs));
29
- continue;
30
- }
31
- return resp;
32
- }
33
- catch (err) {
34
- lastError = err;
35
- if (attempt < maxRetries) {
36
- const delayMs = Math.min(1000 * Math.pow(2, attempt), 8000);
37
- await new Promise(r => setTimeout(r, delayMs));
38
- continue;
39
- }
40
- }
41
- }
42
- throw lastError || new Error('WoC fetch failed after retries');
43
- }
44
- /**
45
- * Fetch with timeout using AbortController.
46
- */
47
- export async function fetchWithTimeout(url, options = {}, timeoutMs = 15000) {
48
- const controller = new AbortController();
49
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
50
- try {
51
- const resp = await fetch(url, { ...options, signal: controller.signal });
52
- return resp;
53
- }
54
- finally {
55
- clearTimeout(timeout);
56
- }
57
- }
58
- /**
59
- * Fetch a pre-built BEEF from WhatsonChain for a given txid.
60
- * WoC returns raw binary BEEF that includes the full source chain and merkle proofs.
61
- */
62
- export async function fetchBeefFromWoC(txid) {
63
- try {
64
- const resp = await wocFetch(`/tx/${txid}/beef`);
65
- if (!resp.ok)
66
- return null;
67
- const hexStr = (await resp.text()).trim();
68
- if (!hexStr || hexStr.length < 8)
69
- return null;
70
- const bytes = hexStr.match(/.{2}/g).map(h => parseInt(h, 16));
71
- return new Uint8Array(bytes);
72
- }
73
- catch {
74
- return null;
75
- }
76
- }
77
- /**
78
- * Get the WoC base URL for the current network.
79
- */
80
- export function getWocBaseUrl() {
81
- const wocNet = NETWORK === 'mainnet' ? 'main' : 'test';
82
- return `https://api.whatsonchain.com/v1/bsv/${wocNet}`;
83
- }
84
- /**
85
- * Get the explorer base URL for the current network.
86
- */
87
- export function getExplorerBaseUrl() {
88
- return NETWORK === 'mainnet'
89
- ? 'https://whatsonchain.com'
90
- : 'https://test.whatsonchain.com';
91
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Wallet balance commands: balance, import, refund.
3
- */
4
- /**
5
- * Balance command: show wallet balance.
6
- */
7
- export declare function cmdBalance(): Promise<any>;
8
- /**
9
- * Import command: import external UTXO with merkle proof.
10
- *
11
- * This function handles both confirmed and unconfirmed transactions.
12
- * For unconfirmed transactions, it uses BEEF from WoC which includes
13
- * the source chain back to confirmed ancestors (SPV-compliant).
14
- *
15
- * If the transaction isn't yet on WoC (just broadcast), it will poll
16
- * with exponential backoff for up to 60 seconds.
17
- */
18
- export declare function cmdImport(txidArg: string | undefined, voutStr?: string): Promise<any>;
19
- /**
20
- * Refund command: sweep wallet to an address.
21
- */
22
- export declare function cmdRefund(targetAddress: string | undefined): Promise<void>;
@@ -1,240 +0,0 @@
1
- /**
2
- * Wallet balance commands: balance, import, refund.
3
- */
4
- import fs from 'node:fs';
5
- import { NETWORK, WALLET_DIR, PATHS } from '../config.js';
6
- import { ok, fail } from '../output.js';
7
- import { wocFetch, fetchBeefFromWoC, getExplorerBaseUrl } from '../utils/woc.js';
8
- import { buildMerklePathFromTSC } from '../utils/merkle.js';
9
- import { BSVAgentWallet } from '../../core/index.js';
10
- async function getBSVAgentWallet() {
11
- return BSVAgentWallet;
12
- }
13
- // Dynamic import for @bsv/sdk
14
- let _sdk = null;
15
- async function getSdk() {
16
- if (_sdk)
17
- return _sdk;
18
- try {
19
- _sdk = await import('@bsv/sdk');
20
- return _sdk;
21
- }
22
- catch {
23
- const { fileURLToPath } = await import('node:url');
24
- const path = await import('node:path');
25
- const os = await import('node:os');
26
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
- const candidates = [
28
- path.resolve(__dirname, '..', '..', '..', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
29
- path.resolve(__dirname, '..', '..', '..', '..', '..', 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
30
- path.resolve(os.homedir(), 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
31
- ];
32
- for (const p of candidates) {
33
- try {
34
- _sdk = await import(p);
35
- return _sdk;
36
- }
37
- catch {
38
- // Try next
39
- }
40
- }
41
- throw new Error('Cannot find @bsv/sdk. Run setup.sh first.');
42
- }
43
- }
44
- /**
45
- * Sleep helper for polling
46
- */
47
- function sleep(ms) {
48
- return new Promise(resolve => setTimeout(resolve, ms));
49
- }
50
- /**
51
- * Balance command: show wallet balance.
52
- */
53
- export async function cmdBalance() {
54
- const BSVAgentWallet = await getBSVAgentWallet();
55
- const sdk = await getSdk();
56
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
57
- const total = await wallet.getBalance();
58
- await wallet.destroy();
59
- return ok({ walletBalance: total });
60
- }
61
- /**
62
- * Import command: import external UTXO with merkle proof.
63
- *
64
- * This function handles both confirmed and unconfirmed transactions.
65
- * For unconfirmed transactions, it uses BEEF from WoC which includes
66
- * the source chain back to confirmed ancestors (SPV-compliant).
67
- *
68
- * If the transaction isn't yet on WoC (just broadcast), it will poll
69
- * with exponential backoff for up to 60 seconds.
70
- */
71
- export async function cmdImport(txidArg, voutStr) {
72
- if (!txidArg) {
73
- return fail('Usage: import <txid> [vout]');
74
- }
75
- const vout = parseInt(voutStr || '0', 10);
76
- const txid = txidArg.toLowerCase();
77
- if (!/^[0-9a-f]{64}$/.test(txid)) {
78
- return fail('Invalid txid — must be 64 hex characters');
79
- }
80
- const sdk = await getSdk();
81
- const BSVAgentWallet = await getBSVAgentWallet();
82
- // Poll for transaction on WoC with exponential backoff
83
- // This handles the case where user just broadcast and WoC hasn't indexed yet
84
- let txInfo = null;
85
- const maxWaitMs = 60000; // 60 seconds max
86
- const startTime = Date.now();
87
- let attempt = 0;
88
- while (Date.now() - startTime < maxWaitMs) {
89
- const txInfoResp = await wocFetch(`/tx/${txid}`, {}, 1, 10000); // Single retry, 10s timeout
90
- if (txInfoResp.ok) {
91
- txInfo = await txInfoResp.json();
92
- break;
93
- }
94
- else if (txInfoResp.status === 404) {
95
- // Transaction not found yet - wait and retry
96
- attempt++;
97
- const delayMs = Math.min(1000 * Math.pow(1.5, attempt), 10000); // 1s, 1.5s, 2.25s, ... max 10s
98
- console.error(`[import] Transaction not on WoC yet, waiting ${Math.round(delayMs / 1000)}s... (attempt ${attempt})`);
99
- await sleep(delayMs);
100
- continue;
101
- }
102
- else {
103
- return fail(`Failed to fetch tx info: ${txInfoResp.status}`);
104
- }
105
- }
106
- if (!txInfo) {
107
- return fail(`Transaction ${txid} not found on WhatsOnChain after ${Math.round((Date.now() - startTime) / 1000)}s. The transaction may not have been broadcast yet, or the txid may be incorrect.`);
108
- }
109
- const isConfirmed = txInfo.confirmations && txInfo.confirmations >= 1;
110
- const blockHeight = txInfo.blockheight;
111
- // Validate output exists
112
- if (!txInfo.vout || !txInfo.vout[vout]) {
113
- return fail(`Output index ${vout} not found in transaction (has ${txInfo.vout?.length || 0} outputs)`);
114
- }
115
- let atomicBeefBytes;
116
- // Try WoC BEEF first - works for both confirmed and unconfirmed transactions
117
- // WoC provides BEEF with full source chain back to confirmed ancestors
118
- const wocBeefBytes = await fetchBeefFromWoC(txid);
119
- if (wocBeefBytes) {
120
- try {
121
- const wocBeef = sdk.Beef.fromBinary(Array.from(wocBeefBytes));
122
- const foundTx = wocBeef.findTxid(txid);
123
- if (foundTx) {
124
- // Verify the output exists in the parsed tx
125
- const txObj = foundTx.tx || foundTx._tx;
126
- if (txObj) {
127
- const output = txObj.outputs[vout];
128
- if (!output) {
129
- return fail(`Output index ${vout} not found in BEEF transaction (has ${txObj.outputs.length} outputs)`);
130
- }
131
- }
132
- atomicBeefBytes = wocBeef.toBinaryAtomic(txid);
133
- }
134
- }
135
- catch (beefErr) {
136
- console.error(`[import] WoC BEEF parse failed: ${beefErr.message}`);
137
- // Fall through to manual construction
138
- }
139
- }
140
- // Fallback for confirmed txs: construct BEEF manually using TSC merkle proof
141
- if (!atomicBeefBytes && isConfirmed) {
142
- try {
143
- const rawTxResp = await wocFetch(`/tx/${txid}/hex`);
144
- if (!rawTxResp.ok) {
145
- return fail(`Failed to fetch raw transaction: ${rawTxResp.status}`);
146
- }
147
- const rawTxHex = await rawTxResp.text();
148
- const sourceTx = sdk.Transaction.fromHex(rawTxHex.trim());
149
- const proofResp = await wocFetch(`/tx/${txid}/proof/tsc`);
150
- if (!proofResp.ok) {
151
- return fail(`Failed to fetch merkle proof: ${proofResp.status}`);
152
- }
153
- const proofData = await proofResp.json();
154
- if (!Array.isArray(proofData) || proofData.length === 0) {
155
- return fail('Merkle proof not available from WoC');
156
- }
157
- const proof = proofData[0];
158
- const merklePath = await buildMerklePathFromTSC(txid, proof.index, proof.nodes, blockHeight);
159
- sourceTx.merklePath = merklePath;
160
- const beef = new sdk.Beef();
161
- beef.mergeTransaction(sourceTx);
162
- atomicBeefBytes = beef.toBinaryAtomic(txid);
163
- }
164
- catch (manualErr) {
165
- return fail(`Failed to construct BEEF manually: ${manualErr.message}`);
166
- }
167
- }
168
- // If still no BEEF, we can't import
169
- if (!atomicBeefBytes) {
170
- if (isConfirmed) {
171
- return fail(`Transaction ${txid} is confirmed but BEEF construction failed. This is unexpected — please report this issue.`);
172
- }
173
- else {
174
- // Unconfirmed and no BEEF available
175
- // This can happen if the funding tx itself spends unconfirmed inputs
176
- return fail(`Transaction ${txid} is unconfirmed (${txInfo.confirmations || 0} confirmations) and BEEF is not available.\n\n` +
177
- `This usually means the funding transaction spends from other unconfirmed transactions, creating a chain.\n` +
178
- `Wait for 1 block confirmation (~10 minutes) and try again, or use a fresh UTXO as the funding source.`);
179
- }
180
- }
181
- // Get output satoshis for reporting
182
- const outputSatoshis = txInfo.vout[vout].value != null
183
- ? Math.round(txInfo.vout[vout].value * 1e8)
184
- : undefined;
185
- // Import into wallet
186
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
187
- const identityKey = await wallet.getIdentityKey();
188
- try {
189
- await wallet._setup.wallet.storage.internalizeAction({
190
- tx: Array.from(atomicBeefBytes),
191
- outputs: [{
192
- outputIndex: vout,
193
- protocol: 'wallet payment',
194
- paymentRemittance: {
195
- derivationPrefix: sdk.Utils.toBase64(sdk.Utils.toArray('import', 'utf8')),
196
- derivationSuffix: sdk.Utils.toBase64(sdk.Utils.toArray('now', 'utf8')),
197
- senderIdentityKey: identityKey,
198
- },
199
- }],
200
- description: 'External funding import',
201
- });
202
- const balance = await wallet.getBalance();
203
- await wallet.destroy();
204
- const explorerBase = getExplorerBaseUrl();
205
- return ok({
206
- txid,
207
- vout,
208
- satoshis: outputSatoshis,
209
- blockHeight: blockHeight || null,
210
- confirmations: txInfo.confirmations || 0,
211
- imported: true,
212
- unconfirmed: !isConfirmed,
213
- balance,
214
- explorer: `${explorerBase}/tx/${txid}`,
215
- });
216
- }
217
- catch (err) {
218
- await wallet.destroy();
219
- // Provide helpful error messages for common issues
220
- if (err.message?.includes('already') || err.message?.includes('duplicate')) {
221
- return fail(`UTXO ${txid}:${vout} appears to already be imported.`);
222
- }
223
- if (err.message?.includes('script') || err.message?.includes('locking')) {
224
- return fail(`UTXO ${txid}:${vout} does not belong to this wallet's address. Make sure you sent to the correct address.`);
225
- }
226
- return fail(`Failed to import UTXO: ${err.message}`);
227
- }
228
- }
229
- /**
230
- * Refund command: sweep wallet to an address.
231
- */
232
- export async function cmdRefund(targetAddress) {
233
- if (!targetAddress) {
234
- return fail('Usage: refund <address>');
235
- }
236
- if (!fs.existsSync(PATHS.walletIdentity)) {
237
- return fail('Wallet not initialized. Run: setup');
238
- }
239
- // TODO IMPLEMENT THIS
240
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * Wallet identity helpers.
3
- */
4
- import type { WalletIdentity } from '../types.js';
5
- /**
6
- * Load wallet identity from disk.
7
- * @returns Identity object with rootKeyHex and identityKey
8
- * @throws Error if wallet not initialized
9
- */
10
- export declare function loadWalletIdentity(): WalletIdentity;
11
- /**
12
- * Load identity and private key for relay message signing.
13
- * @returns Object with identityKey and privKey
14
- */
15
- export declare function loadIdentity(): Promise<{
16
- identityKey: string;
17
- privKey: any;
18
- }>;
19
- /**
20
- * Sign a relay message using ECDSA.
21
- * @param privKey - Private key for signing
22
- * @param to - Recipient's identity key
23
- * @param type - Message type
24
- * @param payload - Message payload
25
- * @returns Hex-encoded DER signature
26
- */
27
- export declare function signRelayMessage(privKey: any, to: string, type: string, payload: unknown): Promise<string>;
28
- /**
29
- * Verify a relay message signature.
30
- * @param fromKey - Sender's public key
31
- * @param to - Recipient's identity key
32
- * @param type - Message type
33
- * @param payload - Message payload
34
- * @param signatureHex - Hex-encoded DER signature
35
- * @returns Verification result
36
- */
37
- export declare function verifyRelaySignature(fromKey: string, to: string, type: string, payload: unknown, signatureHex: string | undefined): Promise<{
38
- valid: boolean;
39
- reason?: string;
40
- }>;
41
- /**
42
- * Derive wallet address components from a private key.
43
- *
44
- * IMPORTANT: This uses BRC-29 key derivation to create a child key.
45
- * Any transactions spending to this address MUST use the matching
46
- * child private key for signing, NOT the root key.
47
- *
48
- * Use deriveWalletKeys() to get both the address and signing key.
49
- */
50
- export declare function deriveWalletAddress(privKey: any, network?: string): Promise<{
51
- address: string;
52
- hash160: Uint8Array;
53
- pubKey: any;
54
- }>;
55
- /**
56
- * Derive wallet keys for both address AND transaction signing.
57
- *
58
- * CRITICAL: Use this function to get the child private key for signing
59
- * transactions that spend from the derived address. Do NOT use the
60
- * root private key - it will cause signature verification failures!
61
- *
62
- * @param rootPrivKey - Root private key from wallet identity
63
- * @param network - Optional network override
64
- * @returns Object with address, hash160, and CHILD private key for signing
65
- */
66
- export declare function deriveWalletKeys(rootPrivKey: any, network?: string): Promise<{
67
- address: string;
68
- hash160: Uint8Array;
69
- pubKey: any;
70
- childPrivKey: any;
71
- }>;
@@ -1,152 +0,0 @@
1
- /**
2
- * Wallet identity helpers.
3
- */
4
- import fs from 'node:fs';
5
- import { PATHS, NETWORK } from '../config.js';
6
- import { CachedKeyDeriver, Utils } from '@bsv/sdk';
7
- import { brc29ProtocolID } from '@bsv/wallet-toolbox';
8
- // Dynamic import for @bsv/sdk
9
- let _sdk = null;
10
- async function getSdk() {
11
- if (_sdk)
12
- return _sdk;
13
- try {
14
- _sdk = await import('@bsv/sdk');
15
- return _sdk;
16
- }
17
- catch {
18
- const { fileURLToPath } = await import('node:url');
19
- const path = await import('node:path');
20
- const os = await import('node:os');
21
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
22
- const candidates = [
23
- path.resolve(__dirname, '..', '..', '..', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
24
- path.resolve(__dirname, '..', '..', '..', '..', '..', 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
25
- path.resolve(os.homedir(), 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
26
- ];
27
- for (const p of candidates) {
28
- try {
29
- _sdk = await import(p);
30
- return _sdk;
31
- }
32
- catch {
33
- // Try next
34
- }
35
- }
36
- throw new Error('Cannot find @bsv/sdk. Run setup.sh first.');
37
- }
38
- }
39
- /**
40
- * Load wallet identity from disk.
41
- * @returns Identity object with rootKeyHex and identityKey
42
- * @throws Error if wallet not initialized
43
- */
44
- export function loadWalletIdentity() {
45
- if (!fs.existsSync(PATHS.walletIdentity)) {
46
- throw new Error('Wallet not initialized. Run: cli setup');
47
- }
48
- // Security warning for overly permissive file mode
49
- try {
50
- const fileMode = fs.statSync(PATHS.walletIdentity).mode & 0o777;
51
- if (fileMode & 0o044) { // world or group readable
52
- console.error(`[security] WARNING: ${PATHS.walletIdentity} has permissive mode 0${fileMode.toString(8)}. Run: chmod 600 ${PATHS.walletIdentity}`);
53
- }
54
- }
55
- catch {
56
- // Ignore stat errors
57
- }
58
- return JSON.parse(fs.readFileSync(PATHS.walletIdentity, 'utf-8'));
59
- }
60
- /**
61
- * Load identity and private key for relay message signing.
62
- * @returns Object with identityKey and privKey
63
- */
64
- export async function loadIdentity() {
65
- const identity = loadWalletIdentity();
66
- const sdk = await getSdk();
67
- const privKey = sdk.PrivateKey.fromHex(identity.rootKeyHex);
68
- return { identityKey: identity.identityKey, privKey };
69
- }
70
- /**
71
- * Sign a relay message using ECDSA.
72
- * @param privKey - Private key for signing
73
- * @param to - Recipient's identity key
74
- * @param type - Message type
75
- * @param payload - Message payload
76
- * @returns Hex-encoded DER signature
77
- */
78
- export async function signRelayMessage(privKey, to, type, payload) {
79
- const sdk = await getSdk();
80
- const preimage = to + type + JSON.stringify(payload);
81
- const msgHash = sdk.Hash.sha256(Array.from(new TextEncoder().encode(preimage)));
82
- const sig = privKey.sign(msgHash);
83
- return Array.from(sig.toDER()).map((b) => b.toString(16).padStart(2, '0')).join('');
84
- }
85
- /**
86
- * Verify a relay message signature.
87
- * @param fromKey - Sender's public key
88
- * @param to - Recipient's identity key
89
- * @param type - Message type
90
- * @param payload - Message payload
91
- * @param signatureHex - Hex-encoded DER signature
92
- * @returns Verification result
93
- */
94
- export async function verifyRelaySignature(fromKey, to, type, payload, signatureHex) {
95
- if (!signatureHex)
96
- return { valid: false, reason: 'no signature' };
97
- try {
98
- const sdk = await getSdk();
99
- const preimage = to + type + JSON.stringify(payload);
100
- const msgHash = sdk.Hash.sha256(Array.from(new TextEncoder().encode(preimage)));
101
- const sigBytes = [];
102
- for (let i = 0; i < signatureHex.length; i += 2) {
103
- sigBytes.push(parseInt(signatureHex.substring(i, i + 2), 16));
104
- }
105
- const sig = sdk.Signature.fromDER(sigBytes);
106
- const pubKey = sdk.PublicKey.fromString(fromKey);
107
- return { valid: pubKey.verify(msgHash, sig) };
108
- }
109
- catch (err) {
110
- return { valid: false, reason: String(err) };
111
- }
112
- }
113
- /**
114
- * Derive wallet address components from a private key.
115
- *
116
- * IMPORTANT: This uses BRC-29 key derivation to create a child key.
117
- * Any transactions spending to this address MUST use the matching
118
- * child private key for signing, NOT the root key.
119
- *
120
- * Use deriveWalletKeys() to get both the address and signing key.
121
- */
122
- export async function deriveWalletAddress(privKey, network = NETWORK) {
123
- const keyDeriver = new CachedKeyDeriver(privKey);
124
- const pubKey = keyDeriver.derivePublicKey(brc29ProtocolID, Utils.toBase64(Utils.toArray('import')) + ' ' + Utils.toBase64(Utils.toArray('now')), 'self', true);
125
- const address = pubKey.toAddress(network);
126
- const hash160 = Buffer.from(pubKey.toHash());
127
- return { address, hash160, pubKey };
128
- }
129
- /**
130
- * Derive wallet keys for both address AND transaction signing.
131
- *
132
- * CRITICAL: Use this function to get the child private key for signing
133
- * transactions that spend from the derived address. Do NOT use the
134
- * root private key - it will cause signature verification failures!
135
- *
136
- * @param rootPrivKey - Root private key from wallet identity
137
- * @param network - Optional network override
138
- * @returns Object with address, hash160, and CHILD private key for signing
139
- */
140
- export async function deriveWalletKeys(rootPrivKey, network = NETWORK) {
141
- const keyDeriver = new CachedKeyDeriver(rootPrivKey);
142
- const derivationPrefix = Utils.toBase64(Utils.toArray('import'));
143
- const derivationSuffix = Utils.toBase64(Utils.toArray('now'));
144
- const keyString = `${derivationPrefix} ${derivationSuffix}`;
145
- // Derive child private key (for signing)
146
- const childPrivKey = keyDeriver.derivePrivateKey(brc29ProtocolID, keyString, 'self');
147
- // Derive child public key (for address)
148
- const pubKey = keyDeriver.derivePublicKey(brc29ProtocolID, keyString, 'self', true);
149
- const address = pubKey.toAddress(network);
150
- const hash160 = Buffer.from(pubKey.toHash());
151
- return { address, hash160, pubKey, childPrivKey };
152
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Wallet module exports.
3
- */
4
- export * from './identity.js';
5
- export * from './setup.js';
6
- export * from './balance.js';
@@ -1,6 +0,0 @@
1
- /**
2
- * Wallet module exports.
3
- */
4
- export * from './identity.js';
5
- export * from './setup.js';
6
- export * from './balance.js';
@@ -1,19 +0,0 @@
1
- /**
2
- * Wallet setup commands: setup, identity, address.
3
- */
4
- /**
5
- * Setup command: create wallet and show identity.
6
- */
7
- export declare function cmdSetup(): Promise<any>;
8
- /**
9
- * Identity command: show identity public key.
10
- */
11
- export declare function cmdIdentity(): Promise<any>;
12
- /**
13
- * Status command: show identity and balance.
14
- */
15
- export declare function cmdStatus(): Promise<any>;
16
- /**
17
- * Address command: show P2PKH receive address.
18
- */
19
- export declare function cmdAddress(): Promise<any>;