@t402/btc 2.7.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 +120 -0
- package/dist/cjs/exact/client/index.d.ts +89 -0
- package/dist/cjs/exact/client/index.js +145 -0
- package/dist/cjs/exact/client/index.js.map +1 -0
- package/dist/cjs/exact/facilitator/index.d.ts +114 -0
- package/dist/cjs/exact/facilitator/index.js +218 -0
- package/dist/cjs/exact/facilitator/index.js.map +1 -0
- package/dist/cjs/exact/server/index.d.ts +101 -0
- package/dist/cjs/exact/server/index.js +161 -0
- package/dist/cjs/exact/server/index.js.map +1 -0
- package/dist/cjs/index.d.ts +179 -0
- package/dist/cjs/index.js +849 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/lightning/client/index.d.ts +82 -0
- package/dist/cjs/lightning/client/index.js +114 -0
- package/dist/cjs/lightning/client/index.js.map +1 -0
- package/dist/cjs/lightning/facilitator/index.d.ts +93 -0
- package/dist/cjs/lightning/facilitator/index.js +211 -0
- package/dist/cjs/lightning/facilitator/index.js.map +1 -0
- package/dist/cjs/lightning/server/index.d.ts +96 -0
- package/dist/cjs/lightning/server/index.js +157 -0
- package/dist/cjs/lightning/server/index.js.map +1 -0
- package/dist/cjs/signer-B_Z4WGLa.d.ts +64 -0
- package/dist/esm/chunk-2DEKJ7ER.mjs +123 -0
- package/dist/esm/chunk-2DEKJ7ER.mjs.map +1 -0
- package/dist/esm/chunk-3IOPLDQH.mjs +74 -0
- package/dist/esm/chunk-3IOPLDQH.mjs.map +1 -0
- package/dist/esm/chunk-7IU3Z36R.mjs +103 -0
- package/dist/esm/chunk-7IU3Z36R.mjs.map +1 -0
- package/dist/esm/chunk-HNFWDITA.mjs +170 -0
- package/dist/esm/chunk-HNFWDITA.mjs.map +1 -0
- package/dist/esm/chunk-MX3PAUPJ.mjs +65 -0
- package/dist/esm/chunk-MX3PAUPJ.mjs.map +1 -0
- package/dist/esm/chunk-YJYTK2QQ.mjs +127 -0
- package/dist/esm/chunk-YJYTK2QQ.mjs.map +1 -0
- package/dist/esm/chunk-YWZC2RR7.mjs +38 -0
- package/dist/esm/chunk-YWZC2RR7.mjs.map +1 -0
- package/dist/esm/chunk-ZOL5R3HZ.mjs +177 -0
- package/dist/esm/chunk-ZOL5R3HZ.mjs.map +1 -0
- package/dist/esm/exact/client/index.d.mts +89 -0
- package/dist/esm/exact/client/index.mjs +11 -0
- package/dist/esm/exact/client/index.mjs.map +1 -0
- package/dist/esm/exact/facilitator/index.d.mts +114 -0
- package/dist/esm/exact/facilitator/index.mjs +11 -0
- package/dist/esm/exact/facilitator/index.mjs.map +1 -0
- package/dist/esm/exact/server/index.d.mts +101 -0
- package/dist/esm/exact/server/index.mjs +10 -0
- package/dist/esm/exact/server/index.mjs.map +1 -0
- package/dist/esm/index.d.mts +179 -0
- package/dist/esm/index.mjs +77 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/lightning/client/index.d.mts +82 -0
- package/dist/esm/lightning/client/index.mjs +11 -0
- package/dist/esm/lightning/client/index.mjs.map +1 -0
- package/dist/esm/lightning/facilitator/index.d.mts +93 -0
- package/dist/esm/lightning/facilitator/index.mjs +11 -0
- package/dist/esm/lightning/facilitator/index.mjs.map +1 -0
- package/dist/esm/lightning/server/index.d.mts +96 -0
- package/dist/esm/lightning/server/index.mjs +10 -0
- package/dist/esm/lightning/server/index.mjs.map +1 -0
- package/dist/esm/signer-B_Z4WGLa.d.mts +64 -0
- package/package.json +142 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SATS_PER_BTC,
|
|
3
|
+
SCHEME_EXACT,
|
|
4
|
+
__publicField
|
|
5
|
+
} from "./chunk-YWZC2RR7.mjs";
|
|
6
|
+
|
|
7
|
+
// src/lightning/server/scheme.ts
|
|
8
|
+
var LightningScheme = class {
|
|
9
|
+
constructor(config) {
|
|
10
|
+
__publicField(this, "scheme", SCHEME_EXACT);
|
|
11
|
+
__publicField(this, "moneyParsers", []);
|
|
12
|
+
__publicField(this, "config");
|
|
13
|
+
this.config = config;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Register a custom money parser in the parser chain.
|
|
17
|
+
*
|
|
18
|
+
* @param parser - Custom function to convert amount to AssetAmount (or null to skip)
|
|
19
|
+
* @returns The server instance for chaining
|
|
20
|
+
*/
|
|
21
|
+
registerMoneyParser(parser) {
|
|
22
|
+
this.moneyParsers.push(parser);
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Parses a price into an asset amount in satoshis.
|
|
27
|
+
*
|
|
28
|
+
* @param price - The price to parse
|
|
29
|
+
* @param network - The network to use
|
|
30
|
+
* @returns Promise that resolves to the parsed asset amount
|
|
31
|
+
*/
|
|
32
|
+
async parsePrice(price, network) {
|
|
33
|
+
if (typeof price === "object" && price !== null && "amount" in price) {
|
|
34
|
+
if (!price.asset) {
|
|
35
|
+
throw new Error(`Asset must be specified for AssetAmount on network ${network}`);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
amount: price.amount,
|
|
39
|
+
asset: price.asset,
|
|
40
|
+
extra: price.extra || {}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const amount = this.parseMoneyToDecimal(price);
|
|
44
|
+
for (const parser of this.moneyParsers) {
|
|
45
|
+
const result = await parser(amount, network);
|
|
46
|
+
if (result !== null) {
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return this.defaultMoneyConversion(amount);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Build payment requirements for Lightning Network.
|
|
54
|
+
*
|
|
55
|
+
* Generates a BOLT11 invoice and adds it to the extra field.
|
|
56
|
+
*/
|
|
57
|
+
async enhancePaymentRequirements(paymentRequirements, supportedKind, extensionKeys) {
|
|
58
|
+
void extensionKeys;
|
|
59
|
+
const extra = { ...paymentRequirements.extra };
|
|
60
|
+
const invoice = await this.config.generateInvoice(
|
|
61
|
+
paymentRequirements.amount,
|
|
62
|
+
`t402 payment on ${supportedKind.network}`,
|
|
63
|
+
paymentRequirements.maxTimeoutSeconds
|
|
64
|
+
);
|
|
65
|
+
extra.bolt11Invoice = invoice.bolt11Invoice;
|
|
66
|
+
extra.paymentHash = invoice.paymentHash;
|
|
67
|
+
return {
|
|
68
|
+
...paymentRequirements,
|
|
69
|
+
asset: paymentRequirements.asset || "BTC",
|
|
70
|
+
extra
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Parse Money (string | number) to a decimal number.
|
|
75
|
+
*/
|
|
76
|
+
parseMoneyToDecimal(money) {
|
|
77
|
+
if (typeof money === "number") {
|
|
78
|
+
if (!Number.isFinite(money)) {
|
|
79
|
+
throw new Error(`Invalid money value: ${money}`);
|
|
80
|
+
}
|
|
81
|
+
return money;
|
|
82
|
+
}
|
|
83
|
+
const cleanMoney = money.replace(/^\$/, "").trim();
|
|
84
|
+
const amount = parseFloat(cleanMoney);
|
|
85
|
+
if (isNaN(amount)) {
|
|
86
|
+
throw new Error(`Invalid money format: ${money}`);
|
|
87
|
+
}
|
|
88
|
+
return amount;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Default money conversion: treat amount as BTC, convert to satoshis.
|
|
92
|
+
*/
|
|
93
|
+
defaultMoneyConversion(amount) {
|
|
94
|
+
const sats = Math.floor(amount * SATS_PER_BTC);
|
|
95
|
+
return {
|
|
96
|
+
amount: sats.toString(),
|
|
97
|
+
asset: "BTC",
|
|
98
|
+
extra: {
|
|
99
|
+
symbol: "BTC",
|
|
100
|
+
decimals: 8
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// src/lightning/server/register.ts
|
|
107
|
+
function registerLightningScheme(server, config) {
|
|
108
|
+
const scheme = new LightningScheme(config.schemeConfig);
|
|
109
|
+
if (config.networks && config.networks.length > 0) {
|
|
110
|
+
config.networks.forEach((network) => {
|
|
111
|
+
server.register(network, scheme);
|
|
112
|
+
});
|
|
113
|
+
} else {
|
|
114
|
+
server.register("lightning:*", scheme);
|
|
115
|
+
}
|
|
116
|
+
return server;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export {
|
|
120
|
+
LightningScheme,
|
|
121
|
+
registerLightningScheme
|
|
122
|
+
};
|
|
123
|
+
//# sourceMappingURL=chunk-2DEKJ7ER.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lightning/server/scheme.ts","../../src/lightning/server/register.ts"],"sourcesContent":["/**\n * Lightning Network Server Scheme Implementation\n *\n * Handles price parsing and payment requirement enhancement for\n * Lightning Network payments.\n */\n\nimport type {\n AssetAmount,\n Network,\n PaymentRequirements,\n Price,\n SchemeNetworkServer,\n MoneyParser,\n} from '@t402/core/types'\nimport { SCHEME_EXACT, SATS_PER_BTC } from '../../constants.js'\n\n/**\n * Lightning invoice generator function\n * Used to create BOLT11 invoices for payment requirements\n */\nexport type InvoiceGenerator = (\n amountSats: string,\n description: string,\n expiry: number,\n) => Promise<{\n bolt11Invoice: string\n paymentHash: string\n}>\n\n/**\n * Configuration options for Lightning server scheme\n */\nexport interface LightningSchemeConfig {\n /**\n * Function to generate BOLT11 invoices\n */\n generateInvoice: InvoiceGenerator\n}\n\n/**\n * Lightning Network server implementation for the Exact payment scheme.\n * Generates BOLT11 invoices and enhances payment requirements.\n */\nexport class LightningScheme implements SchemeNetworkServer {\n readonly scheme = SCHEME_EXACT\n private moneyParsers: MoneyParser[] = []\n private config: LightningSchemeConfig\n\n constructor(config: LightningSchemeConfig) {\n this.config = config\n }\n\n /**\n * Register a custom money parser in the parser chain.\n *\n * @param parser - Custom function to convert amount to AssetAmount (or null to skip)\n * @returns The server instance for chaining\n */\n registerMoneyParser(parser: MoneyParser): LightningScheme {\n this.moneyParsers.push(parser)\n return this\n }\n\n /**\n * Parses a price into an asset amount in satoshis.\n *\n * @param price - The price to parse\n * @param network - The network to use\n * @returns Promise that resolves to the parsed asset amount\n */\n async parsePrice(price: Price, network: Network): Promise<AssetAmount> {\n // If already an AssetAmount, return it directly\n if (typeof price === 'object' && price !== null && 'amount' in price) {\n if (!price.asset) {\n throw new Error(`Asset must be specified for AssetAmount on network ${network}`)\n }\n return {\n amount: price.amount,\n asset: price.asset,\n extra: price.extra || {},\n }\n }\n\n // Parse Money to decimal number\n const amount = this.parseMoneyToDecimal(price)\n\n // Try each custom money parser in order\n for (const parser of this.moneyParsers) {\n const result = await parser(amount, network)\n if (result !== null) {\n return result\n }\n }\n\n // Default: convert to satoshis\n return this.defaultMoneyConversion(amount)\n }\n\n /**\n * Build payment requirements for Lightning Network.\n *\n * Generates a BOLT11 invoice and adds it to the extra field.\n */\n async enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n t402Version: number\n scheme: string\n network: Network\n extra?: Record<string, unknown>\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n void extensionKeys\n\n const extra = { ...paymentRequirements.extra }\n\n // Generate a BOLT11 invoice for the payment\n const invoice = await this.config.generateInvoice(\n paymentRequirements.amount,\n `t402 payment on ${supportedKind.network}`,\n paymentRequirements.maxTimeoutSeconds,\n )\n\n extra.bolt11Invoice = invoice.bolt11Invoice\n extra.paymentHash = invoice.paymentHash\n\n return {\n ...paymentRequirements,\n asset: paymentRequirements.asset || 'BTC',\n extra,\n }\n }\n\n /**\n * Parse Money (string | number) to a decimal number.\n */\n private parseMoneyToDecimal(money: string | number): number {\n if (typeof money === 'number') {\n if (!Number.isFinite(money)) {\n throw new Error(`Invalid money value: ${money}`)\n }\n return money\n }\n\n const cleanMoney = money.replace(/^\\$/, '').trim()\n const amount = parseFloat(cleanMoney)\n\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`)\n }\n\n return amount\n }\n\n /**\n * Default money conversion: treat amount as BTC, convert to satoshis.\n */\n private defaultMoneyConversion(amount: number): AssetAmount {\n const sats = Math.floor(amount * SATS_PER_BTC)\n\n return {\n amount: sats.toString(),\n asset: 'BTC',\n extra: {\n symbol: 'BTC',\n decimals: 8,\n },\n }\n }\n}\n","import { t402ResourceServer } from '@t402/core/server'\nimport { Network } from '@t402/core/types'\nimport { LightningScheme, LightningSchemeConfig } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402ResourceServer\n */\nexport interface LightningResourceServerConfig {\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (lightning:*)\n */\n networks?: Network[]\n\n /**\n * Scheme configuration (invoice generator, etc.)\n */\n schemeConfig: LightningSchemeConfig\n}\n\n/**\n * Registers Lightning payment schemes to an t402ResourceServer instance.\n *\n * @param server - The t402ResourceServer instance to register schemes to\n * @param config - Configuration for Lightning resource server registration\n * @returns The server instance for chaining\n */\nexport function registerLightningScheme(\n server: t402ResourceServer,\n config: LightningResourceServerConfig,\n): t402ResourceServer {\n const scheme = new LightningScheme(config.schemeConfig)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n server.register(network, scheme)\n })\n } else {\n server.register('lightning:*', scheme)\n }\n\n return server\n}\n"],"mappings":";;;;;;;AA4CO,IAAM,kBAAN,MAAqD;AAAA,EAK1D,YAAY,QAA+B;AAJ3C,wBAAS,UAAS;AAClB,wBAAQ,gBAA8B,CAAC;AACvC,wBAAQ;AAGN,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,oBAAoB,QAAsC;AACxD,SAAK,aAAa,KAAK,MAAM;AAC7B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,WAAW,OAAc,SAAwC;AAErE,QAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;AACpE,UAAI,CAAC,MAAM,OAAO;AAChB,cAAM,IAAI,MAAM,sDAAsD,OAAO,EAAE;AAAA,MACjF;AACA,aAAO;AAAA,Q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QAAQ,KAAK,SAAS;AAAA,MACtB,OAAO;AAAA,MACP,OAAO;AAAA,QACL,QAAQ;AAAA,QACR,UAAU;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;;;AChJO,SAAS,wBACd,QACA,QACoB;AACpB,QAAM,SAAS,IAAI,gBAAgB,OAAO,YAAY;AAEtD,MAAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;AACjD,WAAO,SAAS,QAAQ,CAAC,YAAY;AACnC,aAAO,SAAS,SAAS,MAAM;AAAA,IACjC,CAAC;AAAA,EACH,OAAO;AACL,WAAO,SAAS,eAAe,MAAM;AAAA,EACvC;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import {
|
|
2
|
+
validateBolt11Invoice
|
|
3
|
+
} from "./chunk-MX3PAUPJ.mjs";
|
|
4
|
+
import {
|
|
5
|
+
SCHEME_EXACT,
|
|
6
|
+
__publicField
|
|
7
|
+
} from "./chunk-YWZC2RR7.mjs";
|
|
8
|
+
|
|
9
|
+
// src/lightning/client/scheme.ts
|
|
10
|
+
var LightningScheme = class {
|
|
11
|
+
/**
|
|
12
|
+
* Creates a new LightningScheme instance.
|
|
13
|
+
*
|
|
14
|
+
* @param signer - The Lightning signer for client operations
|
|
15
|
+
*/
|
|
16
|
+
constructor(signer) {
|
|
17
|
+
this.signer = signer;
|
|
18
|
+
__publicField(this, "scheme", SCHEME_EXACT);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Creates a payment payload for the Lightning scheme.
|
|
22
|
+
*
|
|
23
|
+
* 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice
|
|
24
|
+
* 2. Pays the invoice using the Lightning signer
|
|
25
|
+
* 3. Returns the preimage and payment hash as proof of payment
|
|
26
|
+
*
|
|
27
|
+
* @param t402Version - The t402 protocol version
|
|
28
|
+
* @param paymentRequirements - The payment requirements
|
|
29
|
+
* @returns Promise resolving to a payment payload
|
|
30
|
+
*/
|
|
31
|
+
async createPaymentPayload(t402Version, paymentRequirements) {
|
|
32
|
+
const bolt11Invoice = paymentRequirements.extra?.bolt11Invoice;
|
|
33
|
+
if (!bolt11Invoice) {
|
|
34
|
+
throw new Error("BOLT11 invoice is required in requirements.extra.bolt11Invoice");
|
|
35
|
+
}
|
|
36
|
+
if (!validateBolt11Invoice(bolt11Invoice)) {
|
|
37
|
+
throw new Error(`Invalid BOLT11 invoice format: ${bolt11Invoice.slice(0, 20)}...`);
|
|
38
|
+
}
|
|
39
|
+
const { preimage, paymentHash } = await this.signer.payInvoice(bolt11Invoice);
|
|
40
|
+
const payload = {
|
|
41
|
+
paymentHash,
|
|
42
|
+
preimage,
|
|
43
|
+
bolt11Invoice
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
t402Version,
|
|
47
|
+
payload
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// src/lightning/client/register.ts
|
|
53
|
+
function registerLightningScheme(client, config) {
|
|
54
|
+
const scheme = new LightningScheme(config.signer);
|
|
55
|
+
if (config.networks && config.networks.length > 0) {
|
|
56
|
+
config.networks.forEach((network) => {
|
|
57
|
+
client.register(network, scheme);
|
|
58
|
+
});
|
|
59
|
+
} else {
|
|
60
|
+
client.register("lightning:*", scheme);
|
|
61
|
+
}
|
|
62
|
+
if (config.policies) {
|
|
63
|
+
config.policies.forEach((policy) => {
|
|
64
|
+
client.registerPolicy(policy);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return client;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export {
|
|
71
|
+
LightningScheme,
|
|
72
|
+
registerLightningScheme
|
|
73
|
+
};
|
|
74
|
+
//# sourceMappingURL=chunk-3IOPLDQH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lightning/client/scheme.ts","../../src/lightning/client/register.ts"],"sourcesContent":["/**\n * Lightning Network Client Scheme Implementation\n *\n * Creates payment payloads for Lightning Network payments.\n * Pays BOLT11 invoices and returns preimage as proof of payment.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from '@t402/core/types'\nimport type { ClientLightningSigner } from '../../signer.js'\nimport type { LightningPayload } from '../../types.js'\nimport { SCHEME_EXACT } from '../../constants.js'\nimport { validateBolt11Invoice } from '../../utils.js'\n\n/**\n * Lightning Network client implementation for the Exact payment scheme.\n *\n * Pays BOLT11 invoices using a Lightning node and returns the\n * payment preimage as proof of payment.\n *\n * Note: The scheme is 'exact' because Lightning payments are always\n * for the exact invoice amount.\n */\nexport class LightningScheme implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT\n\n /**\n * Creates a new LightningScheme instance.\n *\n * @param signer - The Lightning signer for client operations\n */\n constructor(private readonly signer: ClientLightningSigner) {}\n\n /**\n * Creates a payment payload for the Lightning scheme.\n *\n * 1. Extracts the BOLT11 invoice from requirements.extra.bolt11Invoice\n * 2. Pays the invoice using the Lightning signer\n * 3. Returns the preimage and payment hash as proof of payment\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>> {\n // Extract BOLT11 invoice from requirements\n const bolt11Invoice = paymentRequirements.extra?.bolt11Invoice as string | undefined\n\n if (!bolt11Invoice) {\n throw new Error('BOLT11 invoice is required in requirements.extra.bolt11Invoice')\n }\n\n // Validate invoice format\n if (!validateBolt11Invoice(bolt11Invoice)) {\n throw new Error(`Invalid BOLT11 invoice format: ${bolt11Invoice.slice(0, 20)}...`)\n }\n\n // Pay the invoice\n const { preimage, paymentHash } = await this.signer.payInvoice(bolt11Invoice)\n\n // Create payload with proof of payment\n const payload: LightningPayload = {\n paymentHash,\n preimage,\n bolt11Invoice,\n }\n\n return {\n t402Version,\n payload,\n }\n }\n}\n","import { t402Client, PaymentPolicy } from '@t402/core/client'\nimport { Network } from '@t402/core/types'\nimport { ClientLightningSigner } from '../../signer.js'\nimport { LightningScheme } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402Client\n */\nexport interface LightningClientConfig {\n /**\n * The Lightning signer to use for paying invoices\n */\n signer: ClientLightningSigner\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[]\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (lightning:*)\n */\n networks?: Network[]\n}\n\n/**\n * Registers Lightning payment schemes to an t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for Lightning client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerLightningScheme } from \"@t402/btc/lightning/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerLightningScheme(client, {\n * signer: myLnSigner,\n * });\n * ```\n */\nexport function registerLightningScheme(\n client: t402Client,\n config: LightningClientConfig,\n): t402Client {\n const scheme = new LightningScheme(config.signer)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n client.register(network, scheme)\n })\n } else {\n client.register('lightning:*', scheme)\n }\n\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy)\n })\n }\n\n return client\n}\n"],"mappings":";;;;;;;;;AAsBO,IAAM,kBAAN,MAAqD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ1D,YAA6B,QAA+B;AAA/B;AAP7B,wBAAS,UAAS;AAAA,EAO2C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAa7D,MAAM,qBACJ,aACA,qBAC0D;AAE1D,UAAM,gBAAgB,oBAAoB,OAAO;AAEjD,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI,MAAM,gEAAgE;AAAA,IAClF;AAGA,QAAI,CAAC,sBAAsB,aAAa,GAAG;AACzC,YAAM,IAAI,MAAM,kCAAkC,cAAc,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,IACnF;AAGA,UAAM,EAAE,UAAU,YAAY,IAAI,MAAM,KAAK,OAAO,WAAW,aAAa;AAG5E,UAAM,UAA4B;AAAA,MAChC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;;;AC9BO,SAAS,wBACd,QACA,QACY;AACZ,QAAM,SAAS,IAAI,gBAAgB,OAAO,MAAM;AAEhD,MAAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;AACjD,WAAO,SAAS,QAAQ,CAAC,YAAY;AACnC,aAAO,SAAS,SAAS,MAAM;AAAA,IACjC,CAAC;AAAA,EACH,OAAO;AACL,WAAO,SAAS,eAAe,MAAM;AAAA,EACvC;AAEA,MAAI,OAAO,UAAU;AACnB,WAAO,SAAS,QAAQ,CAAC,WAAW;AAClC,aAAO,eAAe,MAAM;AAAA,IAC9B,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {
|
|
2
|
+
validateBitcoinAddress
|
|
3
|
+
} from "./chunk-MX3PAUPJ.mjs";
|
|
4
|
+
import {
|
|
5
|
+
DUST_LIMIT,
|
|
6
|
+
SCHEME_EXACT,
|
|
7
|
+
__publicField
|
|
8
|
+
} from "./chunk-YWZC2RR7.mjs";
|
|
9
|
+
|
|
10
|
+
// src/exact/client/scheme.ts
|
|
11
|
+
var ExactBtcScheme = class {
|
|
12
|
+
/**
|
|
13
|
+
* Creates a new ExactBtcScheme instance.
|
|
14
|
+
*
|
|
15
|
+
* @param signer - The Bitcoin signer for client operations
|
|
16
|
+
*/
|
|
17
|
+
constructor(signer) {
|
|
18
|
+
this.signer = signer;
|
|
19
|
+
__publicField(this, "scheme", SCHEME_EXACT);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Creates a payment payload for the Exact scheme.
|
|
23
|
+
*
|
|
24
|
+
* The payload contains a signed PSBT with a single output
|
|
25
|
+
* paying the required amount to the payTo address.
|
|
26
|
+
*
|
|
27
|
+
* @param t402Version - The t402 protocol version
|
|
28
|
+
* @param paymentRequirements - The payment requirements
|
|
29
|
+
* @returns Promise resolving to a payment payload
|
|
30
|
+
*/
|
|
31
|
+
async createPaymentPayload(t402Version, paymentRequirements) {
|
|
32
|
+
if (!paymentRequirements.payTo) {
|
|
33
|
+
throw new Error("PayTo address is required");
|
|
34
|
+
}
|
|
35
|
+
if (!paymentRequirements.amount) {
|
|
36
|
+
throw new Error("Amount is required");
|
|
37
|
+
}
|
|
38
|
+
if (!validateBitcoinAddress(paymentRequirements.payTo)) {
|
|
39
|
+
throw new Error(`Invalid Bitcoin address: ${paymentRequirements.payTo}`);
|
|
40
|
+
}
|
|
41
|
+
const amountSats = BigInt(paymentRequirements.amount);
|
|
42
|
+
if (amountSats < BigInt(DUST_LIMIT)) {
|
|
43
|
+
throw new Error(`Amount ${amountSats} satoshis is below dust limit (${DUST_LIMIT})`);
|
|
44
|
+
}
|
|
45
|
+
const unsignedPsbt = this.buildUnsignedPsbt(paymentRequirements);
|
|
46
|
+
const signedPsbt = await this.signer.signPsbt(unsignedPsbt);
|
|
47
|
+
const payload = {
|
|
48
|
+
signedPsbt
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
t402Version,
|
|
52
|
+
payload
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build an unsigned PSBT for the payment.
|
|
57
|
+
*
|
|
58
|
+
* Creates a minimal PSBT representation with the required output.
|
|
59
|
+
* The actual UTXO selection and fee calculation should be handled
|
|
60
|
+
* by the signer implementation (which typically has wallet context).
|
|
61
|
+
*
|
|
62
|
+
* @param requirements - Payment requirements
|
|
63
|
+
* @returns Base64-encoded unsigned PSBT
|
|
64
|
+
*/
|
|
65
|
+
buildUnsignedPsbt(requirements) {
|
|
66
|
+
const psbtData = {
|
|
67
|
+
outputs: [
|
|
68
|
+
{
|
|
69
|
+
address: requirements.payTo,
|
|
70
|
+
value: requirements.amount
|
|
71
|
+
}
|
|
72
|
+
],
|
|
73
|
+
network: requirements.network,
|
|
74
|
+
fromAddress: this.signer.getAddress(),
|
|
75
|
+
fromPubKey: this.signer.getPublicKey()
|
|
76
|
+
};
|
|
77
|
+
return Buffer.from(JSON.stringify(psbtData)).toString("base64");
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// src/exact/client/register.ts
|
|
82
|
+
function registerExactBtcScheme(client, config) {
|
|
83
|
+
const scheme = new ExactBtcScheme(config.signer);
|
|
84
|
+
if (config.networks && config.networks.length > 0) {
|
|
85
|
+
config.networks.forEach((network) => {
|
|
86
|
+
client.register(network, scheme);
|
|
87
|
+
});
|
|
88
|
+
} else {
|
|
89
|
+
client.register("bip122:*", scheme);
|
|
90
|
+
}
|
|
91
|
+
if (config.policies) {
|
|
92
|
+
config.policies.forEach((policy) => {
|
|
93
|
+
client.registerPolicy(policy);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return client;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export {
|
|
100
|
+
ExactBtcScheme,
|
|
101
|
+
registerExactBtcScheme
|
|
102
|
+
};
|
|
103
|
+
//# sourceMappingURL=chunk-7IU3Z36R.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/exact/client/scheme.ts","../../src/exact/client/register.ts"],"sourcesContent":["/**\n * Bitcoin On-chain Client Scheme Implementation\n *\n * Creates payment payloads for Bitcoin on-chain transfers using the exact scheme.\n * Builds PSBTs (Partially Signed Bitcoin Transactions) and signs them with the client's wallet.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from '@t402/core/types'\nimport type { ClientBtcSigner } from '../../signer.js'\nimport type { BtcOnchainPayload } from '../../types.js'\nimport { SCHEME_EXACT, DUST_LIMIT } from '../../constants.js'\nimport { validateBitcoinAddress } from '../../utils.js'\n\n/**\n * Bitcoin client implementation for the Exact payment scheme.\n *\n * Creates signed PSBTs for on-chain Bitcoin payments that can be\n * finalized and broadcast by a facilitator.\n */\nexport class ExactBtcScheme implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT\n\n /**\n * Creates a new ExactBtcScheme instance.\n *\n * @param signer - The Bitcoin signer for client operations\n */\n constructor(private readonly signer: ClientBtcSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * The payload contains a signed PSBT with a single output\n * paying the required amount to the payTo address.\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, 't402Version' | 'payload'>> {\n // Validate required fields\n if (!paymentRequirements.payTo) {\n throw new Error('PayTo address is required')\n }\n if (!paymentRequirements.amount) {\n throw new Error('Amount is required')\n }\n\n // Validate address format\n if (!validateBitcoinAddress(paymentRequirements.payTo)) {\n throw new Error(`Invalid Bitcoin address: ${paymentRequirements.payTo}`)\n }\n\n // Validate amount is above dust limit\n const amountSats = BigInt(paymentRequirements.amount)\n if (amountSats < BigInt(DUST_LIMIT)) {\n throw new Error(`Amount ${amountSats} satoshis is below dust limit (${DUST_LIMIT})`)\n }\n\n // Build an unsigned PSBT\n // The PSBT contains: output to payTo address for the required amount\n // Input selection and fee calculation are handled by the signer\n const unsignedPsbt = this.buildUnsignedPsbt(paymentRequirements)\n\n // Sign the PSBT\n const signedPsbt = await this.signer.signPsbt(unsignedPsbt)\n\n // Create payload\n const payload: BtcOnchainPayload = {\n signedPsbt,\n }\n\n return {\n t402Version,\n payload,\n }\n }\n\n /**\n * Build an unsigned PSBT for the payment.\n *\n * Creates a minimal PSBT representation with the required output.\n * The actual UTXO selection and fee calculation should be handled\n * by the signer implementation (which typically has wallet context).\n *\n * @param requirements - Payment requirements\n * @returns Base64-encoded unsigned PSBT\n */\n private buildUnsignedPsbt(requirements: PaymentRequirements): string {\n // Encode payment details as a JSON payload in the PSBT\n // The signer is responsible for building the full PSBT\n // with proper UTXO selection and fee estimation\n const psbtData = {\n outputs: [\n {\n address: requirements.payTo,\n value: requirements.amount,\n },\n ],\n network: requirements.network,\n fromAddress: this.signer.getAddress(),\n fromPubKey: this.signer.getPublicKey(),\n }\n\n // Encode as base64 for transport\n return Buffer.from(JSON.stringify(psbtData)).toString('base64')\n }\n}\n","import { t402Client, PaymentPolicy } from '@t402/core/client'\nimport { Network } from '@t402/core/types'\nimport { ClientBtcSigner } from '../../signer.js'\nimport { ExactBtcScheme } from './scheme.js'\n\n/**\n * Configuration options for registering BTC schemes to an t402Client\n */\nexport interface BtcClientConfig {\n /**\n * The Bitcoin signer to use for creating payment payloads\n */\n signer: ClientBtcSigner\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[]\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (bip122:*)\n */\n networks?: Network[]\n}\n\n/**\n * Registers Bitcoin exact payment schemes to an t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for BTC client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactBtcScheme } from \"@t402/btc/exact/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerExactBtcScheme(client, {\n * signer: myBtcSigner,\n * });\n * ```\n */\nexport function registerExactBtcScheme(client: t402Client, config: BtcClientConfig): t402Client {\n const scheme = new ExactBtcScheme(config.signer)\n\n if (config.networks && config.networks.length > 0) {\n config.networks.forEach((network) => {\n client.register(network, scheme)\n })\n } else {\n client.register('bip122:*', scheme)\n }\n\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy)\n })\n }\n\n return client\n}\n"],"mappings":";;;;;;;;;;AAmBO,IAAM,iBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YAA6B,QAAy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AAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;AACjD,WAAO,SAAS,QAAQ,CAAC,YAAY;AACnC,aAAO,SAAS,SAAS,MAAM;AAAA,IACjC,CAAC;AAAA,EACH,OAAO;AACL,WAAO,SAAS,YAAY,MAAM;AAAA,EACpC;AAEA,MAAI,OAAO,UAAU;AACnB,WAAO,SAAS,QAAQ,CAAC,WAAW;AAClC,aAAO,eAAe,MAAM;AAAA,IAC9B,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isValidHex
|
|
3
|
+
} from "./chunk-MX3PAUPJ.mjs";
|
|
4
|
+
import {
|
|
5
|
+
LIGHTNING_NETWORKS,
|
|
6
|
+
SCHEME_EXACT,
|
|
7
|
+
__publicField
|
|
8
|
+
} from "./chunk-YWZC2RR7.mjs";
|
|
9
|
+
|
|
10
|
+
// src/lightning/facilitator/scheme.ts
|
|
11
|
+
async function sha256Hex(preimageHex) {
|
|
12
|
+
const bytes = new Uint8Array(preimageHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
|
|
13
|
+
const hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", bytes);
|
|
14
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
15
|
+
return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
16
|
+
}
|
|
17
|
+
var LightningScheme = class {
|
|
18
|
+
constructor(signer) {
|
|
19
|
+
this.signer = signer;
|
|
20
|
+
__publicField(this, "scheme", SCHEME_EXACT);
|
|
21
|
+
__publicField(this, "caipFamily", "lightning:*");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Get mechanism-specific extra data for the supported kinds endpoint.
|
|
25
|
+
* Lightning has no extra data.
|
|
26
|
+
*/
|
|
27
|
+
getExtra(_network) {
|
|
28
|
+
return void 0;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Get signer addresses (node public keys) for this facilitator.
|
|
32
|
+
*/
|
|
33
|
+
getSigners(_network) {
|
|
34
|
+
return [...this.signer.getAddresses()];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Verifies a Lightning payment payload.
|
|
38
|
+
*
|
|
39
|
+
* Validates:
|
|
40
|
+
* 1. Payload structure (paymentHash, preimage, bolt11Invoice)
|
|
41
|
+
* 2. Preimage verification: SHA-256(preimage) === paymentHash
|
|
42
|
+
* 3. Payment lookup on the Lightning node
|
|
43
|
+
*/
|
|
44
|
+
async verify(payload, requirements) {
|
|
45
|
+
const lnPayload = payload.payload;
|
|
46
|
+
if (!lnPayload?.paymentHash || !lnPayload?.preimage || !lnPayload?.bolt11Invoice) {
|
|
47
|
+
return {
|
|
48
|
+
isValid: false,
|
|
49
|
+
invalidReason: "invalid_payload_structure",
|
|
50
|
+
payer: void 0
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
if (payload.accepted.scheme !== SCHEME_EXACT || requirements.scheme !== SCHEME_EXACT) {
|
|
54
|
+
return {
|
|
55
|
+
isValid: false,
|
|
56
|
+
invalidReason: "unsupported_scheme",
|
|
57
|
+
payer: void 0
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const validNetworks = LIGHTNING_NETWORKS;
|
|
61
|
+
if (!validNetworks.includes(requirements.network)) {
|
|
62
|
+
return {
|
|
63
|
+
isValid: false,
|
|
64
|
+
invalidReason: "unsupported_network",
|
|
65
|
+
payer: void 0
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (!isValidHex(lnPayload.preimage, 32)) {
|
|
69
|
+
return {
|
|
70
|
+
isValid: false,
|
|
71
|
+
invalidReason: "invalid_preimage_format",
|
|
72
|
+
payer: void 0
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
if (!isValidHex(lnPayload.paymentHash, 32)) {
|
|
76
|
+
return {
|
|
77
|
+
isValid: false,
|
|
78
|
+
invalidReason: "invalid_payment_hash_format",
|
|
79
|
+
payer: void 0
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
const computedHash = await sha256Hex(lnPayload.preimage);
|
|
84
|
+
if (computedHash !== lnPayload.paymentHash.toLowerCase()) {
|
|
85
|
+
return {
|
|
86
|
+
isValid: false,
|
|
87
|
+
invalidReason: "preimage_hash_mismatch",
|
|
88
|
+
payer: void 0
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
return {
|
|
93
|
+
isValid: false,
|
|
94
|
+
invalidReason: "preimage_verification_failed",
|
|
95
|
+
payer: void 0
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
const payment = await this.signer.lookupPayment(lnPayload.paymentHash);
|
|
100
|
+
if (!payment.settled) {
|
|
101
|
+
return {
|
|
102
|
+
isValid: false,
|
|
103
|
+
invalidReason: "payment_not_settled",
|
|
104
|
+
payer: void 0
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (payment.amountSats && BigInt(payment.amountSats) < BigInt(requirements.amount)) {
|
|
108
|
+
return {
|
|
109
|
+
isValid: false,
|
|
110
|
+
invalidReason: "insufficient_amount",
|
|
111
|
+
payer: void 0
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
console.warn("Could not verify payment with Lightning node:", error);
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
isValid: true,
|
|
119
|
+
invalidReason: void 0,
|
|
120
|
+
payer: void 0
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Settles a Lightning payment.
|
|
125
|
+
*
|
|
126
|
+
* Lightning payments are atomic (settle-on-pay), so this is effectively
|
|
127
|
+
* a confirmation that the payment was already completed. The actual
|
|
128
|
+
* settlement happened when the client paid the invoice.
|
|
129
|
+
*/
|
|
130
|
+
async settle(payload, requirements) {
|
|
131
|
+
const lnPayload = payload.payload;
|
|
132
|
+
if (!lnPayload?.paymentHash || !lnPayload?.preimage) {
|
|
133
|
+
return {
|
|
134
|
+
success: false,
|
|
135
|
+
network: payload.accepted.network,
|
|
136
|
+
transaction: "",
|
|
137
|
+
errorReason: "invalid_payload_structure",
|
|
138
|
+
payer: void 0
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
const verifyResult = await this.verify(payload, requirements);
|
|
142
|
+
if (!verifyResult.isValid) {
|
|
143
|
+
return {
|
|
144
|
+
success: false,
|
|
145
|
+
network: payload.accepted.network,
|
|
146
|
+
transaction: "",
|
|
147
|
+
errorReason: verifyResult.invalidReason ?? "verification_failed",
|
|
148
|
+
payer: void 0
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
success: true,
|
|
153
|
+
transaction: lnPayload.paymentHash,
|
|
154
|
+
network: payload.accepted.network,
|
|
155
|
+
payer: void 0
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// src/lightning/facilitator/register.ts
|
|
161
|
+
function registerLightningScheme(facilitator, config) {
|
|
162
|
+
facilitator.register(config.networks, new LightningScheme(config.signer));
|
|
163
|
+
return facilitator;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export {
|
|
167
|
+
LightningScheme,
|
|
168
|
+
registerLightningScheme
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=chunk-HNFWDITA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lightning/facilitator/scheme.ts","../../src/lightning/facilitator/register.ts"],"sourcesContent":["/**\n * Lightning Network Facilitator Scheme Implementation\n *\n * Verifies Lightning Network payments using preimage verification.\n * Lightning payments are atomic (settle-on-pay), so settlement is a no-op.\n */\n\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from '@t402/core/types'\nimport type { LightningPayload } from '../../types.js'\nimport { SCHEME_EXACT, LIGHTNING_NETWORKS } from '../../constants.js'\nimport { isValidHex } from '../../utils.js'\n\n/**\n * Facilitator Lightning signer interface\n */\nexport interface FacilitatorLightningSigner {\n /**\n * Get all node public keys this facilitator manages\n */\n getAddresses(): readonly string[]\n\n /**\n * Look up a payment by its payment hash\n *\n * @param paymentHash - Hex-encoded payment hash\n * @returns Payment status\n */\n lookupPayment(paymentHash: string): Promise<{\n settled: boolean\n amountSats?: string\n preimage?: string\n }>\n}\n\n/**\n * Compute SHA-256 hash of a hex-encoded preimage\n *\n * @param preimageHex - Hex-encoded preimage\n * @returns Hex-encoded SHA-256 hash\n */\nasync function sha256Hex(preimageHex: string): Promise<string> {\n const bytes = new Uint8Array(preimageHex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)))\n const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', bytes)\n const hashArray = new Uint8Array(hashBuffer)\n return Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Lightning Network facilitator implementation for the Exact payment scheme.\n *\n * Verification is done by checking that SHA-256(preimage) === paymentHash.\n * Lightning payments are atomic, so settle is a confirmation-only operation.\n */\nexport class LightningScheme implements SchemeNetworkFacilitator {\n readonly scheme = SCHEME_EXACT\n readonly caipFamily = 'lightning:*'\n\n constructor(private readonly signer: FacilitatorLightningSigner) {}\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * Lightning has no extra data.\n */\n getExtra(_network: string): Record<string, unknown> | undefined {\n return undefined\n }\n\n /**\n * Get signer addresses (node public keys) for this facilitator.\n */\n getSigners(_network: string): string[] {\n return [...this.signer.getAddresses()]\n }\n\n /**\n * Verifies a Lightning payment payload.\n *\n * Validates:\n * 1. Payload structure (paymentHash, preimage, bolt11Invoice)\n * 2. Preimage verification: SHA-256(preimage) === paymentHash\n * 3. Payment lookup on the Lightning node\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const lnPayload = payload.payload as LightningPayload | undefined\n\n // Validate payload structure\n if (!lnPayload?.paymentHash || !lnPayload?.preimage || !lnPayload?.bolt11Invoice) {\n return {\n isValid: false,\n invalidReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Verify scheme matches\n if (payload.accepted.scheme !== SCHEME_EXACT || requirements.scheme !== SCHEME_EXACT) {\n return {\n isValid: false,\n invalidReason: 'unsupported_scheme',\n payer: undefined,\n }\n }\n\n // Verify network is a valid Lightning network\n const validNetworks: readonly string[] = LIGHTNING_NETWORKS\n if (!validNetworks.includes(requirements.network)) {\n return {\n isValid: false,\n invalidReason: 'unsupported_network',\n payer: undefined,\n }\n }\n\n // Validate preimage format (32 bytes hex)\n if (!isValidHex(lnPayload.preimage, 32)) {\n return {\n isValid: false,\n invalidReason: 'invalid_preimage_format',\n payer: undefined,\n }\n }\n\n // Validate payment hash format (32 bytes hex)\n if (!isValidHex(lnPayload.paymentHash, 32)) {\n return {\n isValid: false,\n invalidReason: 'invalid_payment_hash_format',\n payer: undefined,\n }\n }\n\n // Core verification: SHA-256(preimage) must equal paymentHash\n try {\n const computedHash = await sha256Hex(lnPayload.preimage)\n\n if (computedHash !== lnPayload.paymentHash.toLowerCase()) {\n return {\n isValid: false,\n invalidReason: 'preimage_hash_mismatch',\n payer: undefined,\n }\n }\n } catch {\n return {\n isValid: false,\n invalidReason: 'preimage_verification_failed',\n payer: undefined,\n }\n }\n\n // Optionally verify with the Lightning node\n try {\n const payment = await this.signer.lookupPayment(lnPayload.paymentHash)\n\n if (!payment.settled) {\n return {\n isValid: false,\n invalidReason: 'payment_not_settled',\n payer: undefined,\n }\n }\n\n // Verify amount matches if available\n if (payment.amountSats && BigInt(payment.amountSats) < BigInt(requirements.amount)) {\n return {\n isValid: false,\n invalidReason: 'insufficient_amount',\n payer: undefined,\n }\n }\n } catch (error) {\n // If we can't verify with the node, the preimage verification is sufficient\n console.warn('Could not verify payment with Lightning node:', error)\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer: undefined,\n }\n }\n\n /**\n * Settles a Lightning payment.\n *\n * Lightning payments are atomic (settle-on-pay), so this is effectively\n * a confirmation that the payment was already completed. The actual\n * settlement happened when the client paid the invoice.\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const lnPayload = payload.payload as LightningPayload | undefined\n\n if (!lnPayload?.paymentHash || !lnPayload?.preimage) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: 'invalid_payload_structure',\n payer: undefined,\n }\n }\n\n // Verify the payment\n const verifyResult = await this.verify(payload, requirements)\n if (!verifyResult.isValid) {\n return {\n success: false,\n network: payload.accepted.network,\n transaction: '',\n errorReason: verifyResult.invalidReason ?? 'verification_failed',\n payer: undefined,\n }\n }\n\n // Lightning is settle-on-pay: the payment hash serves as the transaction ID\n return {\n success: true,\n transaction: lnPayload.paymentHash,\n network: payload.accepted.network,\n payer: undefined,\n }\n }\n}\n","import { t402Facilitator } from '@t402/core/facilitator'\nimport { Network } from '@t402/core/types'\nimport { FacilitatorLightningSigner, LightningScheme } from './scheme.js'\n\n/**\n * Configuration options for registering Lightning schemes to an t402Facilitator\n */\nexport interface LightningFacilitatorConfig {\n /**\n * The Lightning signer for facilitator operations\n */\n signer: FacilitatorLightningSigner\n\n /**\n * Networks to register (single network or array of networks)\n * Examples: \"lightning:mainnet\", [\"lightning:mainnet\", \"lightning:testnet\"]\n */\n networks: Network | Network[]\n}\n\n/**\n * Registers Lightning payment schemes to an t402Facilitator instance.\n *\n * @param facilitator - The t402Facilitator instance to register schemes to\n * @param config - Configuration for Lightning facilitator registration\n * @returns The facilitator instance for chaining\n */\nexport function registerLightningScheme(\n facilitator: t402Facilitator,\n config: LightningFacilitatorConfig,\n): t402Facilitator {\n facilitator.register(config.networks, new LightningScheme(config.signer))\n return facilitator\n}\n"],"mappings":";;;;;;;;;;AA8CA,eAAe,UAAU,aAAsC;AAC7D,QAAM,QAAQ,IAAI,WAAW,Y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,IACF;AAGA,UAAM,eAAe,MAAM,KAAK,OAAO,SAAS,YAAY;AAC5D,QAAI,CAAC,aAAa,SAAS;AACzB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,SAAS,QAAQ,SAAS;AAAA,QAC1B,aAAa;AAAA,QACb,aAAa,aAAa,iBAAiB;AAAA,QAC3C,OAAO;AAAA,MACT;AAAA,IACF;AAGA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,aAAa,UAAU;AAAA,MACvB,SAAS,QAAQ,SAAS;AAAA,MAC1B,OAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACjNO,SAAS,wBACd,aACA,QACiB;AACjB,cAAY,SAAS,OAAO,UAAU,IAAI,gBAAgB,OAAO,MAAM,CAAC;AACxE,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MAINNET_ADDRESS_PREFIXES,
|
|
3
|
+
SATS_PER_BTC,
|
|
4
|
+
TESTNET_ADDRESS_PREFIXES
|
|
5
|
+
} from "./chunk-YWZC2RR7.mjs";
|
|
6
|
+
|
|
7
|
+
// src/utils.ts
|
|
8
|
+
function satoshisToBtc(sats) {
|
|
9
|
+
const satsBigInt = BigInt(sats);
|
|
10
|
+
const whole = satsBigInt / BigInt(SATS_PER_BTC);
|
|
11
|
+
const frac = satsBigInt % BigInt(SATS_PER_BTC);
|
|
12
|
+
if (frac === 0n) {
|
|
13
|
+
return whole.toString();
|
|
14
|
+
}
|
|
15
|
+
const fracStr = frac.toString().padStart(8, "0");
|
|
16
|
+
return `${whole}.${fracStr}`.replace(/\.?0+$/, "");
|
|
17
|
+
}
|
|
18
|
+
function btcToSatoshis(btc) {
|
|
19
|
+
const btcStr = typeof btc === "number" ? btc.toString() : btc;
|
|
20
|
+
const [wholePart, fracPart = ""] = btcStr.split(".");
|
|
21
|
+
const paddedFrac = fracPart.padEnd(8, "0").slice(0, 8);
|
|
22
|
+
const combined = wholePart + paddedFrac;
|
|
23
|
+
const result = BigInt(combined.replace(/^0+/, "") || "0");
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
function validateBitcoinAddress(address) {
|
|
27
|
+
if (!address || address.length < 14 || address.length > 90) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const allPrefixes = [...MAINNET_ADDRESS_PREFIXES, ...TESTNET_ADDRESS_PREFIXES];
|
|
31
|
+
return allPrefixes.some((prefix) => address.startsWith(prefix));
|
|
32
|
+
}
|
|
33
|
+
function isMainnetAddress(address) {
|
|
34
|
+
return MAINNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix));
|
|
35
|
+
}
|
|
36
|
+
function isTestnetAddress(address) {
|
|
37
|
+
return TESTNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix));
|
|
38
|
+
}
|
|
39
|
+
function validateBolt11Invoice(invoice) {
|
|
40
|
+
if (!invoice || invoice.length < 20) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
const lower = invoice.toLowerCase();
|
|
44
|
+
return lower.startsWith("lnbc") || lower.startsWith("lntb") || lower.startsWith("lnbcrt");
|
|
45
|
+
}
|
|
46
|
+
function isValidHex(hex, expectedLength) {
|
|
47
|
+
if (!/^[0-9a-fA-F]+$/.test(hex)) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
if (expectedLength !== void 0 && hex.length !== expectedLength * 2) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
satoshisToBtc,
|
|
58
|
+
btcToSatoshis,
|
|
59
|
+
validateBitcoinAddress,
|
|
60
|
+
isMainnetAddress,
|
|
61
|
+
isTestnetAddress,
|
|
62
|
+
validateBolt11Invoice,
|
|
63
|
+
isValidHex
|
|
64
|
+
};
|
|
65
|
+
//# sourceMappingURL=chunk-MX3PAUPJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["/**\n * Bitcoin & Lightning Utility Functions\n *\n * Helper functions for address validation, unit conversion,\n * and invoice validation.\n */\n\nimport { SATS_PER_BTC, MAINNET_ADDRESS_PREFIXES, TESTNET_ADDRESS_PREFIXES } from './constants.js'\n\n/**\n * Convert satoshis to BTC\n *\n * @param sats - Amount in satoshis\n * @returns Amount in BTC as string (to avoid floating point issues)\n */\nexport function satoshisToBtc(sats: bigint | number | string): string {\n const satsBigInt = BigInt(sats)\n const whole = satsBigInt / BigInt(SATS_PER_BTC)\n const frac = satsBigInt % BigInt(SATS_PER_BTC)\n\n if (frac === 0n) {\n return whole.toString()\n }\n\n const fracStr = frac.toString().padStart(8, '0')\n return `${whole}.${fracStr}`.replace(/\\.?0+$/, '')\n}\n\n/**\n * Convert BTC to satoshis\n *\n * @param btc - Amount in BTC (string or number)\n * @returns Amount in satoshis as bigint\n */\nexport function btcToSatoshis(btc: string | number): bigint {\n const btcStr = typeof btc === 'number' ? btc.toString() : btc\n const [wholePart, fracPart = ''] = btcStr.split('.')\n const paddedFrac = fracPart.padEnd(8, '0').slice(0, 8)\n const combined = wholePart + paddedFrac\n const result = BigInt(combined.replace(/^0+/, '') || '0')\n return result\n}\n\n/**\n * Validate a Bitcoin address (basic format validation)\n *\n * Checks address prefix against known formats:\n * - Mainnet: bc1 (bech32), 1 (P2PKH), 3 (P2SH)\n * - Testnet: tb1 (bech32), m/n (P2PKH), 2 (P2SH)\n *\n * @param address - Bitcoin address to validate\n * @returns true if the address has a valid format\n */\nexport function validateBitcoinAddress(address: string): boolean {\n if (!address || address.length < 14 || address.length > 90) {\n return false\n }\n\n const allPrefixes = [...MAINNET_ADDRESS_PREFIXES, ...TESTNET_ADDRESS_PREFIXES]\n return allPrefixes.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for mainnet\n *\n * @param address - Bitcoin address\n * @returns true if mainnet address\n */\nexport function isMainnetAddress(address: string): boolean {\n return MAINNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Check if a Bitcoin address is for testnet\n *\n * @param address - Bitcoin address\n * @returns true if testnet address\n */\nexport function isTestnetAddress(address: string): boolean {\n return TESTNET_ADDRESS_PREFIXES.some((prefix) => address.startsWith(prefix))\n}\n\n/**\n * Validate a BOLT11 Lightning invoice (basic format validation)\n *\n * BOLT11 invoices follow the format:\n * - lnbc... for mainnet\n * - lntb... for testnet\n * - lnbcrt... for regtest\n *\n * @param invoice - BOLT11 invoice string\n * @returns true if the invoice has a valid format\n */\nexport function validateBolt11Invoice(invoice: string): boolean {\n if (!invoice || invoice.length < 20) {\n return false\n }\n\n const lower = invoice.toLowerCase()\n return lower.startsWith('lnbc') || lower.startsWith('lntb') || lower.startsWith('lnbcrt')\n}\n\n/**\n * Validate a hex-encoded string\n *\n * @param hex - String to validate\n * @param expectedLength - Expected byte length (hex length / 2)\n * @returns true if valid hex of expected length\n */\nexport function isValidHex(hex: string, expectedLength?: number): boolean {\n if (!/^[0-9a-fA-F]+$/.test(hex)) {\n return false\n }\n if (expectedLength !== undefined && hex.length !== expectedLength * 2) {\n return false\n }\n return true\n}\n"],"mappings":";;;;;;;AAeO,SAAS,cAAc,MAAwC;AACpE,QAAM,aAAa,OAAO,IAAI;AAC9B,QAAM,QAAQ,aAAa,OAAO,YAAY;AAC9C,QAAM,OAAO,aAAa,OAAO,YAAY;AAE7C,MAAI,SAAS,IAAI;AACf,WAAO,MAAM,SAAS;AAAA,EACxB;AAEA,QAAM,UAAU,KAAK,SAAS,EAAE,SAAS,GAAG,GAAG;AAC/C,SAAO,GAAG,KAAK,IAAI,OAAO,GAAG,QAAQ,UAAU,EAAE;AACnD;AAQO,SAAS,cAAc,KAA8B;AAC1D,QAAM,SAAS,OAAO,QAAQ,WAAW,IAAI,SAAS,IAAI;AAC1D,QAAM,CAAC,WAAW,WAAW,EAAE,IAAI,OAAO,MAAM,GAAG;AACnD,QAAM,aAAa,SAAS,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