openclaw-overlay-plugin 0.7.34 → 0.7.35

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 (144) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +13 -2
  3. package/dist/src/scripts/config.d.ts +1 -1
  4. package/dist/src/scripts/config.js +1 -1
  5. package/index.ts +15 -2
  6. package/openclaw.plugin.json +2 -1
  7. package/package.json +1 -1
  8. package/src/scripts/config.ts +1 -1
  9. package/dist/cli-main.d.ts +0 -7
  10. package/dist/cli-main.js +0 -192
  11. package/dist/cli.d.ts +0 -8
  12. package/dist/cli.js +0 -14
  13. package/dist/core/config.d.ts +0 -11
  14. package/dist/core/config.js +0 -13
  15. package/dist/core/index.d.ts +0 -25
  16. package/dist/core/index.js +0 -26
  17. package/dist/core/payment.d.ts +0 -16
  18. package/dist/core/payment.js +0 -94
  19. package/dist/core/types.d.ts +0 -94
  20. package/dist/core/types.js +0 -4
  21. package/dist/core/verify.d.ts +0 -28
  22. package/dist/core/verify.js +0 -104
  23. package/dist/core/wallet.d.ts +0 -99
  24. package/dist/core/wallet.js +0 -219
  25. package/dist/scripts/baemail/commands.d.ts +0 -64
  26. package/dist/scripts/baemail/commands.js +0 -259
  27. package/dist/scripts/baemail/handler.d.ts +0 -36
  28. package/dist/scripts/baemail/handler.js +0 -284
  29. package/dist/scripts/baemail/index.d.ts +0 -5
  30. package/dist/scripts/baemail/index.js +0 -5
  31. package/dist/scripts/config.d.ts +0 -48
  32. package/dist/scripts/config.js +0 -68
  33. package/dist/scripts/index.d.ts +0 -7
  34. package/dist/scripts/index.js +0 -7
  35. package/dist/scripts/messaging/connect.d.ts +0 -8
  36. package/dist/scripts/messaging/connect.js +0 -114
  37. package/dist/scripts/messaging/handlers.d.ts +0 -21
  38. package/dist/scripts/messaging/handlers.js +0 -334
  39. package/dist/scripts/messaging/inbox.d.ts +0 -11
  40. package/dist/scripts/messaging/inbox.js +0 -51
  41. package/dist/scripts/messaging/index.d.ts +0 -8
  42. package/dist/scripts/messaging/index.js +0 -8
  43. package/dist/scripts/messaging/poll.d.ts +0 -7
  44. package/dist/scripts/messaging/poll.js +0 -52
  45. package/dist/scripts/messaging/send.d.ts +0 -7
  46. package/dist/scripts/messaging/send.js +0 -43
  47. package/dist/scripts/output.d.ts +0 -12
  48. package/dist/scripts/output.js +0 -19
  49. package/dist/scripts/overlay/discover.d.ts +0 -7
  50. package/dist/scripts/overlay/discover.js +0 -72
  51. package/dist/scripts/overlay/index.d.ts +0 -7
  52. package/dist/scripts/overlay/index.js +0 -7
  53. package/dist/scripts/overlay/registration.d.ts +0 -19
  54. package/dist/scripts/overlay/registration.js +0 -176
  55. package/dist/scripts/overlay/services.d.ts +0 -29
  56. package/dist/scripts/overlay/services.js +0 -167
  57. package/dist/scripts/overlay/transaction.d.ts +0 -42
  58. package/dist/scripts/overlay/transaction.js +0 -103
  59. package/dist/scripts/payment/build.d.ts +0 -24
  60. package/dist/scripts/payment/build.js +0 -54
  61. package/dist/scripts/payment/commands.d.ts +0 -15
  62. package/dist/scripts/payment/commands.js +0 -73
  63. package/dist/scripts/payment/index.d.ts +0 -6
  64. package/dist/scripts/payment/index.js +0 -6
  65. package/dist/scripts/payment/types.d.ts +0 -56
  66. package/dist/scripts/payment/types.js +0 -4
  67. package/dist/scripts/services/index.d.ts +0 -6
  68. package/dist/scripts/services/index.js +0 -6
  69. package/dist/scripts/services/queue.d.ts +0 -11
  70. package/dist/scripts/services/queue.js +0 -28
  71. package/dist/scripts/services/request.d.ts +0 -7
  72. package/dist/scripts/services/request.js +0 -82
  73. package/dist/scripts/services/respond.d.ts +0 -11
  74. package/dist/scripts/services/respond.js +0 -132
  75. package/dist/scripts/types.d.ts +0 -107
  76. package/dist/scripts/types.js +0 -4
  77. package/dist/scripts/utils/index.d.ts +0 -6
  78. package/dist/scripts/utils/index.js +0 -6
  79. package/dist/scripts/utils/merkle.d.ts +0 -12
  80. package/dist/scripts/utils/merkle.js +0 -47
  81. package/dist/scripts/utils/storage.d.ts +0 -66
  82. package/dist/scripts/utils/storage.js +0 -211
  83. package/dist/scripts/utils/woc.d.ts +0 -26
  84. package/dist/scripts/utils/woc.js +0 -91
  85. package/dist/scripts/wallet/balance.d.ts +0 -22
  86. package/dist/scripts/wallet/balance.js +0 -240
  87. package/dist/scripts/wallet/identity.d.ts +0 -70
  88. package/dist/scripts/wallet/identity.js +0 -151
  89. package/dist/scripts/wallet/index.d.ts +0 -6
  90. package/dist/scripts/wallet/index.js +0 -6
  91. package/dist/scripts/wallet/setup.d.ts +0 -15
  92. package/dist/scripts/wallet/setup.js +0 -105
  93. package/dist/scripts/x-verification/commands.d.ts +0 -27
  94. package/dist/scripts/x-verification/commands.js +0 -222
  95. package/dist/scripts/x-verification/index.d.ts +0 -4
  96. package/dist/scripts/x-verification/index.js +0 -4
  97. package/dist/services/built-in/api-proxy/index.d.ts +0 -6
  98. package/dist/services/built-in/api-proxy/index.js +0 -23
  99. package/dist/services/built-in/code-develop/index.d.ts +0 -6
  100. package/dist/services/built-in/code-develop/index.js +0 -23
  101. package/dist/services/built-in/code-review/index.d.ts +0 -10
  102. package/dist/services/built-in/code-review/index.js +0 -51
  103. package/dist/services/built-in/image-analysis/index.d.ts +0 -6
  104. package/dist/services/built-in/image-analysis/index.js +0 -33
  105. package/dist/services/built-in/memory-store/index.d.ts +0 -6
  106. package/dist/services/built-in/memory-store/index.js +0 -22
  107. package/dist/services/built-in/roulette/index.d.ts +0 -6
  108. package/dist/services/built-in/roulette/index.js +0 -27
  109. package/dist/services/built-in/summarize/index.d.ts +0 -6
  110. package/dist/services/built-in/summarize/index.js +0 -21
  111. package/dist/services/built-in/tell-joke/handler.d.ts +0 -7
  112. package/dist/services/built-in/tell-joke/handler.js +0 -122
  113. package/dist/services/built-in/tell-joke/index.d.ts +0 -9
  114. package/dist/services/built-in/tell-joke/index.js +0 -31
  115. package/dist/services/built-in/translate/index.d.ts +0 -6
  116. package/dist/services/built-in/translate/index.js +0 -21
  117. package/dist/services/built-in/web-research/index.d.ts +0 -9
  118. package/dist/services/built-in/web-research/index.js +0 -51
  119. package/dist/services/index.d.ts +0 -13
  120. package/dist/services/index.js +0 -14
  121. package/dist/services/loader.d.ts +0 -77
  122. package/dist/services/loader.js +0 -292
  123. package/dist/services/manager.d.ts +0 -86
  124. package/dist/services/manager.js +0 -255
  125. package/dist/services/registry.d.ts +0 -98
  126. package/dist/services/registry.js +0 -204
  127. package/dist/services/types.d.ts +0 -230
  128. package/dist/services/types.js +0 -30
  129. package/dist/test/cli.test.d.ts +0 -7
  130. package/dist/test/cli.test.js +0 -329
  131. package/dist/test/comprehensive-overlay.test.d.ts +0 -13
  132. package/dist/test/comprehensive-overlay.test.js +0 -593
  133. package/dist/test/key-derivation.test.d.ts +0 -12
  134. package/dist/test/key-derivation.test.js +0 -86
  135. package/dist/test/overlay-submit.test.d.ts +0 -10
  136. package/dist/test/overlay-submit.test.js +0 -460
  137. package/dist/test/request-response-flow.test.d.ts +0 -5
  138. package/dist/test/request-response-flow.test.js +0 -209
  139. package/dist/test/service-system.test.d.ts +0 -5
  140. package/dist/test/service-system.test.js +0 -190
  141. package/dist/test/utils/server-logic.d.ts +0 -98
  142. package/dist/test/utils/server-logic.js +0 -286
  143. package/dist/test/wallet.test.d.ts +0 -7
  144. package/dist/test/wallet.test.js +0 -146
