nimbill-mcp 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -56,6 +56,7 @@ Running from a clone of this repo instead? Use `"command": "node"` with `"args":
56
56
  - **Keep only small amounts in the agent wallet.** Anything that can run the agent can spend from it.
57
57
  - **Encrypt the key.** Without `NIMBILL_WALLET_PASSPHRASE` the key is stored in plain text. On Windows the file's owner-only mode has no effect, so other programs running as you can read it.
58
58
  - **Spending limits** stop a single call, or a run of calls, from draining the wallet. They are enforced locally and logged in `spend-log.json` next to the wallet file.
59
+ - **Tags are checked locally.** `lookup_tag` and `send_to_tag` check the tag owner's wallet signature on your machine, so a wallet address swapped in on NimBill's side is refused. Tags whose owners haven't signed yet show `confirmedByOwner: false`.
59
60
  - **`buy_from_board` doesn't pay unless `payNow: true`**, and the paying tools are marked `destructiveHint` so MCP clients can ask before running them.
60
61
  - **Cheque secrets are saved** in `cheques.json` next to the wallet file before a cheque is funded, so the agent can always cancel cheques it wrote (`cancel_cheque` accepts just the cheque number).
61
62
 
@@ -66,8 +67,8 @@ Running from a clone of this repo instead? Use `"command": "node"` with `"args":
66
67
  | Tool | Description |
67
68
  | ---------------- | -------------------------------------------------------------------------------------------------------- |
68
69
  | `wallet_status` | Check the agent's `NQ…` address, live on-chain NIM balance, and NimBill `@tag` profile |
69
- | `setup_profile` | Set the agent's display name, bio, default currency, and claim a `@tag` |
70
- | `lookup_tag` | Resolve any `tag@nimbill` to its owner's name, Nimiq address, and avatar |
70
+ | `setup_profile` | Set the agent's display name, bio, default currency, and claim a `@tag` (signed by the agent's wallet) |
71
+ | `lookup_tag` | Resolve any `tag@nimbill` to its owner's name and Nimiq address, and check the owner's signature |
71
72
  | `get_rates` | Live NIM and USDT prices in 19 supported fiat currencies |
72
73
  | `get_board` | Read a merchant's `/pay/<tag>` board and listed products |
73
74
  | `buy_from_board` | Create an order on `/pay/<tag>` and pay it on-chain from the agent's wallet |