@@ -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,70 +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): 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
- * @returns Object with address, hash160, and CHILD private key for signing
64
- */
65
- export declare function deriveWalletKeys(rootPrivKey: any): Promise<{
66
- address: string;
67
- hash160: Uint8Array;
68
- pubKey: any;
69
- childPrivKey: any;
70
- }>;
@@ -1,151 +0,0 @@
1
- /**
2
- * Wallet identity helpers.
3
- */
4
- import fs from 'node:fs';
5
- import { PATHS } 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) {
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();
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
- * @returns Object with address, hash160, and CHILD private key for signing
138
- */
139
- export async function deriveWalletKeys(rootPrivKey) {
140
- const keyDeriver = new CachedKeyDeriver(rootPrivKey);
141
- const derivationPrefix = Utils.toBase64(Utils.toArray('import'));
142
- const derivationSuffix = Utils.toBase64(Utils.toArray('now'));
143
- const keyString = `${derivationPrefix} ${derivationSuffix}`;
144
- // Derive child private key (for signing)
145
- const childPrivKey = keyDeriver.derivePrivateKey(brc29ProtocolID, keyString, 'self');
146
- // Derive child public key (for address)
147
- const pubKey = keyDeriver.derivePublicKey(brc29ProtocolID, keyString, 'self', true);
148
- const address = pubKey.toAddress();
149
- const hash160 = Buffer.from(pubKey.toHash());
150
- return { address, hash160, pubKey, childPrivKey };
151
- }
@@ -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,15 +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<never>;
8
- /**
9
- * Identity command: show identity public key.
10
- */
11
- export declare function cmdIdentity(): Promise<never>;
12
- /**
13
- * Address command: show P2PKH receive address.
14
- */
15
- export declare function cmdAddress(): Promise<never>;
@@ -1,105 +0,0 @@
1
- /**
2
- * Wallet setup commands: setup, identity, address.
3
- */
4
- import fs from 'node:fs';
5
- import { NETWORK, WALLET_DIR, OVERLAY_URL, PATHS } from '../config.js';
6
- import { ok, fail } from '../output.js';
7
- import { loadWalletIdentity, deriveWalletAddress } from './identity.js';
8
- import { BSVAgentWallet } from '../../core/index.js';
9
- async function getBSVAgentWallet() {
10
- return BSVAgentWallet;
11
- }
12
- // Dynamic import for @bsv/sdk
13
- let _sdk = null;
14
- async function getSdk() {
15
- if (_sdk)
16
- return _sdk;
17
- try {
18
- _sdk = await import('@bsv/sdk');
19
- return _sdk;
20
- }
21
- catch {
22
- const { fileURLToPath } = await import('node:url');
23
- const path = await import('node:path');
24
- const os = await import('node:os');
25
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
- const candidates = [
27
- path.resolve(__dirname, '..', '..', '..', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
28
- path.resolve(__dirname, '..', '..', '..', '..', '..', 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
29
- path.resolve(os.homedir(), 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
30
- ];
31
- for (const p of candidates) {
32
- try {
33
- _sdk = await import(p);
34
- return _sdk;
35
- }
36
- catch {
37
- // Try next
38
- }
39
- }
40
- throw new Error('Cannot find @bsv/sdk. Run setup.sh first.');
41
- }
42
- }
43
- /**
44
- * Setup command: create wallet and show identity.
45
- */
46
- export async function cmdSetup() {
47
- const BSVAgentWallet = await getBSVAgentWallet();
48
- if (fs.existsSync(PATHS.walletIdentity)) {
49
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
50
- const identityKey = await wallet.getIdentityKey();
51
- await wallet.destroy();
52
- return ok({
53
- identityKey,
54
- walletDir: WALLET_DIR,
55
- network: NETWORK,
56
- overlayUrl: OVERLAY_URL,
57
- alreadyExisted: true,
58
- });
59
- }
60
- fs.mkdirSync(WALLET_DIR, { recursive: true });
61
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
62
- const identityKey = await wallet.getIdentityKey();
63
- await wallet.destroy();
64
- // Restrict permissions on wallet-identity.json (contains private key)
65
- if (fs.existsSync(PATHS.walletIdentity)) {
66
- fs.chmodSync(PATHS.walletIdentity, 0o600);
67
- }
68
- return ok({
69
- identityKey,
70
- walletDir: WALLET_DIR,
71
- network: NETWORK,
72
- overlayUrl: OVERLAY_URL,
73
- alreadyExisted: false,
74
- });
75
- }
76
- /**
77
- * Identity command: show identity public key.
78
- */
79
- export async function cmdIdentity() {
80
- const BSVAgentWallet = await getBSVAgentWallet();
81
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
82
- const identityKey = await wallet.getIdentityKey();
83
- await wallet.destroy();
84
- return ok({ identityKey });
85
- }
86
- /**
87
- * Address command: show P2PKH receive address.
88
- */
89
- export async function cmdAddress() {
90
- if (!fs.existsSync(PATHS.walletIdentity)) {
91
- return fail('Wallet not initialized. Run: setup');
92
- }
93
- const sdk = await getSdk();
94
- const identity = loadWalletIdentity();
95
- const privKey = sdk.PrivateKey.fromHex(identity.rootKeyHex);
96
- const { address } = await deriveWalletAddress(privKey);
97
- return ok({
98
- address,
99
- network: NETWORK,
100
- identityKey: identity.identityKey,
101
- note: NETWORK === 'mainnet'
102
- ? `Fund this address at an exchange — Explorer: https://whatsonchain.com/address/${address}`
103
- : `Fund via faucet: https://witnessonchain.com/faucet/tbsv — Explorer: https://test.whatsonchain.com/address/${address}`,
104
- });
105
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * X (Twitter) verification commands.
3
- */
4
- /**
5
- * Start X verification: generate a tweet with identity key and signature.
6
- */
7
- export declare function cmdXVerifyStart(handleArg: string | undefined): Promise<never>;
8
- /**
9
- * Complete X verification by checking the posted tweet.
10
- */
11
- export declare function cmdXVerifyComplete(tweetUrl: string | undefined): Promise<never>;
12
- /**
13
- * List verified X accounts (local cache).
14
- */
15
- export declare function cmdXVerifications(): Promise<never>;
16
- /**
17
- * Lookup X verifications from the overlay network.
18
- */
19
- export declare function cmdXLookup(query: string | undefined): Promise<never>;
20
- /**
21
- * List pending X engagement requests.
22
- */
23
- export declare function cmdXEngagementQueue(): Promise<never>;
24
- /**
25
- * Mark an X engagement request as fulfilled.
26
- */
27
- export declare function cmdXEngagementFulfill(requestId: string | undefined, proofUrl?: string): Promise<never>;