@@ -75,7 +76,7 @@ Running from a clone of this repo instead? Use `"command": "node"` with `"args":
75
76
  | `pay_invoice` | Lock a quote, sign & broadcast the NIM payment with memo, and verify on-chain |
76
77
  | `create_invoice` | Create a new invoice so clients or other agents can pay the agent |
77
78
  | `list_invoices` | List all invoices created by the agent |
78
- | `send_to_tag` | Send NIM to any `@tag` and verify the transfer on-chain |
79
+ | `send_to_tag` | Send NIM to any `@tag` (refused if its signature fails) and verify the transfer on-chain |
79
80
  | `write_cheque` | Create and fund a non-custodial cheque (free or locked to a `@tag`), returning the link and `CHQ-…` code |
80
81
  | `cash_cheque` | Cash a cheque link or `CHQ-…` code on-chain to the agent's wallet or any `@tag` |
81
82
  | `cancel_cheque` | Cancel an uncashed cheque written by the agent and reclaim the NIM |
package/index.mjs CHANGED
@@ -45,7 +45,7 @@ async function handleRequest(req) {
45
45
  return sendResult(id, {
46
46
  protocolVersion: SUPPORTED_VERSIONS.includes(requested) ? requested : SUPPORTED_VERSIONS[0],
47
47
  capabilities: { tools: {}, resources: {} },
48
- serverInfo: { name: "nimbill-agent-wallet", version: "1.1.0" },
48
+ serverInfo: { name: "nimbill-agent-wallet", version: "1.2.0" },
49
49
  instructions:
50
50
  `You have your own non-custodial Nimiq wallet (${wallet.address}) connected to NimBill (${client.baseUrl}). ` +
51
51
  "Call wallet_status to inspect your balance, @tag and spending limits, and setup_profile to set your name and claim a @tag. " +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nimbill-mcp",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "NimBill Agent Wallet MCP server: gives any AI agent its own non-custodial Nimiq wallet, @tag, on-chain payments, invoices and cheques.",
5
5
  "type": "module",
6
6
  "bin": {
package/tools.mjs CHANGED
@@ -3,7 +3,11 @@ import {
3
3
  assertSpendAllowed,
4
4
  broadcastRawTx,
5
5
  buildAndSignNimiqTx,
6
+ checkTagProof,
7
+ chequeHtlcPreImage,
6
8
  clientNonceForTx,
9
+ completeDualHtlcCreationSignature,
10
+ completeDualHtlcRegularTransferSignature,
7
11
  completeDualSignature,
8
12
  formatChequeCode,
9
13
  getAgentBalance,
@@ -15,10 +19,15 @@ import {
15
19
  normalizeAddress,
16
20
  parseChequeInput,
17
21
  recordSpend,
22
+ refundKeyFromSecret,
18
23
  saveChequeSecret,
19
24
  serializeBasicTxContent,
25
+ serializeHtlcCreationTxContent,
26
+ serializeHtlcSpendTxContent,
27
+ signNimiqMessage,
20
28
  spendingLimits,
21
29
  spentLast24h,
30
+ tagProofMessage,
22
31
  } from "./wallet.mjs";
23
32
 
24
33
  export const MCP_TOOLS = [
@@ -34,7 +43,7 @@ export const MCP_TOOLS = [
34
43
  {
35
44
  name: "setup_profile",
36
45
  description:
37
- "Set or update the AI agent's NimBill merchant profile: display name, public @tag (e.g. 'shopbot' -> shopbot@nimbill), bio, default currency, or notification email.",
46
+ "Set or update the AI agent's NimBill merchant profile: display name, public @tag (e.g. 'shopbot' -> shopbot@nimbill), bio, default currency, or notification email. The agent's wallet signs the tag, so people paying it can check it goes to this wallet.",
38
47
  inputSchema: {
39
48
  type: "object",
40
49
  properties: {
@@ -48,7 +57,8 @@ export const MCP_TOOLS = [
48
57
  },
49
58
  {
50
59
  name: "lookup_tag",
51
- description: "Resolve a NimBill @tag (e.g. 'ada' or 'ada@nimbill') to its owner's name, Nimiq wallet address, and avatar.",
60
+ description:
61
+ "Resolve a NimBill @tag (e.g. 'ada' or 'ada@nimbill') to its owner's name, Nimiq wallet address, and avatar. confirmedByOwner is true when the owner's wallet signed that the tag is theirs (checked locally, not taken from NimBill); if false, have the user check the name and address before paying.",
52
62
  inputSchema: {
53
63
  type: "object",
54
64
  properties: {
@@ -168,7 +178,7 @@ export const MCP_TOOLS = [
168
178
  {
169
179
  name: "send_to_tag",
170
180
  description:
171
- "Send NIM from the agent's wallet to someone's NimBill @tag (amount in NIM or any supported fiat currency). Signs and broadcasts the on-chain Nimiq transaction with the transfer memo. Irreversible; spending limits apply.",
181
+ "Send NIM from the agent's wallet to someone's NimBill @tag (amount in NIM or any supported fiat currency). Signs and broadcasts the on-chain Nimiq transaction with the transfer memo. Refuses, sending nothing, if the tag's owner signature doesn't match its address. Irreversible; spending limits apply.",
172
182
  inputSchema: {
173
183
  type: "object",
174
184
  properties: {
@@ -408,7 +418,16 @@ export async function executeTool(name, args = {}, client) {
408
418
  case "setup_profile": {
409
419
  const body = {
410
420
  ...(args.name !== undefined ? { name: args.name } : {}),
411
- ...(args.tag !== undefined ? { tag: args.tag } : {}),
421
+ // Signed by the agent's wallet, so whoever pays the tag can check it goes to this wallet.
422
+ ...(args.tag !== undefined
423
+ ? {
424
+ tag: args.tag,
425
+ tagProof: {
426
+ publicKey: wallet.publicKeyHex,
427
+ signature: signNimiqMessage(tagProofMessage(cleanTag(args.tag), wallet.address), wallet.secretKey),
428
+ },
429
+ }
430
+ : {}),
412
431
  ...(args.bio !== undefined ? { bio: args.bio } : {}),
413
432
  ...(args.defaultCurrency !== undefined ? { displayCurrency: args.defaultCurrency } : {}),
414
433
  };
@@ -420,8 +439,11 @@ export async function executeTool(name, args = {}, client) {
420
439
  };
421
440
  }
422
441
 
423
- case "lookup_tag":
424
- return await client.request(`/api/tags/${encodeURIComponent(cleanTag(args.tag))}`);
442
+ case "lookup_tag": {
443
+ const res = await client.request(`/api/tags/${encodeURIComponent(cleanTag(args.tag))}`);
444
+ // true: the owner's wallet signed that this tag is theirs, checked here and not taken from NimBill.
445
+ return { ...res, confirmedByOwner: checkTagProof(res.owner.tag, res.owner.address, res.owner.proof) };
446
+ }
425
447
 
426
448
  case "get_rates": {
427
449
  const currency = (args.currency || "USD").toUpperCase();
@@ -522,28 +544,43 @@ export async function executeTool(name, args = {}, client) {
522
544
  }
523
545
 
524
546
  case "send_to_tag": {
547
+ // Check the owner's signature ourselves before any money moves (see tagProofMessage).
548
+ const toTag = cleanTag(args.to);
549
+ const { owner } = await client.request(`/api/tags/${encodeURIComponent(toTag)}`);
550
+ if (owner.proof && !checkTagProof(owner.tag, owner.address, owner.proof)) {
551
+ throw toolError(
552
+ "TAG_NOT_CONFIRMED",
553
+ `Couldn't confirm that ${owner.tag}@nimbill belongs to ${owner.address}. Nothing was sent. Ask the recipient for their address.`,
554
+ );
555
+ }
525
556
  const created = await client.request("/api/transfers", {
526
557
  method: "POST",
527
558
  auth: true,
528
- body: { to: args.to, amount: args.amount, currency: args.currency, note: args.note },
559
+ // The agent wallet only signs Nimiq transactions, so its transfers are always NIM.
560
+ body: { to: args.to, asset: "NIM", amount: args.amount, currency: args.currency, note: args.note },
529
561
  });
530
562
  const t = created.transfer;
563
+ // What to send (recipient, Luna, memo) is in `payment`, not on the transfer itself.
564
+ const pay = created.payment;
565
+ if (normalizeAddress(pay.recipient) !== normalizeAddress(owner.address)) {
566
+ throw toolError("TAG_NOT_CONFIRMED", `NimBill gave a different wallet for ${owner.tag}@nimbill than its lookup. Nothing was sent.`);
567
+ }
531
568
 
532
569
  if (args.dryRun) {
533
570
  const signed = buildAndSignNimiqTx({
534
571
  secretKey: wallet.secretKey,
535
- recipient: t.recipient.address,
536
- valueLuna: t.amount,
572
+ recipient: pay.recipient,
573
+ valueLuna: pay.amount,
537
574
  validityStartHeight: await getCurrentBlockHeight(),
538
- memo: t.memo,
575
+ memo: pay.memo,
539
576
  });
540
- return { status: "dry_run", transfer: t, txHash: signed.txHash, rawTx: signed.rawTx, amountNim: nim(t.amount) };
577
+ return { status: "dry_run", transfer: t, txHash: signed.txHash, rawTx: signed.rawTx, amountNim: nim(pay.amount) };
541
578
  }
542
579
 
543
580
  const signed = await sendFromAgent(client, {
544
- recipient: t.recipient.address,
545
- luna: t.amount,
546
- memo: t.memo,
581
+ recipient: pay.recipient,
582
+ luna: pay.amount,
583
+ memo: pay.memo,
547
584
  what: `Transfer to ${args.to}`,
548
585
  });
549
586
  const verify = await verifyAfterBroadcast(client, `/api/transfers/${encodeURIComponent(t.id)}/verify`, {
@@ -561,6 +598,10 @@ export async function executeTool(name, args = {}, client) {
561
598
  case "write_cheque": {
562
599
  const secret = newChequeSecret();
563
600
  const { publicKey: linkPublicKey } = linkKeyFromSecret(secret);
601
+ // A separate refund secret for the 30-day timeout refund: it stays in the agent's data dir
602
+ // and is never part of the link or code handed to the recipient.
603
+ const refundSecret = newChequeSecret();
604
+ const { address: refundAddress } = refundKeyFromSecret(refundSecret);
564
605
  const created = await client.request("/api/cheques", {
565
606
  method: "POST",
566
607
  auth: true,
@@ -568,16 +609,18 @@ export async function executeTool(name, args = {}, client) {
568
609
  amount: args.amount,
569
610
  currency: args.currency || "NIM",
570
611
  linkPublicKey,
612
+ refundAddress,
571
613
  recipientTag: args.recipientTag ? cleanTag(args.recipientTag) : null,
572
614
  note: args.note,
573
615
  },
574
616
  });
575
- const { cheque, payment } = created;
617
+ const { payment } = created;
618
+ let { cheque } = created;
576
619
  const url = `${baseUrl}/c/${cheque.id}#${secret}`;
577
620
  const code = formatChequeCode(cheque.id, secret);
578
621
 
579
622
  // Save the secret before any money moves: without it the cheque can't be cancelled.
580
- saveChequeSecret(dataDir, cheque.id, secret, { number: cheque.number, amount: cheque.amount });
623
+ saveChequeSecret(dataDir, cheque.id, secret, { number: cheque.number, amount: cheque.amount, refundSecret });
581
624
 
582
625
  if (payment?.recipient !== cheque.chequeAddress || payment?.amount !== cheque.amount || payment?.memo !== `NimBill C ${cheque.id}`) {
583
626
  throw new Error("The server's funding details don't match the cheque. Nothing was sent.");
@@ -594,6 +637,45 @@ export async function executeTool(name, args = {}, client) {
594
637
  const verify = await verifyAfterBroadcast(client, `/api/cheques/${encodeURIComponent(cheque.id)}/verify`, {
595
638
  txHash: signed.txHash,
596
639
  });
640
+ if (verify.status === "funded" && cheque.htlc?.refundAddress && cheque.htlc?.timeoutMs) {
641
+ try {
642
+ const height = await getCurrentBlockHeight();
643
+ const htlcTx = {
644
+ senderPublicKey: cheque.chequePublicKey,
645
+ htlcSenderAddress: cheque.htlc.refundAddress,
646
+ htlcRecipientAddress: cheque.chequeAddress,
647
+ hashRoot: chequeHtlcPreImage(cheque.id).hashRoot,
648
+ timeoutMs: cheque.htlc.timeoutMs,
649
+ value: payment.amount,
650
+ fee: 0,
651
+ validityStartHeight: height,
652
+ };
653
+ const { txContent } = serializeHtlcCreationTxContent(htlcTx);
654
+ const n1 = clientNonceForTx(secret, txContent);
655
+ const prep = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/htlc`, {
656
+ method: "POST",
657
+ auth: true,
658
+ body: { step: "prepare", validityStartHeight: height, value: payment.amount, clientNoncePublicKey: n1.noncePublicKey },
659
+ });
660
+ if (prep.step === "prepared") {
661
+ const builtHtlc = completeDualHtlcCreationSignature({
662
+ secret,
663
+ tx: htlcTx,
664
+ nonceScalar: n1.nonceScalar,
665
+ serverNoncePublicKey: prep.serverNoncePublicKey,
666
+ serverPartialSig: prep.serverPartialSig,
667
+ });
668
+ const locked = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/htlc`, {
669
+ method: "POST",
670
+ auth: true,
671
+ body: { step: "broadcast", validityStartHeight: height, value: payment.amount, rawTx: builtHtlc.rawTx },
672
+ });
673
+ if (locked.cheque) cheque = locked.cheque;
674
+ }
675
+ } catch {
676
+ // If HTLC lock fails transiently, the cheque remains funded and spendable.
677
+ }
678
+ }
597
679
  funding = {
598
680
  fundedOnChain: true,
599
681
  txHash: signed.txHash,
@@ -652,36 +734,68 @@ export async function executeTool(name, args = {}, client) {
652
734
  const recipient = normalizeAddress(recipientAddress || "");
653
735
  if (!recipient) throw toolError("INVALID_ARGUMENTS", `Invalid Nimiq address: ${recipientAddress}`);
654
736
 
655
- const tx = {
656
- senderPublicKey: cheque.chequePublicKey,
657
- recipient,
658
- value: info.balance,
659
- fee: 0,
660
- validityStartHeight: info.currentBlock || (await getCurrentBlockHeight()),
661
- };
737
+ const spendFrom = info.spendFrom === "htlc" && cheque.htlc?.contractAddress ? "htlc" : "basic";
738
+ const validityStartHeight = info.currentBlock || (await getCurrentBlockHeight());
662
739
  const common = {
663
740
  action,
664
741
  recipientAddress: recipient,
665
742
  claimerName: args.claimerName,
666
- validityStartHeight: tx.validityStartHeight,
743
+ validityStartHeight,
667
744
  value: info.balance,
745
+ spendFrom,
668
746
  };
669
- const { nonceScalar, noncePublicKey } = clientNonceForTx(secret, serializeBasicTxContent(tx));
670
747
 
671
- const prep = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/claim`, {
672
- method: "POST",
673
- auth: action === "cancel",
674
- body: { step: "prepare", ...common, clientNoncePublicKey: noncePublicKey },
675
- });
676
-
677
- // Signs only the transaction built above, whatever the server sent back.
678
- const { rawTx, txHash } = completeDualSignature({
679
- secret,
680
- tx,
681
- nonceScalar,
682
- serverNoncePublicKey: prep.serverNoncePublicKey,
683
- serverPartialSig: prep.serverPartialSig,
684
- });
748
+ let rawTx;
749
+ let txHash;
750
+ if (spendFrom === "htlc") {
751
+ const htlcTx = {
752
+ htlcAddress: cheque.htlc.contractAddress,
753
+ recipient,
754
+ value: info.balance,
755
+ fee: 0,
756
+ validityStartHeight,
757
+ };
758
+ const { nonceScalar, noncePublicKey } = clientNonceForTx(secret, serializeHtlcSpendTxContent(htlcTx));
759
+ const prep = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/claim`, {
760
+ method: "POST",
761
+ auth: action === "cancel",
762
+ body: { step: "prepare", ...common, clientNoncePublicKey: noncePublicKey },
763
+ });
764
+ const built = completeDualHtlcRegularTransferSignature({
765
+ secret,
766
+ chequeId: cheque.id,
767
+ chequePublicKey: cheque.chequePublicKey,
768
+ tx: htlcTx,
769
+ nonceScalar,
770
+ serverNoncePublicKey: prep.serverNoncePublicKey,
771
+ serverPartialSig: prep.serverPartialSig,
772
+ });
773
+ rawTx = built.rawTx;
774
+ txHash = built.txHash;
775
+ } else {
776
+ const tx = {
777
+ senderPublicKey: cheque.chequePublicKey,
778
+ recipient,
779
+ value: info.balance,
780
+ fee: 0,
781
+ validityStartHeight,
782
+ };
783
+ const { nonceScalar, noncePublicKey } = clientNonceForTx(secret, serializeBasicTxContent(tx));
784
+ const prep = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/claim`, {
785
+ method: "POST",
786
+ auth: action === "cancel",
787
+ body: { step: "prepare", ...common, clientNoncePublicKey: noncePublicKey },
788
+ });
789
+ const built = completeDualSignature({
790
+ secret,
791
+ tx,
792
+ nonceScalar,
793
+ serverNoncePublicKey: prep.serverNoncePublicKey,
794
+ serverPartialSig: prep.serverPartialSig,
795
+ });
796
+ rawTx = built.rawTx;
797
+ txHash = built.txHash;
798
+ }
685
799
 
686
800
  const done = await client.request(`/api/cheques/${encodeURIComponent(cheque.id)}/claim`, {
687
801
  method: "POST",
package/wallet.mjs CHANGED
@@ -31,13 +31,13 @@ function ibanCheck(str) {
31
31
  return 98 - rem;
32
32
  }
33
33
 
34
- /** Derive a Nimiq "NQxx xxxx …" address from a 32-byte Ed25519 public key. */
35
- export function addressFromPublicKey(publicKeyBytes) {
36
- const hash = blake2b(publicKeyBytes, { dkLen: 32 }).subarray(0, 20);
34
+ /** Derive a Nimiq "NQxx xxxx …" address from a 20-byte raw address. */
35
+ export function addressFromBytes(addrBytes) {
36
+ if (addrBytes.length !== 20) throw new Error("Address must be 20 bytes");
37
37
  let bits = 0;
38
38
  let value = 0;
39
39
  let base32 = "";
40
- for (const byte of hash) {
40
+ for (const byte of addrBytes) {
41
41
  value = (value << 8) | byte;
42
42
  bits += 8;
43
43
  while (bits >= 5) {
@@ -50,6 +50,11 @@ export function addressFromPublicKey(publicKeyBytes) {
50
50
  return full.match(/.{1,4}/g).join(" ");
51
51
  }
52
52
 
53
+ /** Derive a Nimiq "NQxx xxxx …" address from a 32-byte Ed25519 public key. */
54
+ export function addressFromPublicKey(publicKeyBytes) {
55
+ return addressFromBytes(blake2b(publicKeyBytes, { dkLen: 32 }).subarray(0, 20));
56
+ }
57
+
53
58
  /** Canonical "NQxx xxxx …" form of an address, or null if it is malformed or its checksum is wrong. */
54
59
  export function normalizeAddress(address) {
55
60
  const clean = String(address).toUpperCase().replace(/\s+/g, "");
@@ -294,6 +299,33 @@ export function signNimiqMessage(message, secretKey) {
294
299
  return bytesToHex(ed25519.sign(digest, secretKey));
295
300
  }
296
301
 
302
+ // ---------- Signed tags (the same rules as src/lib/tag-proof.ts in the NimBill app) ----------
303
+
304
+ /** The sentence a tag's owner signs: that `tag` (already cleaned, no "@nimbill") belongs to `address`. */
305
+ export function tagProofMessage(tag, address) {
306
+ return `NimBill tag\n${tag}@nimbill belongs to ${normalizeAddress(address) ?? address}`;
307
+ }
308
+
309
+ /**
310
+ * Whether the owner of `address` signed that `tag` is theirs. `proof` is the { publicKey, signature }
311
+ * a tag lookup returns. False for a missing or broken proof.
312
+ */
313
+ export function checkTagProof(tag, address, proof) {
314
+ if (!proof || !/^[0-9a-f]{64}$/i.test(proof.publicKey) || !/^[0-9a-f]{128}$/i.test(proof.signature)) return false;
315
+ const wallet = normalizeAddress(address);
316
+ if (!wallet || addressFromPublicKey(hexToBytes(proof.publicKey)) !== wallet) return false;
317
+ const bytes = utf8ToBytes(tagProofMessage(tag, wallet));
318
+ const prefix = utf8ToBytes(`\x16Nimiq Signed Message:\n${bytes.length}`);
319
+ const payload = new Uint8Array(prefix.length + bytes.length);
320
+ payload.set(prefix, 0);
321
+ payload.set(bytes, prefix.length);
322
+ try {
323
+ return ed25519.verify(hexToBytes(proof.signature), sha256(payload), hexToBytes(proof.publicKey));
324
+ } catch {
325
+ return false;
326
+ }
327
+ }
328
+
297
329
  function encodeVarint(n) {
298
330
  const out = [];
299
331
  let v = n >>> 0;
@@ -559,6 +591,29 @@ export function linkKeyFromSecret(rawSecret) {
559
591
  return { scalar, publicKey: bytesToHex(point.toBytes()) };
560
592
  }
561
593
 
594
+ // Same as the app's refundKeyFromSecret: the refund secret is separate from the link secret and
595
+ // never shared, so whoever holds the cheque link can't take the 30-day timeout refund.
596
+ export function refundKeyFromSecret(rawRefundSecret) {
597
+ const secret = normalizeChequeSecret(rawRefundSecret);
598
+ if (!SECRET_RE.test(secret)) throw new Error("Invalid cheque refund key");
599
+ const secretKey = sha256(concatBytes(utf8ToBytes("nimbill-cheque-refund-key-v2:"), utf8ToBytes(secret)));
600
+ const pubBytes = ed25519.getPublicKey(secretKey);
601
+ return {
602
+ secretKey,
603
+ publicKey: bytesToHex(pubBytes),
604
+ address: addressFromPublicKey(pubBytes),
605
+ };
606
+ }
607
+
608
+ export function chequeHtlcPreImage(chequeId) {
609
+ const preBytes = sha256(utf8ToBytes(`nimbill-cheque-htlc-preimage-v1:${String(chequeId).toLowerCase()}`));
610
+ const rootBytes = sha256(preBytes);
611
+ return {
612
+ preImage: bytesToHex(preBytes),
613
+ hashRoot: bytesToHex(rootBytes),
614
+ };
615
+ }
616
+
562
617
  export function serializeBasicTxContent(tx) {
563
618
  const pubKey = hexToBytes(tx.senderPublicKey);
564
619
  if (pubKey.length !== 32) throw new Error("senderPublicKey must be 32 bytes");
@@ -588,6 +643,95 @@ export function serializeBasicTxContent(tx) {
588
643
  return out;
589
644
  }
590
645
 
646
+ export function serializeHtlcCreationData(params) {
647
+ const senderBytes = addressToBytes(params.htlcSenderAddress);
648
+ const recipientBytes = addressToBytes(params.htlcRecipientAddress);
649
+ const rootBytes = hexToBytes(params.hashRoot.toLowerCase());
650
+ if (rootBytes.length !== 32) throw new Error("HTLC hashRoot must be 32 bytes");
651
+ const data = new Uint8Array(82);
652
+ const dv = new DataView(data.buffer);
653
+ let o = 0;
654
+ data.set(senderBytes, o);
655
+ o += 20;
656
+ data.set(recipientBytes, o);
657
+ o += 20;
658
+ data[o++] = 3; // Sha256
659
+ data.set(rootBytes, o);
660
+ o += 32;
661
+ data[o++] = 1; // hash_count = 1
662
+ dv.setBigUint64(o, BigInt(params.timeoutMs), false);
663
+ return data;
664
+ }
665
+
666
+ export function serializeHtlcCreationTxContent(tx) {
667
+ const pubKey = hexToBytes(tx.senderPublicKey);
668
+ if (pubKey.length !== 32) throw new Error("senderPublicKey must be 32 bytes");
669
+ const senderBytes = blake2b(pubKey, { dkLen: 32 }).subarray(0, 20);
670
+ const recipientData = serializeHtlcCreationData(tx);
671
+ const value = BigInt(tx.value);
672
+ const fee = BigInt(tx.fee ?? 0);
673
+ const networkId = tx.networkId ?? NIMIQ_MAINNET_ID;
674
+
675
+ const buildContent = (recipient20) => {
676
+ const out = new Uint8Array(67 + recipientData.length);
677
+ const view = new DataView(out.buffer);
678
+ let o = 0;
679
+ view.setUint16(o, recipientData.length, false);
680
+ o += 2;
681
+ out.set(recipientData, o);
682
+ o += recipientData.length;
683
+ out.set(senderBytes, o);
684
+ o += 20;
685
+ out[o++] = 0;
686
+ out.set(recipient20, o);
687
+ o += 20;
688
+ out[o++] = 2; // HTLC
689
+ view.setBigUint64(o, value, false);
690
+ o += 8;
691
+ view.setBigUint64(o, fee, false);
692
+ o += 8;
693
+ view.setUint32(o, tx.validityStartHeight >>> 0, false);
694
+ o += 4;
695
+ out[o++] = networkId & 0xff;
696
+ out[o++] = 1; // CONTRACT_CREATION
697
+ out[o++] = 0;
698
+ return out;
699
+ };
700
+
701
+ const zeroRecipient = new Uint8Array(20);
702
+ const contractAddressBytes = blake2b(buildContent(zeroRecipient), { dkLen: 32 }).subarray(0, 20);
703
+ const contractAddress = addressFromBytes(contractAddressBytes);
704
+ const txContent = buildContent(contractAddressBytes);
705
+ return { txContent, contractAddress, contractAddressBytes, recipientData };
706
+ }
707
+
708
+ export function serializeHtlcSpendTxContent(tx) {
709
+ const senderBytes = addressToBytes(tx.htlcAddress);
710
+ const recipientBytes = addressToBytes(tx.recipient);
711
+ const buf = new ArrayBuffer(67);
712
+ const view = new DataView(buf);
713
+ const out = new Uint8Array(buf);
714
+ let o = 0;
715
+ view.setUint16(o, 0, false);
716
+ o += 2;
717
+ out.set(senderBytes, o);
718
+ o += 20;
719
+ out[o++] = 2; // sender_type = HTLC (2)
720
+ out.set(recipientBytes, o);
721
+ o += 20;
722
+ out[o++] = 0; // recipient_type = Basic (0)
723
+ view.setBigUint64(o, BigInt(tx.value), false);
724
+ o += 8;
725
+ view.setBigUint64(o, BigInt(tx.fee ?? 0), false);
726
+ o += 8;
727
+ view.setUint32(o, tx.validityStartHeight >>> 0, false);
728
+ o += 4;
729
+ out[o++] = (tx.networkId ?? NIMIQ_MAINNET_ID) & 0xff;
730
+ out[o++] = 0;
731
+ out[o++] = 0;
732
+ return out;
733
+ }
734
+
591
735
  /** A fresh nonce for one signing attempt (never reused, even for the same transaction). */
592
736
  export function clientNonceForTx(rawSecret, txContent) {
593
737
  const secret = normalizeChequeSecret(rawSecret);
@@ -597,15 +741,13 @@ export function clientNonceForTx(rawSecret, txContent) {
597
741
  return { nonceScalar, noncePublicKey: bytesToHex(point.toBytes()) };
598
742
  }
599
743
 
600
- /** Combine both halves of the signature over the agent's own `tx` and return the raw transaction. */
601
- export function completeDualSignature({ secret, tx, nonceScalar, serverNoncePublicKey, serverPartialSig }) {
602
- const txContent = serializeBasicTxContent(tx);
744
+ function combineDualSigBytes({ secret, senderPublicKey, txContent, nonceScalar, serverNoncePublicKey, serverPartialSig }) {
603
745
  const { scalar: a1 } = linkKeyFromSecret(secret);
604
746
  const r1 = nonceScalar;
605
747
  const R1 = Point.BASE.multiply(r1);
606
748
  const R2 = Point.fromHex(serverNoncePublicKey);
607
749
  const R = R1.add(R2).toBytes();
608
- const A = hexToBytes(tx.senderPublicKey);
750
+ const A = hexToBytes(senderPublicKey);
609
751
  const k = bytesToNumberLE(sha512(concatBytes(R, A, txContent))) % CURVE_N;
610
752
  const s1 = (r1 + k * a1) % CURVE_N;
611
753
  const s2 = bytesToNumberLE(hexToBytes(serverPartialSig));
@@ -615,6 +757,21 @@ export function completeDualSignature({ secret, tx, nonceScalar, serverNoncePubl
615
757
  if (!ed25519.verify(sigBytes, txContent, A)) {
616
758
  throw new Error("Cheque 2-of-2 signature verification failed");
617
759
  }
760
+ return sigBytes;
761
+ }
762
+
763
+ /** Combine both halves of the signature over the agent's own `tx` and return the raw transaction. */
764
+ export function completeDualSignature({ secret, tx, nonceScalar, serverNoncePublicKey, serverPartialSig }) {
765
+ const txContent = serializeBasicTxContent(tx);
766
+ const sigBytes = combineDualSigBytes({
767
+ secret,
768
+ senderPublicKey: tx.senderPublicKey,
769
+ txContent,
770
+ nonceScalar,
771
+ serverNoncePublicKey,
772
+ serverPartialSig,
773
+ });
774
+ const A = hexToBytes(tx.senderPublicKey);
618
775
  const recipientBytes = addressToBytes(tx.recipient);
619
776
  const buf = new ArrayBuffer(139);
620
777
  const view = new DataView(buf);
@@ -639,3 +796,183 @@ export function completeDualSignature({ secret, tx, nonceScalar, serverNoncePubl
639
796
  txHash: bytesToHex(blake2b(txContent, { dkLen: 32 })),
640
797
  };
641
798
  }
799
+
800
+ export function completeDualHtlcCreationSignature({ secret, tx, nonceScalar, serverNoncePublicKey, serverPartialSig }) {
801
+ const { txContent, contractAddress, contractAddressBytes, recipientData } = serializeHtlcCreationTxContent(tx);
802
+ const sigBytes = combineDualSigBytes({
803
+ secret,
804
+ senderPublicKey: tx.senderPublicKey,
805
+ txContent,
806
+ nonceScalar,
807
+ serverNoncePublicKey,
808
+ serverPartialSig,
809
+ });
810
+ const pubKey = hexToBytes(tx.senderPublicKey);
811
+ const senderBytes = blake2b(pubKey, { dkLen: 32 }).subarray(0, 20);
812
+ const sigProof = new Uint8Array(98);
813
+ sigProof[0] = 0;
814
+ sigProof.set(pubKey, 1);
815
+ sigProof[33] = 0;
816
+ sigProof.set(sigBytes, 34);
817
+
818
+ const dVar = encodeVarint(recipientData.length);
819
+ const pVar = encodeVarint(sigProof.length);
820
+ const raw = new Uint8Array(
821
+ 1 + 20 + 1 + 1 + 20 + 1 + dVar.length + recipientData.length + 8 + 8 + 4 + 1 + 1 + pVar.length + sigProof.length,
822
+ );
823
+ const dv = new DataView(raw.buffer);
824
+ let p = 0;
825
+ raw[p++] = 1;
826
+ raw.set(senderBytes, p);
827
+ p += 20;
828
+ raw[p++] = 0;
829
+ raw[p++] = 0;
830
+ raw.set(contractAddressBytes, p);
831
+ p += 20;
832
+ raw[p++] = 2; // HTLC
833
+ raw.set(dVar, p);
834
+ p += dVar.length;
835
+ raw.set(recipientData, p);
836
+ p += recipientData.length;
837
+ dv.setBigUint64(p, BigInt(tx.value), false);
838
+ p += 8;
839
+ dv.setBigUint64(p, BigInt(tx.fee ?? 0), false);
840
+ p += 8;
841
+ dv.setUint32(p, tx.validityStartHeight >>> 0, false);
842
+ p += 4;
843
+ raw[p++] = (tx.networkId ?? NIMIQ_MAINNET_ID) & 0xff;
844
+ raw[p++] = 1; // CONTRACT_CREATION
845
+ raw.set(pVar, p);
846
+ p += pVar.length;
847
+ raw.set(sigProof, p);
848
+
849
+ return {
850
+ rawTx: bytesToHex(raw),
851
+ txHash: bytesToHex(blake2b(txContent, { dkLen: 32 })),
852
+ contractAddress,
853
+ };
854
+ }
855
+
856
+ export function completeDualHtlcRegularTransferSignature({
857
+ secret,
858
+ chequeId,
859
+ chequePublicKey,
860
+ tx,
861
+ nonceScalar,
862
+ serverNoncePublicKey,
863
+ serverPartialSig,
864
+ }) {
865
+ const txContent = serializeHtlcSpendTxContent(tx);
866
+ const sigBytes = combineDualSigBytes({
867
+ secret,
868
+ senderPublicKey: chequePublicKey,
869
+ txContent,
870
+ nonceScalar,
871
+ serverNoncePublicKey,
872
+ serverPartialSig,
873
+ });
874
+ const pubKey = hexToBytes(chequePublicKey);
875
+ const { preImage, hashRoot } = chequeHtlcPreImage(chequeId);
876
+ const preBytes = hexToBytes(preImage);
877
+ const rootBytes = hexToBytes(hashRoot);
878
+
879
+ const sigProof = new Uint8Array(98);
880
+ sigProof[0] = 0;
881
+ sigProof.set(pubKey, 1);
882
+ sigProof[33] = 0;
883
+ sigProof.set(sigBytes, 34);
884
+
885
+ const proof = new Uint8Array(1 + 1 + 1 + 32 + 1 + 32 + 98);
886
+ let o = 0;
887
+ proof[o++] = 0; // RegularTransfer
888
+ proof[o++] = 1; // hash_depth = 1
889
+ proof[o++] = 3; // Sha256
890
+ proof.set(rootBytes, o);
891
+ o += 32;
892
+ proof[o++] = 32; // PreImage32
893
+ proof.set(preBytes, o);
894
+ o += 32;
895
+ proof.set(sigProof, o);
896
+
897
+ const senderBytes = addressToBytes(tx.htlcAddress);
898
+ const recipientBytes = addressToBytes(tx.recipient);
899
+ const pVar = encodeVarint(proof.length);
900
+ const raw = new Uint8Array(1 + 20 + 1 + 1 + 20 + 1 + 1 + 8 + 8 + 4 + 1 + 1 + pVar.length + proof.length);
901
+ const dv = new DataView(raw.buffer);
902
+ let p = 0;
903
+ raw[p++] = 1;
904
+ raw.set(senderBytes, p);
905
+ p += 20;
906
+ raw[p++] = 2; // HTLC
907
+ raw[p++] = 0;
908
+ raw.set(recipientBytes, p);
909
+ p += 20;
910
+ raw[p++] = 0; // Basic
911
+ raw[p++] = 0;
912
+ dv.setBigUint64(p, BigInt(tx.value), false);
913
+ p += 8;
914
+ dv.setBigUint64(p, BigInt(tx.fee ?? 0), false);
915
+ p += 8;
916
+ dv.setUint32(p, tx.validityStartHeight >>> 0, false);
917
+ p += 4;
918
+ raw[p++] = (tx.networkId ?? NIMIQ_MAINNET_ID) & 0xff;
919
+ raw[p++] = 0;
920
+ raw.set(pVar, p);
921
+ p += pVar.length;
922
+ raw.set(proof, p);
923
+
924
+ return {
925
+ rawTx: bytesToHex(raw),
926
+ txHash: bytesToHex(blake2b(txContent, { dkLen: 32 })),
927
+ };
928
+ }
929
+
930
+ export function buildAndSignHtlcTimeoutResolveTx({ refundSecret, tx }) {
931
+ const refund = refundKeyFromSecret(refundSecret);
932
+ const txContent = serializeHtlcSpendTxContent(tx);
933
+ const sigBytes = ed25519.sign(txContent, refund.secretKey);
934
+ const pubKey = hexToBytes(refund.publicKey);
935
+
936
+ const sigProof = new Uint8Array(98);
937
+ sigProof[0] = 0;
938
+ sigProof.set(pubKey, 1);
939
+ sigProof[33] = 0;
940
+ sigProof.set(sigBytes, 34);
941
+
942
+ const proof = new Uint8Array(1 + 98);
943
+ proof[0] = 2; // TimeoutResolve
944
+ proof.set(sigProof, 1);
945
+
946
+ const senderBytes = addressToBytes(tx.htlcAddress);
947
+ const recipientBytes = addressToBytes(tx.recipient);
948
+ const pVar = encodeVarint(proof.length);
949
+ const raw = new Uint8Array(1 + 20 + 1 + 1 + 20 + 1 + 1 + 8 + 8 + 4 + 1 + 1 + pVar.length + proof.length);
950
+ const dv = new DataView(raw.buffer);
951
+ let p = 0;
952
+ raw[p++] = 1;
953
+ raw.set(senderBytes, p);
954
+ p += 20;
955
+ raw[p++] = 2; // HTLC
956
+ raw[p++] = 0;
957
+ raw.set(recipientBytes, p);
958
+ p += 20;
959
+ raw[p++] = 0;
960
+ raw[p++] = 0;
961
+ dv.setBigUint64(p, BigInt(tx.value), false);
962
+ p += 8;
963
+ dv.setBigUint64(p, BigInt(tx.fee ?? 0), false);
964
+ p += 8;
965
+ dv.setUint32(p, tx.validityStartHeight >>> 0, false);
966
+ p += 4;
967
+ raw[p++] = (tx.networkId ?? NIMIQ_MAINNET_ID) & 0xff;
968
+ raw[p++] = 0;
969
+ raw.set(pVar, p);
970
+ p += pVar.length;
971
+ raw.set(proof, p);
972
+
973
+ return {
974
+ rawTx: bytesToHex(raw),
975
+ txHash: bytesToHex(blake2b(txContent, { dkLen: 32 })),
976
+ refundAddress: refund.address,
977
+ };
978
+ }