Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25ecebcdcc | ||
|
|
e753fc66ab |
Executable
BIN
Binary file not shown.
+12
@@ -0,0 +1,12 @@
|
||||
# Cashu microservice configuration
|
||||
PORT=3333
|
||||
MINT_URL=https://kashu.me
|
||||
|
||||
# Optional: Set to true to enable debug logging
|
||||
DEBUG=true
|
||||
|
||||
# Optional: Set the maximum number of tokens to keep in memory
|
||||
MAX_REDEEMED_TOKENS=10000
|
||||
|
||||
# Optional: Set token expiration time in hours (0 for no expiration)
|
||||
TOKEN_EXPIRATION_HOURS=24
|
||||
@@ -0,0 +1,79 @@
|
||||
# Cashu Redeem Service
|
||||
|
||||
A microservice for redeeming Cashu tokens in the LightningTipBot.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Set environment variables:
|
||||
```bash
|
||||
export MINT_URL=https://mint.0xchat.com # or your preferred mint
|
||||
export PORT=3333 # optional, defaults to 3333
|
||||
```
|
||||
|
||||
3. Start the service:
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### POST /redeem
|
||||
Redeems a Cashu token and returns the amount.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"token": "cashuA1..."
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"amount": 1300
|
||||
}
|
||||
```
|
||||
|
||||
### POST /decode
|
||||
Decodes a Cashu token and returns its mint + proofs.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"token": "cashuA1..."
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"decoded": {
|
||||
"mint": "...",
|
||||
"proofs": [...]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### GET /health
|
||||
Health check endpoint.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "ok"
|
||||
}
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
- Tracks redeemed tokens to prevent double-spending
|
||||
- Validates token structure and mint
|
||||
- Rate limiting (TODO)
|
||||
- Token expiration (TODO)
|
||||
+423
@@ -0,0 +1,423 @@
|
||||
import express from 'express';
|
||||
import bodyParser from 'body-parser';
|
||||
import { CashuMint, CashuWallet, getDecodedToken } from '@cashu/cashu-ts';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
// Load environment variables
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const port = process.env.PORT || 3333;
|
||||
const debug = process.env.DEBUG === 'true';
|
||||
const maxRedeemedTokens = parseInt(process.env.MAX_REDEEMED_TOKENS || '10000');
|
||||
const tokenExpirationHours = parseInt(process.env.TOKEN_EXPIRATION_HOURS || '24');
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// Store for tracking redeemed tokens with timestamps
|
||||
const redeemedTokens = new Map();
|
||||
|
||||
// Initialize Cashu wallet
|
||||
const mintUrl = process.env.MINT_URL || 'https://kashu.me';
|
||||
const wallet = new CashuWallet(new CashuMint(mintUrl));
|
||||
|
||||
// Cleanup expired tokens periodically
|
||||
setInterval(() => {
|
||||
if (tokenExpirationHours > 0) {
|
||||
const now = Date.now();
|
||||
for (const [token, timestamp] of redeemedTokens.entries()) {
|
||||
if (now - timestamp > tokenExpirationHours * 60 * 60 * 1000) {
|
||||
redeemedTokens.delete(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 60 * 60 * 1000); // Check every hour
|
||||
|
||||
// Helper function to validate token format
|
||||
function isValidTokenFormat(token) {
|
||||
// Match both v1 and v3 token formats
|
||||
return /^cashu[abAB][a-zA-Z0-9-_]+$/.test(token);
|
||||
}
|
||||
|
||||
// Helper function to get token mint URL
|
||||
async function getTokenMintUrl(token) {
|
||||
try {
|
||||
const decoded = await getDecodedToken(token);
|
||||
if (!decoded) {
|
||||
if (debug) {
|
||||
console.error('Failed to decode token');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle both v1 and v3 token formats
|
||||
if (decoded.mint) {
|
||||
// v3 format
|
||||
return decoded.mint;
|
||||
} else if (decoded.token && decoded.token[0] && decoded.token[0].mint) {
|
||||
// v1 format
|
||||
return decoded.token[0].mint;
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.error('Invalid token structure:', decoded);
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error getting token mint URL:', error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to decode token
|
||||
async function decodeToken(token) {
|
||||
try {
|
||||
const decoded = await getDecodedToken(token);
|
||||
if (!decoded) {
|
||||
throw new Error('Failed to decode token');
|
||||
}
|
||||
|
||||
// Handle both v1 and v3 token formats
|
||||
if (decoded.proofs) {
|
||||
// v3 format
|
||||
return {
|
||||
proofs: decoded.proofs,
|
||||
mint: decoded.mint
|
||||
};
|
||||
} else if (decoded.token && decoded.token[0]) {
|
||||
// v1 format
|
||||
return {
|
||||
proofs: decoded.token[0].proofs,
|
||||
mint: decoded.token[0].mint
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error('Invalid token structure');
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error decoding token:', error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Redeem endpoint
|
||||
app.post('/redeem', async (req, res) => {
|
||||
try {
|
||||
const { token } = req.body;
|
||||
|
||||
if (!token) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Token is required'
|
||||
});
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log('Received token:', token);
|
||||
}
|
||||
|
||||
// Validate token format
|
||||
if (!isValidTokenFormat(token)) {
|
||||
if (debug) {
|
||||
console.error('Invalid token format:', token);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid token format. Must be a valid Cashu token'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if token was already redeemed
|
||||
if (redeemedTokens.has(token)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Token already redeemed'
|
||||
});
|
||||
}
|
||||
|
||||
// Get token mint URL
|
||||
const tokenMintUrl = await getTokenMintUrl(token);
|
||||
if (!tokenMintUrl) {
|
||||
if (debug) {
|
||||
console.error('Failed to get token mint URL for:', token);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid token format or unable to decode'
|
||||
});
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log('Token mint URL:', tokenMintUrl);
|
||||
}
|
||||
|
||||
// Decode and verify token
|
||||
let decoded;
|
||||
try {
|
||||
decoded = await decodeToken(token);
|
||||
if (debug) {
|
||||
console.log('Decoded token:', decoded);
|
||||
}
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error decoding token:', error);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Failed to decode token: ' + error.message
|
||||
});
|
||||
}
|
||||
|
||||
if (!decoded.proofs || !Array.isArray(decoded.proofs) || decoded.proofs.length === 0) {
|
||||
if (debug) {
|
||||
console.error('Invalid decoded token structure:', decoded);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid token format'
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate total amount
|
||||
const amount = decoded.proofs.reduce((sum, proof) => sum + (proof.amount || 0), 0);
|
||||
if (amount <= 0) {
|
||||
if (debug) {
|
||||
console.error('Token has no value:', decoded);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Token has no value'
|
||||
});
|
||||
}
|
||||
|
||||
// Mark token as redeemed with timestamp
|
||||
redeemedTokens.set(token, Date.now());
|
||||
|
||||
// Cleanup if we have too many tokens
|
||||
if (redeemedTokens.size > maxRedeemedTokens) {
|
||||
const oldestToken = redeemedTokens.entries().next().value[0];
|
||||
redeemedTokens.delete(oldestToken);
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log(`Redeemed token: ${token}, amount: ${amount}`);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
amount: amount,
|
||||
mint_url: tokenMintUrl,
|
||||
fee: 1, // 1 sat fee
|
||||
total_amount: amount,
|
||||
net_amount: amount - 1 // amount after fee
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error redeeming token:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Failed to redeem token: ' + error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Decode endpoint
|
||||
app.post('/decode', async (req, res) => {
|
||||
try {
|
||||
const { token } = req.body;
|
||||
|
||||
if (!token) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Token is required'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate token format
|
||||
if (!isValidTokenFormat(token)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid token format. Must start with cashuA or cashuB'
|
||||
});
|
||||
}
|
||||
|
||||
let decoded;
|
||||
try {
|
||||
decoded = await wallet.decodeToken(token);
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error decoding token:', error);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Failed to decode token: ' + error.message
|
||||
});
|
||||
}
|
||||
|
||||
if (!decoded) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid token format'
|
||||
});
|
||||
}
|
||||
|
||||
// Get token mint URL
|
||||
const tokenMintUrl = await getTokenMintUrl(token);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
decoded: decoded,
|
||||
mint_url: tokenMintUrl,
|
||||
format: token.startsWith('cashuA') ? 'cashuA' : 'cashuB'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error decoding token:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Failed to decode token: ' + error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Add /pay endpoint to handle invoice payments
|
||||
app.post('/pay', async (req, res) => {
|
||||
const { payment_request } = req.body;
|
||||
|
||||
if (!payment_request) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Payment request is required'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the mint URL from the last redeemed token
|
||||
const lastToken = Array.from(redeemedTokens.keys()).pop();
|
||||
if (!lastToken) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'No token has been redeemed yet'
|
||||
});
|
||||
}
|
||||
|
||||
const tokenMintUrl = await getTokenMintUrl(lastToken);
|
||||
if (!tokenMintUrl) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Could not determine mint URL'
|
||||
});
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log('Paying invoice:', payment_request);
|
||||
console.log('Using mint URL:', tokenMintUrl);
|
||||
}
|
||||
|
||||
// First, melt the token at the mint
|
||||
try {
|
||||
const decoded = await decodeToken(lastToken);
|
||||
if (!decoded || !decoded.proofs) {
|
||||
throw new Error('Invalid token structure');
|
||||
}
|
||||
|
||||
// Calculate total amount
|
||||
const amount = decoded.proofs.reduce((sum, proof) => sum + (proof.amount || 0), 0);
|
||||
|
||||
if (debug) {
|
||||
console.log('Melting token for amount:', amount);
|
||||
}
|
||||
|
||||
// Melt the token at the mint
|
||||
const meltResponse = await fetch(`${tokenMintUrl}/melt`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
proofs: decoded.proofs,
|
||||
pr: payment_request
|
||||
})
|
||||
});
|
||||
|
||||
if (!meltResponse.ok) {
|
||||
const error = await meltResponse.text();
|
||||
if (debug) {
|
||||
console.error('Error melting token:', error);
|
||||
}
|
||||
let errorMessage = 'Failed to melt token at mint';
|
||||
try {
|
||||
const errorJson = JSON.parse(error);
|
||||
if (errorJson.detail) {
|
||||
errorMessage = errorJson.detail;
|
||||
}
|
||||
} catch (e) {
|
||||
// If we can't parse the error as JSON, use the raw error text
|
||||
errorMessage = error;
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: errorMessage
|
||||
});
|
||||
}
|
||||
|
||||
const meltResult = await meltResponse.json();
|
||||
if (!meltResult.paid) {
|
||||
if (debug) {
|
||||
console.error('Token melted but payment failed:', meltResult);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Token melted but payment failed'
|
||||
});
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log('Token melted successfully:', meltResult);
|
||||
}
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
message: 'Invoice paid successfully',
|
||||
change: meltResult.change
|
||||
});
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error in token melting:', error);
|
||||
}
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Failed to process token: ' + error.message
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (debug) {
|
||||
console.error('Error in /pay:', error);
|
||||
}
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({
|
||||
status: 'ok',
|
||||
mint_url: mintUrl,
|
||||
redeemed_tokens: redeemedTokens.size,
|
||||
debug_mode: debug,
|
||||
max_tokens: maxRedeemedTokens,
|
||||
token_expiration_hours: tokenExpirationHours
|
||||
});
|
||||
});
|
||||
|
||||
// Start the server
|
||||
app.listen(port, () => {
|
||||
console.log(`Cashu redeem service listening on port ${port}`);
|
||||
console.log(`Using mint URL: ${mintUrl}`);
|
||||
console.log(`Debug mode: ${debug}`);
|
||||
console.log(`Token expiration: ${tokenExpirationHours} hours`);
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
../mime/cli.js
|
||||
+885
@@ -0,0 +1,885 @@
|
||||
{
|
||||
"name": "cashu-redeem-service",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/@cashu/cashu-ts": {
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@cashu/cashu-ts/-/cashu-ts-2.5.2.tgz",
|
||||
"integrity": "sha512-AjfDOZKb3RWWhmpHABC4KJxwJs3wp6eOFg6U3S6d3QOqtSoNkceMTn6lLN4/bYQarLR19rysbrIJ8MHsSwNxeQ==",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.6.0",
|
||||
"@noble/hashes": "^1.5.0",
|
||||
"@scure/bip32": "^1.5.0",
|
||||
"buffer": "^6.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz",
|
||||
"integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "1.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scure/base": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.5.tgz",
|
||||
"integrity": "sha512-9rE6EOVeIQzt5TSu4v+K523F8u6DhBsoZWPGKlnCshhlDhy0kJzUX4V+tr2dWmzF1GdekvThABoEQBGBQI7xZw==",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@scure/bip32": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz",
|
||||
"integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==",
|
||||
"dependencies": {
|
||||
"@noble/curves": "~1.9.0",
|
||||
"@noble/hashes": "~1.8.0",
|
||||
"@scure/base": "~1.2.5"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.3",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
|
||||
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.4.24",
|
||||
"on-finished": "2.4.1",
|
||||
"qs": "6.13.0",
|
||||
"raw-body": "2.5.2",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bound": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
|
||||
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
||||
"dependencies": {
|
||||
"safe-buffer": "5.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "0.7.1",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
|
||||
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-signature": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
||||
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/destroy": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
|
||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.5.0",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz",
|
||||
"integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
|
||||
},
|
||||
"node_modules/encodeurl": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
|
||||
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="
|
||||
},
|
||||
"node_modules/etag": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
|
||||
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.21.2",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
|
||||
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.8",
|
||||
"array-flatten": "1.1.1",
|
||||
"body-parser": "1.20.3",
|
||||
"content-disposition": "0.5.4",
|
||||
"content-type": "~1.0.4",
|
||||
"cookie": "0.7.1",
|
||||
"cookie-signature": "1.0.6",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"finalhandler": "1.3.1",
|
||||
"fresh": "0.5.2",
|
||||
"http-errors": "2.0.0",
|
||||
"merge-descriptors": "1.0.3",
|
||||
"methods": "~1.1.2",
|
||||
"on-finished": "2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"path-to-regexp": "0.1.12",
|
||||
"proxy-addr": "~2.0.7",
|
||||
"qs": "6.13.0",
|
||||
"range-parser": "~1.2.1",
|
||||
"safe-buffer": "5.2.1",
|
||||
"send": "0.19.0",
|
||||
"serve-static": "1.16.2",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "2.0.1",
|
||||
"type-is": "~1.6.18",
|
||||
"utils-merge": "1.0.1",
|
||||
"vary": "~1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
|
||||
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"on-finished": "2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"statuses": "2.0.1",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fresh": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
|
||||
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/function-bind": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
|
||||
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
|
||||
"dependencies": {
|
||||
"depd": "2.0.0",
|
||||
"inherits": "2.0.4",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "2.0.1",
|
||||
"toidentifier": "1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"node_modules/ipaddr.js": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
||||
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/media-typer": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/methods": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
|
||||
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
||||
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
|
||||
"bin": {
|
||||
"mime": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
||||
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
|
||||
"dependencies": {
|
||||
"ee-first": "1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "0.1.12",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
|
||||
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ=="
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
|
||||
"dependencies": {
|
||||
"forwarded": "0.2.0",
|
||||
"ipaddr.js": "1.9.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.13.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
|
||||
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
|
||||
"dependencies": {
|
||||
"side-channel": "^1.0.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
|
||||
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.4.24",
|
||||
"unpipe": "1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
},
|
||||
"node_modules/send": {
|
||||
"version": "0.19.0",
|
||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz",
|
||||
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"encodeurl": "~1.0.2",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"fresh": "0.5.2",
|
||||
"http-errors": "2.0.0",
|
||||
"mime": "1.6.0",
|
||||
"ms": "2.1.3",
|
||||
"on-finished": "2.4.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"statuses": "2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/encodeurl": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
|
||||
"integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/serve-static": {
|
||||
"version": "1.16.2",
|
||||
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz",
|
||||
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
|
||||
"dependencies": {
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"parseurl": "~1.3.3",
|
||||
"send": "0.19.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
|
||||
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-list": "^1.0.0",
|
||||
"side-channel-map": "^1.0.1",
|
||||
"side-channel-weakmap": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-list": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
|
||||
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-map": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-weakmap": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-map": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
|
||||
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
||||
"dependencies": {
|
||||
"media-typer": "0.3.0",
|
||||
"mime-types": "~2.1.24"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
|
||||
"engines": {
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vary": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Cashu
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
# Cashu TS
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[code coverage](https://cashubtc.github.io/cashu-ts/coverage)
|
||||
|
||||
⚠️ **Don't be reckless:** This project is in early development, it does however work with real sats! Always use amounts you don't mind losing.
|
||||
|
||||
Cashu TS is a JavaScript library for [Cashu](https://github.com/cashubtc) wallets written in Typescript.
|
||||
|
||||
Wallet Features:
|
||||
|
||||
- [x] connect to mint (load keys)
|
||||
- [x] request minting tokens
|
||||
- [x] minting tokens
|
||||
- [x] sending tokens (get encoded token for chosen value)
|
||||
- [x] receiving tokens
|
||||
- [x] melting tokens
|
||||
- [x] check if tokens are spent
|
||||
- [ ] ...
|
||||
|
||||
Implemented [NUTs](https://github.com/cashubtc/nuts/):
|
||||
|
||||
- [x] [NUT-00](https://github.com/cashubtc/nuts/blob/main/00.md)
|
||||
- [x] [NUT-01](https://github.com/cashubtc/nuts/blob/main/01.md)
|
||||
- [x] [NUT-02](https://github.com/cashubtc/nuts/blob/main/02.md)
|
||||
- [x] [NUT-03](https://github.com/cashubtc/nuts/blob/main/03.md)
|
||||
- [x] [NUT-04](https://github.com/cashubtc/nuts/blob/main/04.md)
|
||||
- [x] [NUT-05](https://github.com/cashubtc/nuts/blob/main/05.md)
|
||||
- [x] [NUT-06](https://github.com/cashubtc/nuts/blob/main/06.md)
|
||||
- [x] [NUT-07](https://github.com/cashubtc/nuts/blob/main/07.md)
|
||||
- [x] [NUT-08](https://github.com/cashubtc/nuts/blob/main/08.md)
|
||||
- [x] [NUT-09](https://github.com/cashubtc/nuts/blob/main/09.md)
|
||||
- [x] [NUT-11](https://github.com/cashubtc/nuts/blob/main/11.md)
|
||||
- [x] [NUT-18](https://github.com/cashubtc/nuts/blob/main/18.md)
|
||||
|
||||
Supported token formats:
|
||||
|
||||
- [x] v1 read
|
||||
- [x] v2 read (deprecated)
|
||||
- [x] v3 read/write
|
||||
- [x] v4 read/write
|
||||
|
||||
## Usage
|
||||
|
||||
Go to the [docs](https://cashubtc.github.io/cashu-ts/docs/main) for detailed usage, or have a look at the [integration tests](./test/integration.test.ts) for examples on how to implement a wallet.
|
||||
|
||||
### Install
|
||||
|
||||
```shell
|
||||
npm i @cashu/cashu-ts
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
#### Mint tokens
|
||||
|
||||
```typescript
|
||||
import { CashuMint, CashuWallet, MintQuoteState } from '@cashu/cashu-ts';
|
||||
const mintUrl = 'http://localhost:3338';
|
||||
const mint = new CashuMint(mintUrl);
|
||||
const wallet = new CashuWallet(mint);
|
||||
await wallet.loadMint(); // persist wallet.keys and wallet.keysets to avoid calling loadMint() in the future
|
||||
const mintQuote = await wallet.createMintQuote(64);
|
||||
// pay the invoice here before you continue...
|
||||
const mintQuoteChecked = await wallet.checkMintQuote(mintQuote.quote);
|
||||
if (mintQuoteChecked.state == MintQuoteState.PAID) {
|
||||
const proofs = await wallet.mintProofs(64, mintQuote.quote);
|
||||
}
|
||||
```
|
||||
|
||||
#### Melt tokens
|
||||
|
||||
```typescript
|
||||
import { CashuMint, CashuWallet } from '@cashu/cashu-ts';
|
||||
const mintUrl = 'http://localhost:3338'; // the mint URL
|
||||
const mint = new CashuMint(mintUrl);
|
||||
const wallet = new CashuWallet(mint); // load the keysets of the mint
|
||||
|
||||
const invoice = 'lnbc......'; // Lightning invoice to pay
|
||||
const meltQuote = await wallet.createMeltQuote(invoice);
|
||||
const amountToSend = meltQuote.amount + meltQuote.fee_reserve;
|
||||
|
||||
// CashuWallet.send performs coin selection and swaps the proofs with the mint
|
||||
// if no appropriate amount can be selected offline. We must include potential
|
||||
// ecash fees that the mint might require to melt the resulting proofsToSend later.
|
||||
const { keep: proofsToKeep, send: proofsToSend } = await wallet.send(amountToSend, proofs, {
|
||||
includeFees: true
|
||||
});
|
||||
// store proofsToKeep in wallet ..
|
||||
|
||||
const meltResponse = await wallet.meltProofs(meltQuote, proofsToSend);
|
||||
// store meltResponse.change in wallet ..
|
||||
```
|
||||
|
||||
#### Create a token and receive it
|
||||
|
||||
```typescript
|
||||
// we assume that `wallet` already minted `proofs`, as above
|
||||
const { keep, send } = await wallet.send(32, proofs);
|
||||
const token = getEncodedTokenV4({ mint: mintUrl, proofs: send });
|
||||
console.log(token);
|
||||
|
||||
const wallet2 = new CashuWallet(mint); // receiving wallet
|
||||
const receiveProofs = await wallet2.receive(token);
|
||||
```
|
||||
|
||||
#### Get token data
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const decodedToken = getDecodedToken(token);
|
||||
console.log(decodedToken); // { mint: "https://mint.0xchat.com", unit: "sat", proofs: [...] }
|
||||
} catch (_) {
|
||||
console.log('Invalid token');
|
||||
}
|
||||
```
|
||||
|
||||
## Contribute
|
||||
|
||||
Contributions are very welcome.
|
||||
|
||||
If you want to contribute, please open an Issue or a PR.
|
||||
If you open a PR, please do so from the `development` branch as the base branch.
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
||||
"mainEntryPointFilePath": "<projectFolder>/lib/types/index.d.ts",
|
||||
"bundledPackages": [],
|
||||
|
||||
"apiReport": {
|
||||
"enabled": true
|
||||
},
|
||||
|
||||
"docModel": {
|
||||
/**
|
||||
* (REQUIRED) Whether to generate a doc model file.
|
||||
*/
|
||||
"enabled": true
|
||||
|
||||
/**
|
||||
* The output path for the doc model file. The file extension should be ".api.json".
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: "<projectFolder>/temp/<unscopedPackageName>.api.json"
|
||||
*/
|
||||
// "apiJsonFilePath": "<projectFolder>/temp/<unscopedPackageName>.api.json",
|
||||
|
||||
/**
|
||||
* Whether "forgotten exports" should be included in the doc model file. Forgotten exports are declarations
|
||||
* flagged with `ae-forgotten-export` warnings. See https://api-extractor.com/pages/messages/ae-forgotten-export/ to
|
||||
* learn more.
|
||||
*
|
||||
* DEFAULT VALUE: "false"
|
||||
*/
|
||||
// "includeForgottenExports": false,
|
||||
|
||||
/**
|
||||
* The base URL where the project's source code can be viewed on a website such as GitHub or
|
||||
* Azure DevOps. This URL path corresponds to the `<projectFolder>` path on disk.
|
||||
*
|
||||
* This URL is concatenated with the file paths serialized to the doc model to produce URL file paths to individual API items.
|
||||
* For example, if the `projectFolderUrl` is "https://github.com/microsoft/rushstack/tree/main/apps/api-extractor" and an API
|
||||
* item's file path is "api/ExtractorConfig.ts", the full URL file path would be
|
||||
* "https://github.com/microsoft/rushstack/tree/main/apps/api-extractor/api/ExtractorConfig.js".
|
||||
*
|
||||
* This setting can be omitted if you don't need source code links in your API documentation reference.
|
||||
*
|
||||
* SUPPORTED TOKENS: none
|
||||
* DEFAULT VALUE: ""
|
||||
*/
|
||||
// "projectFolderUrl": "http://github.com/path/to/your/projectFolder"
|
||||
},
|
||||
|
||||
/**
|
||||
* Configures how the .d.ts rollup file will be generated.
|
||||
*/
|
||||
"dtsRollup": {
|
||||
/**
|
||||
* (REQUIRED) Whether to generate the .d.ts rollup file.
|
||||
*/
|
||||
"enabled": false
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
|
||||
* This file will include all declarations that are exported by the main entry point.
|
||||
*
|
||||
* If the path is an empty string, then this file will not be written.
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
|
||||
*/
|
||||
// "untrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>.d.ts",
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated with trimming for an "alpha" release.
|
||||
* This file will include only declarations that are marked as "@public", "@beta", or "@alpha".
|
||||
*
|
||||
* If the path is an empty string, then this file will not be written.
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: ""
|
||||
*/
|
||||
// "alphaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-alpha.d.ts",
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release.
|
||||
* This file will include only declarations that are marked as "@public" or "@beta".
|
||||
*
|
||||
* If the path is an empty string, then this file will not be written.
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: ""
|
||||
*/
|
||||
// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release.
|
||||
* This file will include only declarations that are marked as "@public".
|
||||
*
|
||||
* If the path is an empty string, then this file will not be written.
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: ""
|
||||
*/
|
||||
// "publicTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-public.d.ts",
|
||||
|
||||
/**
|
||||
* When a declaration is trimmed, by default it will be replaced by a code comment such as
|
||||
* "Excluded from this release type: exampleMember". Set "omitTrimmingComments" to true to remove the
|
||||
* declaration completely.
|
||||
*
|
||||
* DEFAULT VALUE: false
|
||||
*/
|
||||
// "omitTrimmingComments": true
|
||||
},
|
||||
|
||||
/**
|
||||
* Configures how the tsdoc-metadata.json file will be generated.
|
||||
*/
|
||||
"tsdocMetadata": {
|
||||
/**
|
||||
* Whether to generate the tsdoc-metadata.json file.
|
||||
*
|
||||
* DEFAULT VALUE: true
|
||||
*/
|
||||
// "enabled": true,
|
||||
/**
|
||||
* Specifies where the TSDoc metadata file should be written.
|
||||
*
|
||||
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
|
||||
* prepend a folder token such as "<projectFolder>".
|
||||
*
|
||||
* The default value is "<lookup>", which causes the path to be automatically inferred from the "tsdocMetadata",
|
||||
* "typings" or "main" fields of the project's package.json. If none of these fields are set, the lookup
|
||||
* falls back to "tsdoc-metadata.json" in the package folder.
|
||||
*
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: "<lookup>"
|
||||
*/
|
||||
// "tsdocMetadataFilePath": "<projectFolder>/dist/tsdoc-metadata.json"
|
||||
},
|
||||
|
||||
/**
|
||||
* Configures how API Extractor reports error and warning messages produced during analysis.
|
||||
*
|
||||
* There are three sources of messages: compiler messages, API Extractor messages, and TSDoc messages.
|
||||
*/
|
||||
"messages": {
|
||||
/**
|
||||
* Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing
|
||||
* the input .d.ts files.
|
||||
*
|
||||
* TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551"
|
||||
*
|
||||
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
|
||||
*/
|
||||
"compilerMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Configures handling of messages reported by API Extractor during its analysis.
|
||||
*
|
||||
* API Extractor message identifiers start with "ae-". For example: "ae-extra-release-tag"
|
||||
*
|
||||
* DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings
|
||||
*/
|
||||
"extractorMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
},
|
||||
|
||||
"ae-missing-release-tag": {
|
||||
"logLevel": "none"
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Configures handling of messages reported by the TSDoc parser when analyzing code comments.
|
||||
*
|
||||
* TSDoc message identifiers start with "tsdoc-". For example: "tsdoc-link-tag-unescaped-text"
|
||||
*
|
||||
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
|
||||
*/
|
||||
"tsdocMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "none"
|
||||
// "addToApiReportFile": false
|
||||
}
|
||||
|
||||
// "tsdoc-link-tag-unescaped-text": {
|
||||
// "logLevel": "warning",
|
||||
// "addToApiReportFile": true
|
||||
// },
|
||||
//
|
||||
// . . .
|
||||
}
|
||||
}
|
||||
}
|
||||
+924
@@ -0,0 +1,924 @@
|
||||
## API Report File for "@cashu/cashu-ts"
|
||||
|
||||
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
|
||||
|
||||
```ts
|
||||
|
||||
import { MintContactInfo as MintContactInfo_2 } from './types';
|
||||
|
||||
// @public
|
||||
export type ApiError = {
|
||||
error?: string;
|
||||
code?: number;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type BlindAuthMintPayload = {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type BlindAuthMintResponse = {
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
|
||||
// @public
|
||||
export class CashuAuthMint {
|
||||
// Warning: (ae-forgotten-export) The symbol "request" needs to be exported by the entry point index.d.ts
|
||||
constructor(_mintUrl: string, _customRequest?: typeof request | undefined);
|
||||
static getKeys(mintUrl: string, keysetId?: string, customRequest?: typeof request): Promise<MintActiveKeys>;
|
||||
getKeys(keysetId?: string, mintUrl?: string): Promise<MintActiveKeys>;
|
||||
static getKeySets(mintUrl: string, customRequest?: typeof request): Promise<MintAllKeysets>;
|
||||
getKeySets(): Promise<MintAllKeysets>;
|
||||
static mint(mintUrl: string, mintPayload: BlindAuthMintPayload, clearAuthToken: string, customRequest?: typeof request): Promise<BlindAuthMintResponse>;
|
||||
mint(mintPayload: BlindAuthMintPayload, clearAuthToken: string): Promise<BlindAuthMintResponse>;
|
||||
// (undocumented)
|
||||
get mintUrl(): string;
|
||||
}
|
||||
|
||||
// @public
|
||||
export class CashuAuthWallet {
|
||||
constructor(mint: CashuAuthMint, options?: {
|
||||
keys?: Array<MintKeys> | MintKeys;
|
||||
keysets?: Array<MintKeyset>;
|
||||
});
|
||||
getActiveKeyset(keysets: Array<MintKeyset>): MintKeyset;
|
||||
getAllKeys(): Promise<Array<MintKeys>>;
|
||||
getKeys(keysetId?: string, forceRefresh?: boolean): Promise<MintKeys>;
|
||||
getKeySets(): Promise<Array<MintKeyset>>;
|
||||
// (undocumented)
|
||||
get keys(): Map<string, MintKeys>;
|
||||
// (undocumented)
|
||||
get keysetId(): string;
|
||||
set keysetId(keysetId: string);
|
||||
// (undocumented)
|
||||
get keysets(): Array<MintKeyset>;
|
||||
loadMint(): Promise<void>;
|
||||
// (undocumented)
|
||||
mint: CashuAuthMint;
|
||||
mintProofs(amount: number, clearAuthToken: string, options?: {
|
||||
keysetId?: string;
|
||||
}): Promise<Array<Proof>>;
|
||||
}
|
||||
|
||||
// @public
|
||||
export class CashuMint {
|
||||
constructor(_mintUrl: string, _customRequest?: typeof request | undefined, authTokenGetter?: () => Promise<string>);
|
||||
static check(mintUrl: string, checkPayload: CheckStatePayload, customRequest?: typeof request): Promise<CheckStateResponse>;
|
||||
check(checkPayload: CheckStatePayload): Promise<CheckStateResponse>;
|
||||
static checkMeltQuote(mintUrl: string, quote: string, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
checkMeltQuote(quote: string): Promise<PartialMeltQuoteResponse>;
|
||||
static checkMintQuote(mintUrl: string, quote: string, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMintQuoteResponse>;
|
||||
checkMintQuote(quote: string): Promise<PartialMintQuoteResponse>;
|
||||
connectWebSocket(): Promise<void>;
|
||||
static createMeltQuote(mintUrl: string, meltQuotePayload: MeltQuotePayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
createMeltQuote(meltQuotePayload: MeltQuotePayload): Promise<PartialMeltQuoteResponse>;
|
||||
static createMintQuote(mintUrl: string, mintQuotePayload: MintQuotePayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMintQuoteResponse>;
|
||||
createMintQuote(mintQuotePayload: MintQuotePayload): Promise<PartialMintQuoteResponse>;
|
||||
disconnectWebSocket(): void;
|
||||
static getInfo(mintUrl: string, customRequest?: typeof request): Promise<GetInfoResponse>;
|
||||
getInfo(): Promise<GetInfoResponse>;
|
||||
static getKeys(mintUrl: string, keysetId?: string, customRequest?: typeof request): Promise<MintActiveKeys>;
|
||||
getKeys(keysetId?: string, mintUrl?: string): Promise<MintActiveKeys>;
|
||||
static getKeySets(mintUrl: string, customRequest?: typeof request): Promise<MintAllKeysets>;
|
||||
getKeySets(): Promise<MintAllKeysets>;
|
||||
// Warning: (ae-forgotten-export) The symbol "MintInfo" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// (undocumented)
|
||||
getLazyMintInfo(): Promise<MintInfo>;
|
||||
// (undocumented)
|
||||
handleBlindAuth(path: string): Promise<string | undefined>;
|
||||
static melt(mintUrl: string, meltPayload: MeltPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
melt(meltPayload: MeltPayload): Promise<PartialMeltQuoteResponse>;
|
||||
static mint(mintUrl: string, mintPayload: MintPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<MintResponse>;
|
||||
mint(mintPayload: MintPayload): Promise<MintResponse>;
|
||||
// (undocumented)
|
||||
get mintUrl(): string;
|
||||
// (undocumented)
|
||||
static restore(mintUrl: string, restorePayload: PostRestorePayload, customRequest?: typeof request): Promise<PostRestoreResponse>;
|
||||
// (undocumented)
|
||||
restore(restorePayload: {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
}): Promise<PostRestoreResponse>;
|
||||
static swap(mintUrl: string, swapPayload: SwapPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<SwapResponse>;
|
||||
swap(swapPayload: SwapPayload): Promise<SwapResponse>;
|
||||
// Warning: (ae-forgotten-export) The symbol "WSConnection" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// (undocumented)
|
||||
get webSocketConnection(): WSConnection | undefined;
|
||||
}
|
||||
|
||||
// @public
|
||||
export class CashuWallet {
|
||||
constructor(mint: CashuMint, options?: {
|
||||
unit?: string;
|
||||
keys?: Array<MintKeys> | MintKeys;
|
||||
keysets?: Array<MintKeyset>;
|
||||
mintInfo?: GetInfoResponse;
|
||||
bip39seed?: Uint8Array;
|
||||
denominationTarget?: number;
|
||||
keepFactory?: OutputDataFactory;
|
||||
});
|
||||
batchRestore(gapLimit?: number, batchSize?: number, counter?: number, keysetId?: string): Promise<{
|
||||
proofs: Array<Proof>;
|
||||
lastCounterWithSignature?: number;
|
||||
}>;
|
||||
checkMeltQuote(quote: string): Promise<PartialMeltQuoteResponse>;
|
||||
// (undocumented)
|
||||
checkMeltQuote(quote: MeltQuoteResponse): Promise<MeltQuoteResponse>;
|
||||
checkMintQuote(quote: MintQuoteResponse): Promise<MintQuoteResponse>;
|
||||
// (undocumented)
|
||||
checkMintQuote(quote: string): Promise<PartialMintQuoteResponse>;
|
||||
checkProofsStates(proofs: Array<Proof>): Promise<Array<ProofState>>;
|
||||
createLockedMintQuote(amount: number, pubkey: string, description?: string): Promise<LockedMintQuoteResponse>;
|
||||
createMeltQuote(invoice: string): Promise<MeltQuoteResponse>;
|
||||
createMintQuote(amount: number, description?: string): Promise<MintQuoteResponse>;
|
||||
createMultiPathMeltQuote(invoice: string, millisatPartialAmount: number): Promise<MeltQuoteResponse>;
|
||||
getActiveKeyset(keysets: Array<MintKeyset>): MintKeyset;
|
||||
getAllKeys(): Promise<Array<MintKeys>>;
|
||||
getFeesForKeyset(nInputs: number, keysetId: string): number;
|
||||
getFeesForProofs(proofs: Array<Proof>): number;
|
||||
getKeys(keysetId?: string, forceRefresh?: boolean): Promise<MintKeys>;
|
||||
getKeySets(): Promise<Array<MintKeyset>>;
|
||||
getMintInfo(): Promise<MintInfo>;
|
||||
// (undocumented)
|
||||
get keys(): Map<string, MintKeys>;
|
||||
// (undocumented)
|
||||
get keysetId(): string;
|
||||
set keysetId(keysetId: string);
|
||||
// (undocumented)
|
||||
get keysets(): Array<MintKeyset>;
|
||||
lazyGetMintInfo(): Promise<MintInfo>;
|
||||
loadMint(): Promise<void>;
|
||||
meltProofs(meltQuote: MeltQuoteResponse, proofsToSend: Array<Proof>, options?: MeltProofOptions): Promise<MeltProofsResponse>;
|
||||
// (undocumented)
|
||||
mint: CashuMint;
|
||||
// (undocumented)
|
||||
get mintInfo(): MintInfo;
|
||||
mintProofs(amount: number, quote: MintQuoteResponse, options: MintProofOptions & {
|
||||
privateKey: string;
|
||||
}): Promise<Array<Proof>>;
|
||||
// (undocumented)
|
||||
mintProofs(amount: number, quote: string, options?: MintProofOptions): Promise<Array<Proof>>;
|
||||
onMeltQuotePaid(quoteId: string, callback: (payload: MeltQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
onMeltQuoteUpdates(quoteIds: Array<string>, callback: (payload: MeltQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
onMintQuotePaid(quoteId: string, callback: (payload: MintQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
// Warning: (ae-forgotten-export) The symbol "SubscriptionCanceller" needs to be exported by the entry point index.d.ts
|
||||
onMintQuoteUpdates(quoteIds: Array<string>, callback: (payload: MintQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
onProofStateUpdates(proofs: Array<Proof>, callback: (payload: ProofState & {
|
||||
proof: Proof;
|
||||
}) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
receive(token: string | Token, options?: ReceiveOptions): Promise<Array<Proof>>;
|
||||
restore(start: number, count: number, options?: RestoreOptions): Promise<{
|
||||
proofs: Array<Proof>;
|
||||
lastCounterWithSignature?: number;
|
||||
}>;
|
||||
// (undocumented)
|
||||
selectProofsToSend(proofs: Array<Proof>, amountToSend: number, includeFees?: boolean): SendResponse;
|
||||
send(amount: number, proofs: Array<Proof>, options?: SendOptions): Promise<SendResponse>;
|
||||
swap(amount: number, proofs: Array<Proof>, options?: SwapOptions): Promise<SendResponse>;
|
||||
// (undocumented)
|
||||
get unit(): string;
|
||||
}
|
||||
|
||||
// @public
|
||||
export const CheckStateEnum: {
|
||||
readonly UNSPENT: "UNSPENT";
|
||||
readonly PENDING: "PENDING";
|
||||
readonly SPENT: "SPENT";
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type CheckStateEnum = (typeof CheckStateEnum)[keyof typeof CheckStateEnum];
|
||||
|
||||
// @public
|
||||
export type CheckStatePayload = {
|
||||
Ys: Array<string>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type CheckStateResponse = {
|
||||
states: Array<ProofState>;
|
||||
} & ApiError;
|
||||
|
||||
// @public (undocumented)
|
||||
export function decodePaymentRequest(paymentRequest: string): PaymentRequest_2;
|
||||
|
||||
// @public
|
||||
export type DeprecatedToken = {
|
||||
token: Array<TokenEntry>;
|
||||
memo?: string;
|
||||
unit?: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export function deriveKeysetId(keys: Keys): string;
|
||||
|
||||
// @public (undocumented)
|
||||
export function getBlindedAuthToken(amount: number, url: string, clearAuthToken: string): Promise<string[]>;
|
||||
|
||||
// @public
|
||||
export function getDecodedToken(token: string): Token;
|
||||
|
||||
// @public (undocumented)
|
||||
export function getDecodedTokenBinary(bytes: Uint8Array): Token;
|
||||
|
||||
// @public
|
||||
export function getEncodedAuthToken(proof: Proof): string;
|
||||
|
||||
// @public
|
||||
export function getEncodedToken(token: Token, opts?: {
|
||||
version: 3 | 4;
|
||||
}): string;
|
||||
|
||||
// @public (undocumented)
|
||||
export function getEncodedTokenBinary(token: Token): Uint8Array;
|
||||
|
||||
// @public (undocumented)
|
||||
export function getEncodedTokenV4(token: Token): string;
|
||||
|
||||
// @public
|
||||
export type GetInfoResponse = {
|
||||
name: string;
|
||||
pubkey: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
description_long?: string;
|
||||
icon_url?: string;
|
||||
contact: Array<MintContactInfo>;
|
||||
nuts: {
|
||||
'4': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'5': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'7'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'8'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'9'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'10'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'11'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'12'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'14'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'15'?: {
|
||||
methods: Array<MPPMethod>;
|
||||
};
|
||||
'17'?: {
|
||||
supported: Array<WebSocketSupport>;
|
||||
};
|
||||
'20'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'22'?: {
|
||||
bat_max_mint: number;
|
||||
protected_endpoints: Array<{
|
||||
method: 'GET' | 'POST';
|
||||
path: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
motd?: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export function hasValidDleq(proof: Proof, keyset: MintKeys): boolean;
|
||||
|
||||
// @public
|
||||
export type HTLCWitness = {
|
||||
preimage: string;
|
||||
signatures?: Array<string>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export class HttpResponseError extends Error {
|
||||
constructor(message: string, status: number);
|
||||
// (undocumented)
|
||||
status: number;
|
||||
}
|
||||
|
||||
// @public (undocumented)
|
||||
export function injectWebSocketImpl(ws: any): void;
|
||||
|
||||
// @public (undocumented)
|
||||
export type InvoiceData = {
|
||||
paymentRequest: string;
|
||||
amountInSats?: number;
|
||||
amountInMSats?: number;
|
||||
timestamp?: number;
|
||||
paymentHash?: string;
|
||||
memo?: string;
|
||||
expiry?: number;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type JsonRpcErrorObject = {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: any;
|
||||
};
|
||||
|
||||
// Warning: (ae-forgotten-export) The symbol "JsonRpcRequest" needs to be exported by the entry point index.d.ts
|
||||
// Warning: (ae-forgotten-export) The symbol "JsonRpcSuccess" needs to be exported by the entry point index.d.ts
|
||||
// Warning: (ae-forgotten-export) The symbol "JsonRpcError" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// @public (undocumented)
|
||||
export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;
|
||||
|
||||
// @public (undocumented)
|
||||
export type JsonRpcNotification = {
|
||||
jsonrpc: '2.0';
|
||||
method: string;
|
||||
params?: JsonRpcParams;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type JsonRpcReqParams = {
|
||||
kind: RpcSubKinds;
|
||||
filters: Array<string>;
|
||||
subId: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type Keys = {
|
||||
[amount: number]: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type LockedMintQuote = {
|
||||
id: string;
|
||||
privkey: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type LockedMintQuoteResponse = MintQuoteResponse & {
|
||||
pubkey: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MeltPayload = {
|
||||
quote: string;
|
||||
inputs: Array<Proof>;
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MeltProofOptions = {
|
||||
keysetId?: string;
|
||||
counter?: number;
|
||||
privkey?: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MeltProofsResponse = {
|
||||
quote: MeltQuoteResponse;
|
||||
change: Array<Proof>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MeltQuoteOptions = {
|
||||
mpp: MPPOption;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MeltQuotePayload = {
|
||||
unit: string;
|
||||
request: string;
|
||||
options?: MeltQuoteOptions;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MeltQuoteResponse = PartialMeltQuoteResponse & {
|
||||
request: string;
|
||||
unit: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export const MeltQuoteState: {
|
||||
readonly UNPAID: "UNPAID";
|
||||
readonly PENDING: "PENDING";
|
||||
readonly PAID: "PAID";
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MeltQuoteState = (typeof MeltQuoteState)[keyof typeof MeltQuoteState];
|
||||
|
||||
// @public
|
||||
export type MintActiveKeys = {
|
||||
keysets: Array<MintKeys>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MintAllKeysets = {
|
||||
keysets: Array<MintKeyset>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MintContactInfo = {
|
||||
method: string;
|
||||
info: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MintKeys = {
|
||||
id: string;
|
||||
unit: string;
|
||||
keys: Keys;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MintKeyset = {
|
||||
id: string;
|
||||
unit: string;
|
||||
active: boolean;
|
||||
input_fee_ppk?: number;
|
||||
};
|
||||
|
||||
// @public
|
||||
export class MintOperationError extends HttpResponseError {
|
||||
constructor(code: number, detail: string);
|
||||
// (undocumented)
|
||||
code: number;
|
||||
}
|
||||
|
||||
// @public
|
||||
export type MintPayload = {
|
||||
quote: string;
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
signature?: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MintProofOptions = {
|
||||
keysetId?: string;
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
outputData?: Array<OutputDataLike> | OutputDataFactory;
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MintQuotePayload = {
|
||||
unit: string;
|
||||
amount: number;
|
||||
description?: string;
|
||||
pubkey?: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MintQuoteResponse = PartialMintQuoteResponse & {
|
||||
amount: number;
|
||||
unit: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export const MintQuoteState: {
|
||||
readonly UNPAID: "UNPAID";
|
||||
readonly PAID: "PAID";
|
||||
readonly ISSUED: "ISSUED";
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type MintQuoteState = (typeof MintQuoteState)[keyof typeof MintQuoteState];
|
||||
|
||||
// @public
|
||||
export type MintResponse = {
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
|
||||
// @public
|
||||
export type MPPMethod = {
|
||||
method: string;
|
||||
unit: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type MPPOption = {
|
||||
amount: number;
|
||||
};
|
||||
|
||||
// @public
|
||||
export class NetworkError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
|
||||
// @public
|
||||
export type NUT10Option = {
|
||||
kind: string;
|
||||
data: string;
|
||||
tags: Array<Array<string>>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type OutputAmounts = {
|
||||
sendAmounts: Array<number>;
|
||||
keepAmounts?: Array<number>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export class OutputData implements OutputDataLike {
|
||||
constructor(blindedMessage: SerializedBlindedMessage, blidingFactor: bigint, secret: Uint8Array);
|
||||
// (undocumented)
|
||||
blindedMessage: SerializedBlindedMessage;
|
||||
// (undocumented)
|
||||
blindingFactor: bigint;
|
||||
// (undocumented)
|
||||
static createDeterministicData(amount: number, seed: Uint8Array, counter: number, keyset: MintKeys, customSplit?: Array<number>): Array<OutputData>;
|
||||
// (undocumented)
|
||||
static createP2PKData(p2pk: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
}, amount: number, keyset: MintKeys, customSplit?: Array<number>): OutputData[];
|
||||
// (undocumented)
|
||||
static createRandomData(amount: number, keyset: MintKeys, customSplit?: Array<number>): OutputData[];
|
||||
// (undocumented)
|
||||
static createSingleDeterministicData(amount: number, seed: Uint8Array, counter: number, keysetId: string): OutputData;
|
||||
// (undocumented)
|
||||
static createSingleP2PKData(p2pk: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
}, amount: number, keysetId: string): OutputData;
|
||||
// (undocumented)
|
||||
static createSingleRandomData(amount: number, keysetId: string): OutputData;
|
||||
// (undocumented)
|
||||
secret: Uint8Array;
|
||||
// (undocumented)
|
||||
toProof(sig: SerializedBlindedSignature, keyset: MintKeys): Proof;
|
||||
}
|
||||
|
||||
// @public
|
||||
export type P2PKWitness = {
|
||||
signatures?: Array<string>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type PartialMeltQuoteResponse = {
|
||||
quote: string;
|
||||
amount: number;
|
||||
fee_reserve: number;
|
||||
state: MeltQuoteState;
|
||||
expiry: number;
|
||||
payment_preimage: string | null;
|
||||
change?: Array<SerializedBlindedSignature>;
|
||||
request?: string;
|
||||
unit?: string;
|
||||
} & ApiError;
|
||||
|
||||
// @public
|
||||
export type PartialMintQuoteResponse = {
|
||||
request: string;
|
||||
quote: string;
|
||||
state: MintQuoteState;
|
||||
expiry: number;
|
||||
pubkey?: string;
|
||||
unit?: string;
|
||||
amount?: number;
|
||||
} & ApiError;
|
||||
|
||||
// @public
|
||||
export type PaymentPayload = {
|
||||
pr: string;
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
class PaymentRequest_2 {
|
||||
constructor(transport?: Array<PaymentRequestTransport> | undefined, id?: string | undefined, amount?: number | undefined, unit?: string | undefined, mints?: Array<string> | undefined, description?: string | undefined, singleUse?: boolean, nut10?: NUT10Option | undefined);
|
||||
// (undocumented)
|
||||
amount?: number | undefined;
|
||||
// (undocumented)
|
||||
description?: string | undefined;
|
||||
// (undocumented)
|
||||
static fromEncodedRequest(encodedRequest: string): PaymentRequest_2;
|
||||
// (undocumented)
|
||||
static fromRawRequest(rawPaymentRequest: RawPaymentRequest): PaymentRequest_2;
|
||||
// (undocumented)
|
||||
getTransport(type: PaymentRequestTransportType): PaymentRequestTransport | undefined;
|
||||
// (undocumented)
|
||||
id?: string | undefined;
|
||||
// (undocumented)
|
||||
mints?: Array<string> | undefined;
|
||||
// (undocumented)
|
||||
nut10?: NUT10Option | undefined;
|
||||
// (undocumented)
|
||||
singleUse: boolean;
|
||||
// (undocumented)
|
||||
toEncodedRequest(): string;
|
||||
// (undocumented)
|
||||
toRawRequest(): RawPaymentRequest;
|
||||
// (undocumented)
|
||||
transport?: Array<PaymentRequestTransport> | undefined;
|
||||
// (undocumented)
|
||||
unit?: string | undefined;
|
||||
}
|
||||
export { PaymentRequest_2 as PaymentRequest }
|
||||
|
||||
// @public (undocumented)
|
||||
export type PaymentRequestPayload = {
|
||||
id?: string;
|
||||
memo?: string;
|
||||
unit: string;
|
||||
mint: string;
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type PaymentRequestTransport = {
|
||||
type: PaymentRequestTransportType;
|
||||
target: string;
|
||||
tags?: Array<Array<string>>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export enum PaymentRequestTransportType {
|
||||
// (undocumented)
|
||||
NOSTR = "nostr",
|
||||
// (undocumented)
|
||||
POST = "post"
|
||||
}
|
||||
|
||||
// @public
|
||||
export type PostRestorePayload = {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type PostRestoreResponse = {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type Proof = {
|
||||
id: string;
|
||||
amount: number;
|
||||
secret: string;
|
||||
C: string;
|
||||
dleq?: SerializedDLEQ;
|
||||
witness?: string | P2PKWitness | HTLCWitness;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type ProofState = {
|
||||
Y: string;
|
||||
state: CheckStateEnum;
|
||||
witness: string | null;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type RawNUT10Option = {
|
||||
k: string;
|
||||
d: string;
|
||||
t: Array<Array<string>>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type RawPaymentRequest = {
|
||||
i?: string;
|
||||
a?: number;
|
||||
u?: string;
|
||||
s?: boolean;
|
||||
m?: Array<string>;
|
||||
d?: string;
|
||||
t?: Array<RawTransport>;
|
||||
nut10?: RawNUT10Option;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type RawTransport = {
|
||||
t: PaymentRequestTransportType;
|
||||
a: string;
|
||||
g?: Array<Array<string>>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type ReceiveOptions = {
|
||||
keysetId?: string;
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
requireDleq?: boolean;
|
||||
outputData?: Array<OutputDataLike> | OutputDataFactory;
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
|
||||
// @public
|
||||
export type ReceiveResponse = {
|
||||
token: Token;
|
||||
tokensWithErrors: Token | undefined;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type ReceiveTokenEntryResponse = {
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type RestoreOptions = {
|
||||
keysetId?: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type RpcSubId = string | number | null;
|
||||
|
||||
// @public (undocumented)
|
||||
export type SendOptions = {
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
keysetId?: string;
|
||||
offline?: boolean;
|
||||
includeFees?: boolean;
|
||||
includeDleq?: boolean;
|
||||
outputData?: {
|
||||
send?: Array<OutputDataLike> | OutputDataFactory;
|
||||
keep?: Array<OutputDataLike> | OutputDataFactory;
|
||||
};
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
|
||||
// @public
|
||||
export type SendResponse = {
|
||||
keep: Array<Proof>;
|
||||
send: Array<Proof>;
|
||||
serialized?: Array<{
|
||||
proof: Proof;
|
||||
keep: boolean;
|
||||
}>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type SerializedBlindedMessage = {
|
||||
amount: number;
|
||||
B_: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type SerializedBlindedSignature = {
|
||||
id: string;
|
||||
amount: number;
|
||||
C_: string;
|
||||
dleq?: SerializedDLEQ;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type SerializedDLEQ = {
|
||||
s: string;
|
||||
e: string;
|
||||
r?: string;
|
||||
};
|
||||
|
||||
// Warning: (ae-forgotten-export) The symbol "RequestOptions" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// @public
|
||||
export function setGlobalRequestOptions(options: Partial<RequestOptions>): void;
|
||||
|
||||
// @public
|
||||
export type SwapMethod = {
|
||||
method: string;
|
||||
unit: string;
|
||||
min_amount: number;
|
||||
max_amount: number;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type SwapOptions = {
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
keysetId?: string;
|
||||
includeFees?: boolean;
|
||||
outputData?: {
|
||||
send?: Array<OutputDataLike> | OutputDataFactory;
|
||||
keep?: Array<OutputDataLike> | OutputDataFactory;
|
||||
};
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
|
||||
// @public
|
||||
export type SwapPayload = {
|
||||
inputs: Array<Proof>;
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type SwapResponse = {
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
|
||||
// @public
|
||||
export type SwapTransaction = {
|
||||
payload: SwapPayload;
|
||||
outputData: Array<OutputData>;
|
||||
keepVector: Array<boolean>;
|
||||
sortedIndices: Array<number>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type Token = {
|
||||
mint: string;
|
||||
proofs: Array<Proof>;
|
||||
memo?: string;
|
||||
unit?: string;
|
||||
};
|
||||
|
||||
// @public @deprecated (undocumented)
|
||||
export type TokenV2 = {
|
||||
proofs: Array<Proof>;
|
||||
mints: Array<{
|
||||
url: string;
|
||||
ids: Array<string>;
|
||||
}>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type TokenV4Template = {
|
||||
t: Array<V4InnerToken>;
|
||||
d: string;
|
||||
m: string;
|
||||
u: string;
|
||||
};
|
||||
|
||||
// @public (undocumented)
|
||||
export type V4DLEQTemplate = {
|
||||
e: Uint8Array;
|
||||
s: Uint8Array;
|
||||
r: Uint8Array;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type V4InnerToken = {
|
||||
i: Uint8Array;
|
||||
p: Array<V4ProofTemplate>;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type V4ProofTemplate = {
|
||||
a: number;
|
||||
s: string;
|
||||
c: Uint8Array;
|
||||
d?: V4DLEQTemplate;
|
||||
w?: string;
|
||||
};
|
||||
|
||||
// @public
|
||||
export type WebSocketSupport = {
|
||||
method: string;
|
||||
unit: string;
|
||||
commands: Array<string>;
|
||||
};
|
||||
|
||||
// Warnings were encountered during analysis:
|
||||
//
|
||||
// lib/types/CashuWallet.d.ts:38:9 - (ae-forgotten-export) The symbol "OutputDataFactory" needs to be exported by the entry point index.d.ts
|
||||
// lib/types/model/types/index.d.ts:117:5 - (ae-forgotten-export) The symbol "OutputDataLike" needs to be exported by the entry point index.d.ts
|
||||
// lib/types/model/types/index.d.ts:148:5 - (ae-forgotten-export) The symbol "RpcSubKinds" needs to be exported by the entry point index.d.ts
|
||||
// lib/types/model/types/index.d.ts:176:5 - (ae-forgotten-export) The symbol "JsonRpcParams" needs to be exported by the entry point index.d.ts
|
||||
// lib/types/model/types/wallet/tokens.d.ts:103:5 - (ae-forgotten-export) The symbol "TokenEntry" needs to be exported by the entry point index.d.ts
|
||||
|
||||
// (No @packageDocumentation comment for this package)
|
||||
|
||||
```
|
||||
+2
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+2430
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+184
@@ -0,0 +1,184 @@
|
||||
import { WSConnection } from './WSConnection.js';
|
||||
import { CheckStatePayload, CheckStateResponse, GetInfoResponse, MeltPayload, MintActiveKeys, MintAllKeysets, PostRestoreResponse, SerializedBlindedMessage, SwapPayload, SwapResponse, MintQuotePayload, MintPayload, MintResponse, PostRestorePayload, MeltQuotePayload, PartialMintQuoteResponse, PartialMeltQuoteResponse } from './model/types/index.js';
|
||||
import { default as request } from './request.js';
|
||||
import { MintInfo } from './model/MintInfo.js';
|
||||
/**
|
||||
* Class represents Cashu Mint API. This class contains Lower level functions that are implemented by CashuWallet.
|
||||
*/
|
||||
declare class CashuMint {
|
||||
private _mintUrl;
|
||||
private _customRequest?;
|
||||
private ws?;
|
||||
private _mintInfo?;
|
||||
private _authTokenGetter?;
|
||||
private _checkNut22;
|
||||
/**
|
||||
* @param _mintUrl requires mint URL to create this object
|
||||
* @param _customRequest if passed, use custom request implementation for network communication with the mint
|
||||
* @param [authTokenGetter] a function that is called by the CashuMint instance to obtain a NUT-22 BlindedAuthToken (e.g. from a database or localstorage)
|
||||
*/
|
||||
constructor(_mintUrl: string, _customRequest?: typeof request | undefined, authTokenGetter?: () => Promise<string>);
|
||||
get mintUrl(): string;
|
||||
/**
|
||||
* fetches mints info at the /info endpoint
|
||||
* @param mintUrl
|
||||
* @param customRequest
|
||||
*/
|
||||
static getInfo(mintUrl: string, customRequest?: typeof request): Promise<GetInfoResponse>;
|
||||
/**
|
||||
* fetches mints info at the /info endpoint
|
||||
*/
|
||||
getInfo(): Promise<GetInfoResponse>;
|
||||
getLazyMintInfo(): Promise<MintInfo>;
|
||||
/**
|
||||
* Performs a swap operation with ecash inputs and outputs.
|
||||
* @param mintUrl
|
||||
* @param swapPayload payload containing inputs and outputs
|
||||
* @param customRequest
|
||||
* @returns signed outputs
|
||||
*/
|
||||
static swap(mintUrl: string, swapPayload: SwapPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<SwapResponse>;
|
||||
/**
|
||||
* Performs a swap operation with ecash inputs and outputs.
|
||||
* @param swapPayload payload containing inputs and outputs
|
||||
* @returns signed outputs
|
||||
*/
|
||||
swap(swapPayload: SwapPayload): Promise<SwapResponse>;
|
||||
/**
|
||||
* Requests a new mint quote from the mint.
|
||||
* @param mintUrl
|
||||
* @param mintQuotePayload Payload for creating a new mint quote
|
||||
* @param customRequest
|
||||
* @returns the mint will create and return a new mint quote containing a payment request for the specified amount and unit
|
||||
*/
|
||||
static createMintQuote(mintUrl: string, mintQuotePayload: MintQuotePayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMintQuoteResponse>;
|
||||
/**
|
||||
* Requests a new mint quote from the mint.
|
||||
* @param mintQuotePayload Payload for creating a new mint quote
|
||||
* @returns the mint will create and return a new mint quote containing a payment request for the specified amount and unit
|
||||
*/
|
||||
createMintQuote(mintQuotePayload: MintQuotePayload): Promise<PartialMintQuoteResponse>;
|
||||
/**
|
||||
* Gets an existing mint quote from the mint.
|
||||
* @param mintUrl
|
||||
* @param quote Quote ID
|
||||
* @param customRequest
|
||||
* @returns the mint will create and return a Lightning invoice for the specified amount
|
||||
*/
|
||||
static checkMintQuote(mintUrl: string, quote: string, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMintQuoteResponse>;
|
||||
/**
|
||||
* Gets an existing mint quote from the mint.
|
||||
* @param quote Quote ID
|
||||
* @returns the mint will create and return a Lightning invoice for the specified amount
|
||||
*/
|
||||
checkMintQuote(quote: string): Promise<PartialMintQuoteResponse>;
|
||||
/**
|
||||
* Mints new tokens by requesting blind signatures on the provided outputs.
|
||||
* @param mintUrl
|
||||
* @param mintPayload Payload containing the outputs to get blind signatures on
|
||||
* @param customRequest
|
||||
* @returns serialized blinded signatures
|
||||
*/
|
||||
static mint(mintUrl: string, mintPayload: MintPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<MintResponse>;
|
||||
/**
|
||||
* Mints new tokens by requesting blind signatures on the provided outputs.
|
||||
* @param mintPayload Payload containing the outputs to get blind signatures on
|
||||
* @returns serialized blinded signatures
|
||||
*/
|
||||
mint(mintPayload: MintPayload): Promise<MintResponse>;
|
||||
/**
|
||||
* Requests a new melt quote from the mint.
|
||||
* @param mintUrl
|
||||
* @param MeltQuotePayload
|
||||
* @returns
|
||||
*/
|
||||
static createMeltQuote(mintUrl: string, meltQuotePayload: MeltQuotePayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Requests a new melt quote from the mint.
|
||||
* @param MeltQuotePayload
|
||||
* @returns
|
||||
*/
|
||||
createMeltQuote(meltQuotePayload: MeltQuotePayload): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Gets an existing melt quote.
|
||||
* @param mintUrl
|
||||
* @param quote Quote ID
|
||||
* @returns
|
||||
*/
|
||||
static checkMeltQuote(mintUrl: string, quote: string, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Gets an existing melt quote.
|
||||
* @param quote Quote ID
|
||||
* @returns
|
||||
*/
|
||||
checkMeltQuote(quote: string): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Requests the mint to pay for a Bolt11 payment request by providing ecash as inputs to be spent. The inputs contain the amount and the fee_reserves for a Lightning payment. The payload can also contain blank outputs in order to receive back overpaid Lightning fees.
|
||||
* @param mintUrl
|
||||
* @param meltPayload
|
||||
* @param customRequest
|
||||
* @returns
|
||||
*/
|
||||
static melt(mintUrl: string, meltPayload: MeltPayload, customRequest?: typeof request, blindAuthToken?: string): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Ask mint to perform a melt operation. This pays a lightning invoice and destroys tokens matching its amount + fees
|
||||
* @param meltPayload
|
||||
* @returns
|
||||
*/
|
||||
melt(meltPayload: MeltPayload): Promise<PartialMeltQuoteResponse>;
|
||||
/**
|
||||
* Checks if specific proofs have already been redeemed
|
||||
* @param mintUrl
|
||||
* @param checkPayload
|
||||
* @param customRequest
|
||||
* @returns redeemed and unredeemed ordered list of booleans
|
||||
*/
|
||||
static check(mintUrl: string, checkPayload: CheckStatePayload, customRequest?: typeof request): Promise<CheckStateResponse>;
|
||||
/**
|
||||
* Get the mints public keys
|
||||
* @param mintUrl
|
||||
* @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched
|
||||
* @param customRequest
|
||||
* @returns
|
||||
*/
|
||||
static getKeys(mintUrl: string, keysetId?: string, customRequest?: typeof request): Promise<MintActiveKeys>;
|
||||
/**
|
||||
* Get the mints public keys
|
||||
* @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched
|
||||
* @returns the mints public keys
|
||||
*/
|
||||
getKeys(keysetId?: string, mintUrl?: string): Promise<MintActiveKeys>;
|
||||
/**
|
||||
* Get the mints keysets in no specific order
|
||||
* @param mintUrl
|
||||
* @param customRequest
|
||||
* @returns all the mints past and current keysets.
|
||||
*/
|
||||
static getKeySets(mintUrl: string, customRequest?: typeof request): Promise<MintAllKeysets>;
|
||||
/**
|
||||
* Get the mints keysets in no specific order
|
||||
* @returns all the mints past and current keysets.
|
||||
*/
|
||||
getKeySets(): Promise<MintAllKeysets>;
|
||||
/**
|
||||
* Checks if specific proofs have already been redeemed
|
||||
* @param checkPayload
|
||||
* @returns redeemed and unredeemed ordered list of booleans
|
||||
*/
|
||||
check(checkPayload: CheckStatePayload): Promise<CheckStateResponse>;
|
||||
static restore(mintUrl: string, restorePayload: PostRestorePayload, customRequest?: typeof request): Promise<PostRestoreResponse>;
|
||||
restore(restorePayload: {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
}): Promise<PostRestoreResponse>;
|
||||
/**
|
||||
* Tries to establish a websocket connection with the websocket mint url according to NUT-17
|
||||
*/
|
||||
connectWebSocket(): Promise<void>;
|
||||
/**
|
||||
* Closes a websocket connection
|
||||
*/
|
||||
disconnectWebSocket(): void;
|
||||
get webSocketConnection(): WSConnection | undefined;
|
||||
handleBlindAuth(path: string): Promise<string | undefined>;
|
||||
}
|
||||
export { CashuMint };
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
import { CashuMint } from './CashuMint.js';
|
||||
import { MintInfo } from './model/MintInfo.js';
|
||||
import { GetInfoResponse, MeltProofOptions, MintProofOptions, MintQuoteResponse, ProofState, ReceiveOptions, RestoreOptions, SendOptions, SwapOptions, MeltProofsResponse, MeltQuoteResponse, MintKeys, MintKeyset, Proof, SendResponse, Token, LockedMintQuoteResponse, PartialMintQuoteResponse, PartialMeltQuoteResponse } from './model/types/index.js';
|
||||
import { SubscriptionCanceller } from './model/types/wallet/websocket.js';
|
||||
import { OutputDataFactory } from './model/OutputData.js';
|
||||
/**
|
||||
* Class that represents a Cashu wallet.
|
||||
* This class should act as the entry point for this library
|
||||
*/
|
||||
declare class CashuWallet {
|
||||
private _keys;
|
||||
private _keysetId;
|
||||
private _keysets;
|
||||
private _seed;
|
||||
private _unit;
|
||||
private _mintInfo;
|
||||
private _denominationTarget;
|
||||
private _keepFactory;
|
||||
mint: CashuMint;
|
||||
/**
|
||||
* @param mint Cashu mint instance is used to make api calls
|
||||
* @param options.unit optionally set unit (default is 'sat')
|
||||
* @param options.keys public keys from the mint (will be fetched from mint if not provided)
|
||||
* @param options.keysets keysets from the mint (will be fetched from mint if not provided)
|
||||
* @param options.mintInfo mint info from the mint (will be fetched from mint if not provided)
|
||||
* @param options.denominationTarget target number proofs per denomination (default: see @constant DEFAULT_DENOMINATION_TARGET)
|
||||
* @param options.bip39seed BIP39 seed for deterministic secrets.
|
||||
* @param options.keepFactory A function that will be used by all parts of the library that produce proofs to be kept (change, etc.).
|
||||
* This can lead to poor performance, in which case the seed should be directly provided
|
||||
*/
|
||||
constructor(mint: CashuMint, options?: {
|
||||
unit?: string;
|
||||
keys?: Array<MintKeys> | MintKeys;
|
||||
keysets?: Array<MintKeyset>;
|
||||
mintInfo?: GetInfoResponse;
|
||||
bip39seed?: Uint8Array;
|
||||
denominationTarget?: number;
|
||||
keepFactory?: OutputDataFactory;
|
||||
});
|
||||
get unit(): string;
|
||||
get keys(): Map<string, MintKeys>;
|
||||
get keysetId(): string;
|
||||
set keysetId(keysetId: string);
|
||||
get keysets(): Array<MintKeyset>;
|
||||
get mintInfo(): MintInfo;
|
||||
/**
|
||||
* Get information about the mint
|
||||
* @returns mint info
|
||||
*/
|
||||
getMintInfo(): Promise<MintInfo>;
|
||||
/**
|
||||
* Get stored information about the mint or request it if not loaded.
|
||||
* @returns mint info
|
||||
*/
|
||||
lazyGetMintInfo(): Promise<MintInfo>;
|
||||
/**
|
||||
* Load mint information, keysets and keys. This function can be called if no keysets are passed in the constructor
|
||||
*/
|
||||
loadMint(): Promise<void>;
|
||||
/**
|
||||
* Choose a keyset to activate based on the lowest input fee
|
||||
*
|
||||
* Note: this function will filter out deprecated base64 keysets
|
||||
*
|
||||
* @param keysets keysets to choose from
|
||||
* @returns active keyset
|
||||
*/
|
||||
getActiveKeyset(keysets: Array<MintKeyset>): MintKeyset;
|
||||
/**
|
||||
* Get keysets from the mint with the unit of the wallet
|
||||
* @returns keysets with wallet's unit
|
||||
*/
|
||||
getKeySets(): Promise<Array<MintKeyset>>;
|
||||
/**
|
||||
* Get all active keys from the mint and set the keyset with the lowest fees as the active wallet keyset.
|
||||
* @returns keyset
|
||||
*/
|
||||
getAllKeys(): Promise<Array<MintKeys>>;
|
||||
/**
|
||||
* Get public keys from the mint. If keys were already fetched, it will return those.
|
||||
*
|
||||
* If `keysetId` is set, it will fetch and return that specific keyset.
|
||||
* Otherwise, we select an active keyset with the unit of the wallet.
|
||||
*
|
||||
* @param keysetId optional keysetId to get keys for
|
||||
* @param forceRefresh? if set to true, it will force refresh the keyset from the mint
|
||||
* @returns keyset
|
||||
*/
|
||||
getKeys(keysetId?: string, forceRefresh?: boolean): Promise<MintKeys>;
|
||||
/**
|
||||
* Receive an encoded or raw Cashu token (only supports single tokens. It will only process the first token in the token array)
|
||||
* @param {(string|Token)} token - Cashu token, either as string or decoded
|
||||
* @param {ReceiveOptions} [options] - Optional configuration for token processing
|
||||
* @returns New token with newly created proofs, token entries that had errors
|
||||
*/
|
||||
receive(token: string | Token, options?: ReceiveOptions): Promise<Array<Proof>>;
|
||||
/**
|
||||
* Send proofs of a given amount, by providing at least the required amount of proofs
|
||||
* @param amount amount to send
|
||||
* @param proofs array of proofs (accumulated amount of proofs must be >= than amount)
|
||||
* @param {SendOptions} [options] - Optional parameters for configuring the send operation
|
||||
* @returns {SendResponse}
|
||||
*/
|
||||
send(amount: number, proofs: Array<Proof>, options?: SendOptions): Promise<SendResponse>;
|
||||
selectProofsToSend(proofs: Array<Proof>, amountToSend: number, includeFees?: boolean): SendResponse;
|
||||
/**
|
||||
* calculates the fees based on inputs (proofs)
|
||||
* @param proofs input proofs to calculate fees for
|
||||
* @returns fee amount
|
||||
*/
|
||||
getFeesForProofs(proofs: Array<Proof>): number;
|
||||
/**
|
||||
* calculates the fees based on inputs for a given keyset
|
||||
* @param nInputs number of inputs
|
||||
* @param keysetId keysetId used to lookup `input_fee_ppk`
|
||||
* @returns fee amount
|
||||
*/
|
||||
getFeesForKeyset(nInputs: number, keysetId: string): number;
|
||||
/**
|
||||
* Splits and creates sendable tokens
|
||||
* if no amount is specified, the amount is implied by the cumulative amount of all proofs
|
||||
* if both amount and preference are set, but the preference cannot fulfill the amount, then we use the default split
|
||||
* @param {SwapOptions} [options] - Optional parameters for configuring the swap operation
|
||||
* @returns promise of the change- and send-proofs
|
||||
*/
|
||||
swap(amount: number, proofs: Array<Proof>, options?: SwapOptions): Promise<SendResponse>;
|
||||
/**
|
||||
* Restores batches of deterministic proofs until no more signatures are returned from the mint
|
||||
* @param [gapLimit=300] the amount of empty counters that should be returned before restoring ends (defaults to 300)
|
||||
* @param [batchSize=100] the amount of proofs that should be restored at a time (defaults to 100)
|
||||
* @param [counter=0] the counter that should be used as a starting point (defaults to 0)
|
||||
* @param [keysetId] which keysetId to use for the restoration. If none is passed the instance's default one will be used
|
||||
*/
|
||||
batchRestore(gapLimit?: number, batchSize?: number, counter?: number, keysetId?: string): Promise<{
|
||||
proofs: Array<Proof>;
|
||||
lastCounterWithSignature?: number;
|
||||
}>;
|
||||
/**
|
||||
* Regenerates
|
||||
* @param start set starting point for count (first cycle for each keyset should usually be 0)
|
||||
* @param count set number of blinded messages that should be generated
|
||||
* @param options.keysetId set a custom keysetId to restore from. keysetIds can be loaded with `CashuMint.getKeySets()`
|
||||
*/
|
||||
restore(start: number, count: number, options?: RestoreOptions): Promise<{
|
||||
proofs: Array<Proof>;
|
||||
lastCounterWithSignature?: number;
|
||||
}>;
|
||||
/**
|
||||
* Requests a mint quote form the mint. Response returns a Lightning payment request for the requested given amount and unit.
|
||||
* @param amount Amount requesting for mint.
|
||||
* @param description optional description for the mint quote
|
||||
* @param pubkey optional public key to lock the quote to
|
||||
* @returns the mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit
|
||||
*/
|
||||
createMintQuote(amount: number, description?: string): Promise<MintQuoteResponse>;
|
||||
/**
|
||||
* Requests a mint quote from the mint that is locked to a public key.
|
||||
* @param amount Amount requesting for mint.
|
||||
* @param pubkey public key to lock the quote to
|
||||
* @param description optional description for the mint quote
|
||||
* @returns the mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit.
|
||||
* The quote will be locked to the specified `pubkey`.
|
||||
*/
|
||||
createLockedMintQuote(amount: number, pubkey: string, description?: string): Promise<LockedMintQuoteResponse>;
|
||||
/**
|
||||
* Gets an existing mint quote from the mint.
|
||||
* @param quote Quote ID
|
||||
* @returns the mint will create and return a Lightning invoice for the specified amount
|
||||
*/
|
||||
checkMintQuote(quote: MintQuoteResponse): Promise<MintQuoteResponse>;
|
||||
checkMintQuote(quote: string): Promise<PartialMintQuoteResponse>;
|
||||
/**
|
||||
* Mint proofs for a given mint quote
|
||||
* @param amount amount to request
|
||||
* @param {string} quote - ID of mint quote (when quote is a string)
|
||||
* @param {LockedMintQuote} quote - containing the quote ID and unlocking private key (when quote is a LockedMintQuote)
|
||||
* @param {MintProofOptions} [options] - Optional parameters for configuring the Mint Proof operation
|
||||
* @returns proofs
|
||||
*/
|
||||
mintProofs(amount: number, quote: MintQuoteResponse, options: MintProofOptions & {
|
||||
privateKey: string;
|
||||
}): Promise<Array<Proof>>;
|
||||
mintProofs(amount: number, quote: string, options?: MintProofOptions): Promise<Array<Proof>>;
|
||||
/**
|
||||
* Requests a melt quote from the mint. Response returns amount and fees for a given unit in order to pay a Lightning invoice.
|
||||
* @param invoice LN invoice that needs to get a fee estimate
|
||||
* @returns the mint will create and return a melt quote for the invoice with an amount and fee reserve
|
||||
*/
|
||||
createMeltQuote(invoice: string): Promise<MeltQuoteResponse>;
|
||||
/**
|
||||
* Requests a multi path melt quote from the mint.
|
||||
* @param invoice LN invoice that needs to get a fee estimate
|
||||
* @param partialAmount the partial amount of the invoice's total to be paid by this instance
|
||||
* @returns the mint will create and return a melt quote for the invoice with an amount and fee reserve
|
||||
*/
|
||||
createMultiPathMeltQuote(invoice: string, millisatPartialAmount: number): Promise<MeltQuoteResponse>;
|
||||
/**
|
||||
* Return an existing melt quote from the mint.
|
||||
* @param quote ID of the melt quote
|
||||
* @returns the mint will return an existing melt quote
|
||||
*/
|
||||
checkMeltQuote(quote: string): Promise<PartialMeltQuoteResponse>;
|
||||
checkMeltQuote(quote: MeltQuoteResponse): Promise<MeltQuoteResponse>;
|
||||
/**
|
||||
* Melt proofs for a melt quote. proofsToSend must be at least amount+fee_reserve form the melt quote. This function does not perform coin selection!.
|
||||
* Returns melt quote and change proofs
|
||||
* @param meltQuote ID of the melt quote
|
||||
* @param proofsToSend proofs to melt
|
||||
* @param {MeltProofOptions} [options] - Optional parameters for configuring the Melting Proof operation
|
||||
* @returns
|
||||
*/
|
||||
meltProofs(meltQuote: MeltQuoteResponse, proofsToSend: Array<Proof>, options?: MeltProofOptions): Promise<MeltProofsResponse>;
|
||||
/**
|
||||
* Creates a split payload
|
||||
* @param amount amount to send
|
||||
* @param proofsToSend proofs to split*
|
||||
* @param outputAmounts? optionally specify the output's amounts to keep and to send.
|
||||
* @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!
|
||||
* @param privkey? will create a signature on the @param proofsToSend secrets if set
|
||||
* @returns
|
||||
*/
|
||||
private createSwapPayload;
|
||||
/**
|
||||
* Get an array of the states of proofs from the mint (as an array of CheckStateEnum's)
|
||||
* @param proofs (only the `secret` field is required)
|
||||
* @returns
|
||||
*/
|
||||
checkProofsStates(proofs: Array<Proof>): Promise<Array<ProofState>>;
|
||||
/**
|
||||
* Register a callback to be called whenever a mint quote's state changes
|
||||
* @param quoteIds List of mint quote IDs that should be subscribed to
|
||||
* @param callback Callback function that will be called whenever a mint quote state changes
|
||||
* @param errorCallback
|
||||
* @returns
|
||||
*/
|
||||
onMintQuoteUpdates(quoteIds: Array<string>, callback: (payload: MintQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
/**
|
||||
* Register a callback to be called whenever a melt quote's state changes
|
||||
* @param quoteIds List of melt quote IDs that should be subscribed to
|
||||
* @param callback Callback function that will be called whenever a melt quote state changes
|
||||
* @param errorCallback
|
||||
* @returns
|
||||
*/
|
||||
onMeltQuotePaid(quoteId: string, callback: (payload: MeltQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
/**
|
||||
* Register a callback to be called when a single mint quote gets paid
|
||||
* @param quoteId Mint quote id that should be subscribed to
|
||||
* @param callback Callback function that will be called when this mint quote gets paid
|
||||
* @param errorCallback
|
||||
* @returns
|
||||
*/
|
||||
onMintQuotePaid(quoteId: string, callback: (payload: MintQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
/**
|
||||
* Register a callback to be called when a single melt quote gets paid
|
||||
* @param quoteId Melt quote id that should be subscribed to
|
||||
* @param callback Callback function that will be called when this melt quote gets paid
|
||||
* @param errorCallback
|
||||
* @returns
|
||||
*/
|
||||
onMeltQuoteUpdates(quoteIds: Array<string>, callback: (payload: MeltQuoteResponse) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
/**
|
||||
* Register a callback to be called whenever a subscribed proof state changes
|
||||
* @param proofs List of proofs that should be subscribed to
|
||||
* @param callback Callback function that will be called whenever a proof's state changes
|
||||
* @param errorCallback
|
||||
* @returns
|
||||
*/
|
||||
onProofStateUpdates(proofs: Array<Proof>, callback: (payload: ProofState & {
|
||||
proof: Proof;
|
||||
}) => void, errorCallback: (e: Error) => void): Promise<SubscriptionCanceller>;
|
||||
/**
|
||||
* Creates blinded messages for a according to @param amounts
|
||||
* @param amount array of amounts to create blinded messages for
|
||||
* @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* @param keyksetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint
|
||||
* @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!
|
||||
* @returns blinded messages, secrets, rs, and amounts
|
||||
*/
|
||||
private createOutputData;
|
||||
/**
|
||||
* Creates NUT-08 blank outputs (fee returns) for a given fee reserve
|
||||
* See: https://github.com/cashubtc/nuts/blob/main/08.md
|
||||
* @param amount amount to cover with blank outputs
|
||||
* @param keysetId mint keysetId
|
||||
* @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* @returns blinded messages, secrets, and rs
|
||||
*/
|
||||
private createBlankOutputs;
|
||||
}
|
||||
export { CashuWallet };
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { JsonRpcReqParams } from './model/types';
|
||||
export declare class ConnectionManager {
|
||||
static instace: ConnectionManager;
|
||||
private connectionMap;
|
||||
static getInstance(): ConnectionManager;
|
||||
getConnection(url: string): WSConnection;
|
||||
}
|
||||
export declare class WSConnection {
|
||||
readonly url: URL;
|
||||
private readonly _WS;
|
||||
private ws;
|
||||
private connectionPromise;
|
||||
private subListeners;
|
||||
private rpcListeners;
|
||||
private messageQueue;
|
||||
private handlingInterval?;
|
||||
private rpcId;
|
||||
constructor(url: string);
|
||||
connect(): Promise<void>;
|
||||
sendRequest(method: 'subscribe', params: JsonRpcReqParams): void;
|
||||
sendRequest(method: 'unsubscribe', params: {
|
||||
subId: string;
|
||||
}): void;
|
||||
closeSubscription(subId: string): void;
|
||||
addSubListener(subId: string, callback: (payload: any) => any): void;
|
||||
private addRpcListener;
|
||||
private removeRpcListener;
|
||||
private removeListener;
|
||||
ensureConnection(): Promise<void>;
|
||||
private handleNextMesage;
|
||||
createSubscription(params: Omit<JsonRpcReqParams, 'subId'>, callback: (payload: any) => any, errorCallback: (e: Error) => any): any;
|
||||
cancelSubscription(subId: string, callback: (payload: any) => any): void;
|
||||
get activeSubscriptions(): string[];
|
||||
close(): void;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { BlindAuthMintPayload, BlindAuthMintResponse, MintActiveKeys, MintAllKeysets } from '../model/types';
|
||||
import { default as request } from '../request';
|
||||
/**
|
||||
* Class represents Cashu Auth Mint API. This class contains Lower level functions that are implemented by CashuAuthWallet.
|
||||
*/
|
||||
declare class CashuAuthMint {
|
||||
private _mintUrl;
|
||||
private _customRequest?;
|
||||
/**
|
||||
* @param _mintUrl requires mint URL to create this object
|
||||
* @param _customRequest if passed, use custom request implementation for network communication with the mint
|
||||
*/
|
||||
constructor(_mintUrl: string, _customRequest?: typeof request | undefined);
|
||||
get mintUrl(): string;
|
||||
/**
|
||||
* Mints new Blinded Authentication tokens by requesting blind signatures on the provided outputs.
|
||||
* @param mintUrl
|
||||
* @param mintPayload Payload containing the outputs to get blind signatures on
|
||||
* @param clearAuthToken A NUT-21 clear auth token
|
||||
* @param customRequest
|
||||
* @returns serialized blinded signatures
|
||||
*/
|
||||
static mint(mintUrl: string, mintPayload: BlindAuthMintPayload, clearAuthToken: string, customRequest?: typeof request): Promise<BlindAuthMintResponse>;
|
||||
/**
|
||||
* Mints new Blinded Authentication tokens by requesting blind signatures on the provided outputs.
|
||||
* @param mintPayload Payload containing the outputs to get blind signatures on
|
||||
* @param clearAuthToken A NUT-21 clear auth token
|
||||
* @returns serialized blinded signatures
|
||||
*/
|
||||
mint(mintPayload: BlindAuthMintPayload, clearAuthToken: string): Promise<BlindAuthMintResponse>;
|
||||
/**
|
||||
* Get the mints public NUT-22 keys
|
||||
* @param mintUrl
|
||||
* @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched
|
||||
* @param customRequest
|
||||
* @returns
|
||||
*/
|
||||
static getKeys(mintUrl: string, keysetId?: string, customRequest?: typeof request): Promise<MintActiveKeys>;
|
||||
/**
|
||||
* Get the mints public NUT-22 keys
|
||||
* @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched
|
||||
* @returns the mints public keys
|
||||
*/
|
||||
getKeys(keysetId?: string, mintUrl?: string): Promise<MintActiveKeys>;
|
||||
/**
|
||||
* Get the mints NUT-22 keysets in no specific order
|
||||
* @param mintUrl
|
||||
* @param customRequest
|
||||
* @returns all the mints past and current keysets.
|
||||
*/
|
||||
static getKeySets(mintUrl: string, customRequest?: typeof request): Promise<MintAllKeysets>;
|
||||
/**
|
||||
* Get the mints NUT-22 keysets in no specific order
|
||||
* @returns all the mints past and current keysets.
|
||||
*/
|
||||
getKeySets(): Promise<MintAllKeysets>;
|
||||
}
|
||||
export { CashuAuthMint };
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { MintKeys, MintKeyset, Proof } from '../model/types';
|
||||
import { CashuAuthMint } from './CashuAuthMint';
|
||||
/**
|
||||
* Class that represents a Cashu NUT-22 wallet.
|
||||
*/
|
||||
declare class CashuAuthWallet {
|
||||
private _keys;
|
||||
private _keysetId;
|
||||
private _keysets;
|
||||
private _unit;
|
||||
mint: CashuAuthMint;
|
||||
/**
|
||||
* @param mint NUT-22 auth mint instance
|
||||
* @param options.keys public keys from the mint (will be fetched from mint if not provided)
|
||||
* @param options.keysets keysets from the mint (will be fetched from mint if not provided)
|
||||
*/
|
||||
constructor(mint: CashuAuthMint, options?: {
|
||||
keys?: Array<MintKeys> | MintKeys;
|
||||
keysets?: Array<MintKeyset>;
|
||||
});
|
||||
get keys(): Map<string, MintKeys>;
|
||||
get keysetId(): string;
|
||||
set keysetId(keysetId: string);
|
||||
get keysets(): Array<MintKeyset>;
|
||||
/**
|
||||
* Load mint information, keysets and keys. This function can be called if no keysets are passed in the constructor
|
||||
*/
|
||||
loadMint(): Promise<void>;
|
||||
/**
|
||||
* Choose a keyset to activate based on the lowest input fee
|
||||
*
|
||||
* Note: this function will filter out deprecated base64 keysets
|
||||
*
|
||||
* @param keysets keysets to choose from
|
||||
* @returns active keyset
|
||||
*/
|
||||
getActiveKeyset(keysets: Array<MintKeyset>): MintKeyset;
|
||||
/**
|
||||
* Get keysets from the mint with the unit of the wallet
|
||||
* @returns keysets with wallet's unit
|
||||
*/
|
||||
getKeySets(): Promise<Array<MintKeyset>>;
|
||||
/**
|
||||
* Get all active keys from the mint and set the keyset with the lowest fees as the active wallet keyset.
|
||||
* @returns keyset
|
||||
*/
|
||||
getAllKeys(): Promise<Array<MintKeys>>;
|
||||
/**
|
||||
* Get public keys from the mint. If keys were already fetched, it will return those.
|
||||
*
|
||||
* If `keysetId` is set, it will fetch and return that specific keyset.
|
||||
* Otherwise, we select an active keyset with the unit of the wallet.
|
||||
*
|
||||
* @param keysetId optional keysetId to get keys for
|
||||
* @param forceRefresh? if set to true, it will force refresh the keyset from the mint
|
||||
* @returns keyset
|
||||
*/
|
||||
getKeys(keysetId?: string, forceRefresh?: boolean): Promise<MintKeys>;
|
||||
/**
|
||||
* Mint proofs for a given mint quote
|
||||
* @param amount amount to request
|
||||
* @param clearAuthToken clearAuthToken to mint
|
||||
* @param options.keysetId? optionally set keysetId for blank outputs for returned change.
|
||||
* @returns proofs
|
||||
*/
|
||||
mintProofs(amount: number, clearAuthToken: string, options?: {
|
||||
keysetId?: string;
|
||||
}): Promise<Array<Proof>>;
|
||||
}
|
||||
export { CashuAuthWallet };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { CashuAuthMint } from './CashuAuthMint';
|
||||
import { CashuAuthWallet } from './CashuAuthWallet';
|
||||
import { Proof } from '../model/types';
|
||||
/**
|
||||
* Helper function to encode a cashu auth token authA
|
||||
* @param proof
|
||||
*/
|
||||
export declare function getEncodedAuthToken(proof: Proof): string;
|
||||
export declare function getBlindedAuthToken(amount: number, url: string, clearAuthToken: string): Promise<string[]>;
|
||||
export { CashuAuthMint, CashuAuthWallet };
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
declare function encodeUint8toBase64(uint8array: Uint8Array): string;
|
||||
declare function encodeUint8toBase64Url(bytes: Uint8Array): string;
|
||||
declare function encodeBase64toUint8(base64String: string): Uint8Array;
|
||||
declare function encodeJsonToBase64(jsonObj: unknown): string;
|
||||
declare function encodeBase64ToJson<T extends object>(base64String: string): T;
|
||||
export { encodeUint8toBase64, encodeUint8toBase64Url, encodeBase64toUint8, encodeJsonToBase64, encodeBase64ToJson };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
type SimpleValue = boolean | null | undefined;
|
||||
export type ResultObject = {
|
||||
[key: string]: ResultValue;
|
||||
};
|
||||
export type ResultValue = SimpleValue | number | string | Uint8Array | Array<ResultValue> | ResultObject;
|
||||
export type ValidDecodedType = Extract<ResultValue, ResultObject>;
|
||||
export declare function encodeCBOR(value: any): Uint8Array<ArrayBuffer>;
|
||||
export declare function decodeCBOR(data: Uint8Array): ResultValue;
|
||||
export {};
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const deriveSecret: (seed: Uint8Array, keysetId: string, counter: number) => Uint8Array;
|
||||
export declare const deriveBlindingFactor: (seed: Uint8Array, keysetId: string, counter: number) => Uint8Array;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { PrivKey } from '@noble/curves/abstract/utils';
|
||||
import { Proof } from '../common/index.js';
|
||||
import { BlindedMessage } from './index.js';
|
||||
export declare const createP2PKsecret: (pubkey: string) => Uint8Array;
|
||||
export declare const signP2PKsecret: (secret: Uint8Array, privateKey: PrivKey) => Uint8Array<ArrayBufferLike>;
|
||||
export declare const signBlindedMessage: (B_: string, privateKey: PrivKey) => Uint8Array;
|
||||
export declare const getSignedProofs: (proofs: Array<Proof>, privateKey: string | string[]) => Array<Proof>;
|
||||
export declare const getSignedOutput: (output: BlindedMessage, privateKey: PrivKey) => BlindedMessage;
|
||||
export declare const getSignedOutputs: (outputs: Array<BlindedMessage>, privateKey: string) => Array<BlindedMessage>;
|
||||
export declare const getSignedProof: (proof: Proof, privateKey: PrivKey) => Proof;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { DLEQ } from '../common/index.js';
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
export declare const verifyDLEQProof: (dleq: DLEQ, B_: ProjPointType<bigint>, C_: ProjPointType<bigint>, A: ProjPointType<bigint>) => boolean;
|
||||
export declare const verifyDLEQProof_reblind: (secret: Uint8Array, dleq: DLEQ, C: ProjPointType<bigint>, A: ProjPointType<bigint>) => boolean;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { SerializedBlindedMessage } from '../../model/types';
|
||||
export declare function signMintQuote(privkey: string, quote: string, blindedMessages: Array<SerializedBlindedMessage>): string;
|
||||
export declare function verifyMintQuoteSignature(pubkey: string, quote: string, blindedMessages: Array<SerializedBlindedMessage>, signature: string): boolean;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
import { BlindSignature, Proof, SerializedBlindedMessage, SerializedProof } from '../common/index.js';
|
||||
import { Witness } from '../common/index';
|
||||
import { PrivKey } from '@noble/curves/abstract/utils';
|
||||
export type BlindedMessage = {
|
||||
B_: ProjPointType<bigint>;
|
||||
r: bigint;
|
||||
secret: Uint8Array;
|
||||
witness?: Witness;
|
||||
};
|
||||
export declare function createRandomBlindedMessage(privateKey?: PrivKey): BlindedMessage;
|
||||
export declare function blindMessage(secret: Uint8Array, r?: bigint, privateKey?: PrivKey): BlindedMessage;
|
||||
export declare function unblindSignature(C_: ProjPointType<bigint>, r: bigint, A: ProjPointType<bigint>): ProjPointType<bigint>;
|
||||
export declare function constructProofFromPromise(promise: BlindSignature, r: bigint, secret: Uint8Array, key: ProjPointType<bigint>): Proof;
|
||||
export declare const serializeProof: (proof: Proof) => SerializedProof;
|
||||
export declare const deserializeProof: (proof: SerializedProof) => Proof;
|
||||
export declare const serializeBlindedMessage: (bm: BlindedMessage, amount: number) => SerializedBlindedMessage;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Secret } from './index.js';
|
||||
export declare const parseSecret: (secret: string | Uint8Array) => Secret;
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
export type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
|
||||
export type IntRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
|
||||
export type MintKeys = {
|
||||
[k: string]: Uint8Array;
|
||||
};
|
||||
export type SerializedMintKeys = {
|
||||
[k: string]: string;
|
||||
};
|
||||
export type Keyset = {
|
||||
id: string;
|
||||
unit: string;
|
||||
active: boolean;
|
||||
};
|
||||
export type BlindSignature = {
|
||||
C_: ProjPointType<bigint>;
|
||||
amount: number;
|
||||
id: string;
|
||||
};
|
||||
export type SerializedBlindSignature = {
|
||||
C_: string;
|
||||
amount: number;
|
||||
id: string;
|
||||
};
|
||||
export type DLEQ = {
|
||||
s: Uint8Array;
|
||||
e: Uint8Array;
|
||||
r?: bigint;
|
||||
};
|
||||
export type Proof = {
|
||||
C: ProjPointType<bigint>;
|
||||
secret: Uint8Array;
|
||||
amount: number;
|
||||
id: string;
|
||||
witness?: Witness;
|
||||
};
|
||||
export type SerializedProof = {
|
||||
C: string;
|
||||
secret: string;
|
||||
amount: number;
|
||||
id: string;
|
||||
witness?: string;
|
||||
};
|
||||
export type SerializedBlindedMessage = {
|
||||
B_: string;
|
||||
amount: number;
|
||||
witness?: string;
|
||||
};
|
||||
export type Secret = [WellKnownSecret, SecretData];
|
||||
export type WellKnownSecret = 'P2PK';
|
||||
export type SecretData = {
|
||||
nonce: string;
|
||||
data: string;
|
||||
tags?: Array<Array<string>>;
|
||||
};
|
||||
export type Witness = {
|
||||
signatures: Array<string>;
|
||||
};
|
||||
export type Tags = {
|
||||
[k: string]: string;
|
||||
};
|
||||
export type SigFlag = 'SIG_INPUTS' | 'SIG_ALL';
|
||||
export declare function hashToCurve(secret: Uint8Array): ProjPointType<bigint>;
|
||||
export declare function hash_e(pubkeys: Array<ProjPointType<bigint>>): Uint8Array;
|
||||
export declare function pointFromBytes(bytes: Uint8Array): ProjPointType<bigint>;
|
||||
export declare function pointFromHex(hex: string): ProjPointType<bigint>;
|
||||
export declare const getKeysetIdInt: (keysetId: string) => bigint;
|
||||
export declare function createRandomPrivateKey(): Uint8Array<ArrayBufferLike>;
|
||||
export declare function serializeMintKeys(mintKeys: MintKeys): SerializedMintKeys;
|
||||
export declare function deserializeMintKeys(serializedMintKeys: SerializedMintKeys): MintKeys;
|
||||
export declare function deriveKeysetId(keys: MintKeys): string;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { Proof } from '../common/index.js';
|
||||
import { BlindedMessage } from '../client/index.js';
|
||||
export declare const verifyP2PKSig: (proof: Proof) => boolean;
|
||||
export declare const verifyP2PKSigOutput: (output: BlindedMessage, publicKey: string) => boolean;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { DLEQ } from '../common/index.js';
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
/**
|
||||
* !!! WARNING !!! Not recommended for production use, due to non-constant time operations
|
||||
* See: https://github.com/cashubtc/cashu-crypto-ts/pull/2 for more details
|
||||
* See: https://en.wikipedia.org/wiki/Timing_attack for information about timing attacks.
|
||||
*/
|
||||
export declare const createDLEQProof: (B_: ProjPointType<bigint>, a: Uint8Array) => DLEQ;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
import { BlindSignature, IntRange, Keyset, MintKeys, Proof } from '../common/index.js';
|
||||
export type KeysetPair = {
|
||||
keysetId: string;
|
||||
pubKeys: MintKeys;
|
||||
privKeys: MintKeys;
|
||||
};
|
||||
export type KeysetWithKeys = Keyset & {
|
||||
pubKeys: MintKeys;
|
||||
};
|
||||
export declare function createBlindSignature(B_: ProjPointType<bigint>, privateKey: Uint8Array, amount: number, id: string): BlindSignature;
|
||||
export declare function getPubKeyFromPrivKey(privKey: Uint8Array): Uint8Array<ArrayBufferLike>;
|
||||
export declare function createNewMintKeys(pow2height: IntRange<0, 65>, seed?: Uint8Array): KeysetPair;
|
||||
export declare function verifyProof(proof: Proof, privKey: Uint8Array): boolean;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export declare function bytesToNumber(bytes: Uint8Array): bigint;
|
||||
export declare function hexToNumber(hex: string): bigint;
|
||||
export declare function encodeBase64toUint8(base64String: string): Uint8Array;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { CashuMint } from './CashuMint.js';
|
||||
import { CashuWallet } from './CashuWallet.js';
|
||||
import { OutputData } from './model/OutputData.js';
|
||||
import { PaymentRequest } from './model/PaymentRequest.js';
|
||||
import { setGlobalRequestOptions } from './request.js';
|
||||
import { getEncodedToken, getEncodedTokenV4, getDecodedToken, deriveKeysetId, decodePaymentRequest, getDecodedTokenBinary, getEncodedTokenBinary, hasValidDleq } from './utils.js';
|
||||
import { CashuAuthMint, CashuAuthWallet, getBlindedAuthToken, getEncodedAuthToken } from './auth';
|
||||
export * from './model/types/index.js';
|
||||
export { CashuMint, CashuWallet, CashuAuthMint, CashuAuthWallet, getEncodedAuthToken, getBlindedAuthToken, PaymentRequest, OutputData, getDecodedToken, getEncodedToken, getEncodedTokenV4, decodePaymentRequest, deriveKeysetId, setGlobalRequestOptions, getDecodedTokenBinary, getEncodedTokenBinary, hasValidDleq };
|
||||
export { injectWebSocketImpl } from './ws.js';
|
||||
export { MintOperationError, NetworkError, HttpResponseError } from './model/Errors.js';
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { PartialMintQuoteResponse } from '../model/types/index.js';
|
||||
export type MintQuoteResponsePaidDeprecated = {
|
||||
paid?: boolean;
|
||||
};
|
||||
export declare function handleMintQuoteResponseDeprecated(response: PartialMintQuoteResponse & MintQuoteResponsePaidDeprecated): PartialMintQuoteResponse;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { PartialMeltQuoteResponse } from '../model/types/index.js';
|
||||
export type MeltQuoteResponsePaidDeprecated = {
|
||||
paid?: boolean;
|
||||
};
|
||||
export declare function handleMeltQuoteResponseDeprecated(response: PartialMeltQuoteResponse & MeltQuoteResponsePaidDeprecated): PartialMeltQuoteResponse;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { GetInfoResponse } from '../model/types/index.js';
|
||||
export declare function handleMintInfoContactFieldDeprecated(data: GetInfoResponse): GetInfoResponse;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { SerializedBlindedMessage } from './types/index.js';
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
declare class BlindedMessage {
|
||||
amount: number;
|
||||
B_: ProjPointType<bigint>;
|
||||
id: string;
|
||||
constructor(amount: number, B_: ProjPointType<bigint>, id: string);
|
||||
getSerializedBlindedMessage(): SerializedBlindedMessage;
|
||||
}
|
||||
export { BlindedMessage };
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ProjPointType } from '@noble/curves/abstract/weierstrass';
|
||||
import { SerializedBlindedSignature } from './types/index.js';
|
||||
import { DLEQ } from '../crypto/common/index.js';
|
||||
declare class BlindedSignature {
|
||||
id: string;
|
||||
amount: number;
|
||||
C_: ProjPointType<bigint>;
|
||||
dleq?: DLEQ;
|
||||
constructor(id: string, amount: number, C_: ProjPointType<bigint>, dleq?: DLEQ);
|
||||
getSerializedBlindedSignature(): SerializedBlindedSignature;
|
||||
}
|
||||
export { BlindedSignature };
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/** This error is thrown when a HTTP response is not 2XX nor a protocol error. */
|
||||
export declare class HttpResponseError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number);
|
||||
}
|
||||
/** This error is thrown when a network request fails. */
|
||||
export declare class NetworkError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
/**
|
||||
* This error is thrown when a [protocol error](https://github.com/cashubtc/nuts/blob/main/00.md#errors) occurs.
|
||||
* See error codes [here](https://github.com/cashubtc/nuts/blob/main/error_codes.md).
|
||||
*/
|
||||
export declare class MintOperationError extends HttpResponseError {
|
||||
code: number;
|
||||
constructor(code: number, detail: string);
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { GetInfoResponse, MPPMethod, SwapMethod, WebSocketSupport } from './types';
|
||||
export declare class MintInfo {
|
||||
private readonly _mintInfo;
|
||||
private readonly _protectedEnpoints?;
|
||||
constructor(info: GetInfoResponse);
|
||||
isSupported(num: 4 | 5): {
|
||||
disabled: boolean;
|
||||
params: Array<SwapMethod>;
|
||||
};
|
||||
isSupported(num: 7 | 8 | 9 | 10 | 11 | 12 | 14 | 20): {
|
||||
supported: boolean;
|
||||
};
|
||||
isSupported(num: 17): {
|
||||
supported: boolean;
|
||||
params?: Array<WebSocketSupport>;
|
||||
};
|
||||
isSupported(num: 15): {
|
||||
supported: boolean;
|
||||
params?: Array<MPPMethod>;
|
||||
};
|
||||
requiresBlindAuthToken(path: string): boolean;
|
||||
private checkGenericNut;
|
||||
private checkMintMelt;
|
||||
private checkNut17;
|
||||
private checkNut15;
|
||||
get contact(): import('./types').MintContactInfo[];
|
||||
get description(): string | undefined;
|
||||
get description_long(): string | undefined;
|
||||
get name(): string;
|
||||
get pubkey(): string;
|
||||
get nuts(): {
|
||||
'4': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'5': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'7'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'8'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'9'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'10'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'11'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'12'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'14'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'15'?: {
|
||||
methods: Array<MPPMethod>;
|
||||
};
|
||||
'17'?: {
|
||||
supported: Array<WebSocketSupport>;
|
||||
};
|
||||
'20'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'22'?: {
|
||||
bat_max_mint: number;
|
||||
protected_endpoints: Array<{
|
||||
method: "GET" | "POST";
|
||||
path: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
get version(): string;
|
||||
get motd(): string | undefined;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { MintKeys, Proof, SerializedBlindedMessage, SerializedBlindedSignature } from './types';
|
||||
export interface OutputDataLike {
|
||||
blindedMessage: SerializedBlindedMessage;
|
||||
blindingFactor: bigint;
|
||||
secret: Uint8Array;
|
||||
toProof: (signature: SerializedBlindedSignature, keyset: MintKeys) => Proof;
|
||||
}
|
||||
export type OutputDataFactory = (amount: number, keys: MintKeys) => OutputDataLike;
|
||||
export declare function isOutputDataFactory(value: Array<OutputData> | OutputDataFactory): value is OutputDataFactory;
|
||||
export declare class OutputData implements OutputDataLike {
|
||||
blindedMessage: SerializedBlindedMessage;
|
||||
blindingFactor: bigint;
|
||||
secret: Uint8Array;
|
||||
constructor(blindedMessage: SerializedBlindedMessage, blidingFactor: bigint, secret: Uint8Array);
|
||||
toProof(sig: SerializedBlindedSignature, keyset: MintKeys): Proof;
|
||||
static createP2PKData(p2pk: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
}, amount: number, keyset: MintKeys, customSplit?: Array<number>): OutputData[];
|
||||
static createSingleP2PKData(p2pk: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
}, amount: number, keysetId: string): OutputData;
|
||||
static createRandomData(amount: number, keyset: MintKeys, customSplit?: Array<number>): OutputData[];
|
||||
static createSingleRandomData(amount: number, keysetId: string): OutputData;
|
||||
static createDeterministicData(amount: number, seed: Uint8Array, counter: number, keyset: MintKeys, customSplit?: Array<number>): Array<OutputData>;
|
||||
static createSingleDeterministicData(amount: number, seed: Uint8Array, counter: number, keysetId: string): OutputData;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { RawPaymentRequest, NUT10Option, PaymentRequestTransport, PaymentRequestTransportType } from './types';
|
||||
export declare class PaymentRequest {
|
||||
transport?: Array<PaymentRequestTransport> | undefined;
|
||||
id?: string | undefined;
|
||||
amount?: number | undefined;
|
||||
unit?: string | undefined;
|
||||
mints?: Array<string> | undefined;
|
||||
description?: string | undefined;
|
||||
singleUse: boolean;
|
||||
nut10?: NUT10Option | undefined;
|
||||
constructor(transport?: Array<PaymentRequestTransport> | undefined, id?: string | undefined, amount?: number | undefined, unit?: string | undefined, mints?: Array<string> | undefined, description?: string | undefined, singleUse?: boolean, nut10?: NUT10Option | undefined);
|
||||
toRawRequest(): RawPaymentRequest;
|
||||
toEncodedRequest(): string;
|
||||
getTransport(type: PaymentRequestTransportType): PaymentRequestTransport | undefined;
|
||||
static fromRawRequest(rawPaymentRequest: RawPaymentRequest): PaymentRequest;
|
||||
static fromEncodedRequest(encodedRequest: string): PaymentRequest;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { BlindedMessage } from './BlindedMessage.js';
|
||||
import { Proof } from './types/index.js';
|
||||
declare class Split {
|
||||
proofs: Array<Proof>;
|
||||
amount: number;
|
||||
outputs: Array<BlindedMessage>;
|
||||
constructor(proofs: Array<Proof>, amount: number, outputs: Array<BlindedMessage>);
|
||||
getSerializedSplit(): {
|
||||
proofs: Proof[];
|
||||
amount: number;
|
||||
outputs: {
|
||||
amount: number;
|
||||
B_: string;
|
||||
}[];
|
||||
};
|
||||
}
|
||||
export { Split };
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
import { OutputDataFactory, OutputDataLike } from '../OutputData';
|
||||
import { Proof } from './wallet/index';
|
||||
export * from './mint/index';
|
||||
export * from './wallet/index';
|
||||
export type OutputAmounts = {
|
||||
sendAmounts: Array<number>;
|
||||
keepAmounts?: Array<number>;
|
||||
};
|
||||
export type LockedMintQuote = {
|
||||
id: string;
|
||||
privkey: string;
|
||||
};
|
||||
/**
|
||||
* @param {ReceiveOptions} [options] - Optional configuration for token processing:
|
||||
* - `keysetId`: Override the default keyset ID with a custom one fetched from the `/keysets` endpoint.
|
||||
* - `outputAmounts`: Specify output amounts for keeping or sending.
|
||||
* - `proofsWeHave`: Provide stored proofs for optimal output derivation.
|
||||
* - `counter`: Set a counter to deterministically derive secrets (requires CashuWallet initialized with a seed phrase).
|
||||
* - `pubkey`: Lock eCash to a public key (non-deterministic, even with a counter set).
|
||||
* - `privkey`: Create a signature for token secrets.
|
||||
* - `requireDleq`: Verify DLEQ proofs for all provided proofs; reject the token if any proof fails verification.
|
||||
*/
|
||||
export type ReceiveOptions = {
|
||||
keysetId?: string;
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
requireDleq?: boolean;
|
||||
outputData?: Array<OutputDataLike> | OutputDataFactory;
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* @param {SendOptions} [options] - Optional parameters for configuring the send operation:
|
||||
* - `outputAmounts` (OutputAmounts): Specify the amounts to keep and send in the output.
|
||||
* - `counter` (number): Set a counter to derive secrets deterministically. Requires the `CashuWallet` class to be initialized with a seed phrase.
|
||||
* - `proofsWeHave` (Array<Proof>): Provide all currently stored proofs for the mint. Used to derive optimal output amounts.
|
||||
* - `pubkey` (string): Lock eCash to a specified public key. Note that this will not be deterministic, even if a counter is set.
|
||||
* - `privkey` (string): Create a signature for the output secrets if provided.
|
||||
* - `keysetId` (string): Override the keyset ID derived from the current mint keys with a custom one. The keyset ID should be fetched from the `/keysets` endpoint.
|
||||
* - `offline` (boolean): Send proofs offline, if enabled.
|
||||
* - `includeFees` (boolean): Include fees in the response, if enabled.
|
||||
* - `includeDleq` (boolean): Include DLEQ proofs in the proofs to be sent, if enabled.
|
||||
*/
|
||||
export type SendOptions = {
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
keysetId?: string;
|
||||
offline?: boolean;
|
||||
includeFees?: boolean;
|
||||
includeDleq?: boolean;
|
||||
outputData?: {
|
||||
send?: Array<OutputDataLike> | OutputDataFactory;
|
||||
keep?: Array<OutputDataLike> | OutputDataFactory;
|
||||
};
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* @param {SwapOptions} [options] - Optional parameters for configuring the swap operation:
|
||||
* - `amount`: amount to send while performing the optimal split (least proofs possible). can be set to undefined if preference is set
|
||||
* - proofs proofs matching that amount
|
||||
* - outputAmounts? optionally specify the output's amounts to keep and to send.
|
||||
* - counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* - keysetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint
|
||||
* - includeFees? include estimated fees for the receiver to receive the proofs
|
||||
* - proofsWeHave? optionally provide all currently stored proofs of this mint. Cashu-ts will use them to derive the optimal output amounts
|
||||
* - pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!
|
||||
* - privkey? will create a signature on the proofs secrets if set
|
||||
*/
|
||||
export type SwapOptions = {
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
privkey?: string;
|
||||
keysetId?: string;
|
||||
includeFees?: boolean;
|
||||
outputData?: {
|
||||
send?: Array<OutputDataLike> | OutputDataFactory;
|
||||
keep?: Array<OutputDataLike> | OutputDataFactory;
|
||||
};
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
export type RestoreOptions = {
|
||||
keysetId?: string;
|
||||
};
|
||||
/**
|
||||
* @param {MintProofOptions} [options] - Optional parameters for configuring the Mint Proof operation:
|
||||
* - `keysetId`: override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint
|
||||
* - `outputAmounts`: optionally specify the output's amounts to keep and to send.
|
||||
* - `counter`: optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* - `proofsWeHave`: optionally provide all currently stored proofs of this mint. Cashu-ts will use them to derive the optimal output amounts
|
||||
* - `pubkey`: optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!
|
||||
*/
|
||||
export type MintProofOptions = {
|
||||
keysetId?: string;
|
||||
outputAmounts?: OutputAmounts;
|
||||
proofsWeHave?: Array<Proof>;
|
||||
counter?: number;
|
||||
pubkey?: string;
|
||||
outputData?: Array<OutputDataLike> | OutputDataFactory;
|
||||
p2pk?: {
|
||||
pubkey: string;
|
||||
locktime?: number;
|
||||
refundKeys?: Array<string>;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* @param {MeltProofOptions} [options] - Optional parameters for configuring the Melting Proof operation:
|
||||
* - `keysetId`: override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint
|
||||
* - `counter`: optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
|
||||
* - `privkey`: will create a signature on the proofs secrets if set
|
||||
*/
|
||||
export type MeltProofOptions = {
|
||||
keysetId?: string;
|
||||
counter?: number;
|
||||
privkey?: string;
|
||||
};
|
||||
export type InvoiceData = {
|
||||
paymentRequest: string;
|
||||
amountInSats?: number;
|
||||
amountInMSats?: number;
|
||||
timestamp?: number;
|
||||
paymentHash?: string;
|
||||
memo?: string;
|
||||
expiry?: number;
|
||||
};
|
||||
type RpcSubKinds = 'bolt11_mint_quote' | 'bolt11_melt_quote' | 'proof_state';
|
||||
export type RpcSubId = string | number | null;
|
||||
type JsonRpcParams = any;
|
||||
export type JsonRpcReqParams = {
|
||||
kind: RpcSubKinds;
|
||||
filters: Array<string>;
|
||||
subId: string;
|
||||
};
|
||||
type JsonRpcSuccess<T = any> = {
|
||||
jsonrpc: '2.0';
|
||||
result: T;
|
||||
id: RpcSubId;
|
||||
};
|
||||
export type JsonRpcErrorObject = {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: any;
|
||||
};
|
||||
type JsonRpcError = {
|
||||
jsonrpc: '2.0';
|
||||
error: JsonRpcErrorObject;
|
||||
id: RpcSubId;
|
||||
};
|
||||
type JsonRpcRequest = {
|
||||
jsonrpc: '2.0';
|
||||
method: 'sub';
|
||||
params: JsonRpcReqParams;
|
||||
id: Exclude<RpcSubId, null>;
|
||||
};
|
||||
export type JsonRpcNotification = {
|
||||
jsonrpc: '2.0';
|
||||
method: string;
|
||||
params?: JsonRpcParams;
|
||||
};
|
||||
export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { SerializedBlindedMessage } from '../wallet';
|
||||
export * from './responses';
|
||||
export * from './keys';
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when checking for spendable proofs
|
||||
*/
|
||||
export type CheckStatePayload = {
|
||||
/**
|
||||
* The Y = hash_to_curve(secret) of the proofs to be checked.
|
||||
*/
|
||||
Ys: Array<string>;
|
||||
};
|
||||
/**
|
||||
* Request to mint at /v1/restore endpoint
|
||||
*/
|
||||
export type PostRestorePayload = {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Public keys are a dictionary of number and string. The number represents the amount that the key signs for.
|
||||
*/
|
||||
export type Keys = {
|
||||
[amount: number]: string;
|
||||
};
|
||||
/**
|
||||
* An array of mint keysets
|
||||
*/
|
||||
export type MintActiveKeys = {
|
||||
/**
|
||||
* Keysets
|
||||
*/
|
||||
keysets: Array<MintKeys>;
|
||||
};
|
||||
/**
|
||||
* An array of mint keyset entries.
|
||||
*/
|
||||
export type MintAllKeysets = {
|
||||
/**
|
||||
* Keysets
|
||||
*/
|
||||
keysets: Array<MintKeyset>;
|
||||
};
|
||||
/**
|
||||
* A mint keyset.
|
||||
*/
|
||||
export type MintKeys = {
|
||||
/**
|
||||
* Keyset ID
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Unit of the keyset.
|
||||
*/
|
||||
unit: string;
|
||||
/**
|
||||
* Public keys are a dictionary of number and string. The number represents the amount that the key signs for.
|
||||
*/
|
||||
keys: Keys;
|
||||
};
|
||||
/**
|
||||
* A mint keyset entry.
|
||||
*/
|
||||
export type MintKeyset = {
|
||||
/**
|
||||
* Keyset ID
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Unit of the keyset.
|
||||
*/
|
||||
unit: string;
|
||||
/**
|
||||
* Whether the keyset is active or not.
|
||||
*/
|
||||
active: boolean;
|
||||
/**
|
||||
* Input fee for keyset (in ppk)
|
||||
*/
|
||||
input_fee_ppk?: number;
|
||||
};
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
import { SerializedBlindedMessage } from '../wallet';
|
||||
/**
|
||||
* Cashu api error
|
||||
*/
|
||||
export type ApiError = {
|
||||
/**
|
||||
* Error message
|
||||
*/
|
||||
error?: string;
|
||||
/**
|
||||
* HTTP error code
|
||||
*/
|
||||
code?: number;
|
||||
/**
|
||||
* Detailed error message
|
||||
*/
|
||||
detail?: string;
|
||||
};
|
||||
/**
|
||||
* Entries of CheckStateResponse with state of the proof
|
||||
*/
|
||||
export type ProofState = {
|
||||
Y: string;
|
||||
state: CheckStateEnum;
|
||||
witness: string | null;
|
||||
};
|
||||
/**
|
||||
* Enum for the state of a proof
|
||||
*/
|
||||
export declare const CheckStateEnum: {
|
||||
readonly UNSPENT: "UNSPENT";
|
||||
readonly PENDING: "PENDING";
|
||||
readonly SPENT: "SPENT";
|
||||
};
|
||||
export type CheckStateEnum = (typeof CheckStateEnum)[keyof typeof CheckStateEnum];
|
||||
/**
|
||||
* Response when checking proofs if they are spendable. Should not rely on this for receiving, since it can be easily cheated.
|
||||
*/
|
||||
export type CheckStateResponse = {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
states: Array<ProofState>;
|
||||
} & ApiError;
|
||||
/**
|
||||
* Response from mint at /info endpoint
|
||||
*/
|
||||
export type GetInfoResponse = {
|
||||
name: string;
|
||||
pubkey: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
description_long?: string;
|
||||
icon_url?: string;
|
||||
contact: Array<MintContactInfo>;
|
||||
nuts: {
|
||||
'4': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'5': {
|
||||
methods: Array<SwapMethod>;
|
||||
disabled: boolean;
|
||||
};
|
||||
'7'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'8'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'9'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'10'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'11'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'12'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'14'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'15'?: {
|
||||
methods: Array<MPPMethod>;
|
||||
};
|
||||
'17'?: {
|
||||
supported: Array<WebSocketSupport>;
|
||||
};
|
||||
'20'?: {
|
||||
supported: boolean;
|
||||
};
|
||||
'22'?: {
|
||||
bat_max_mint: number;
|
||||
protected_endpoints: Array<{
|
||||
method: 'GET' | 'POST';
|
||||
path: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
motd?: string;
|
||||
};
|
||||
/**
|
||||
* Response from the mint after requesting a melt quote
|
||||
*/
|
||||
export type PartialMeltQuoteResponse = {
|
||||
/**
|
||||
* Quote ID
|
||||
*/
|
||||
quote: string;
|
||||
/**
|
||||
* Amount to be melted
|
||||
*/
|
||||
amount: number;
|
||||
/**
|
||||
* Fee reserve to be added to the amount
|
||||
*/
|
||||
fee_reserve: number;
|
||||
/**
|
||||
* State of the melt quote
|
||||
*/
|
||||
state: MeltQuoteState;
|
||||
/**
|
||||
* Timestamp of when the quote expires
|
||||
*/
|
||||
expiry: number;
|
||||
/**
|
||||
* preimage of the paid invoice. is null if it the invoice has not been paid yet. can be null, depending on which LN-backend the mint uses
|
||||
*/
|
||||
payment_preimage: string | null;
|
||||
/**
|
||||
* Return/Change from overpaid fees. This happens due to Lighting fee estimation being inaccurate
|
||||
*/
|
||||
change?: Array<SerializedBlindedSignature>;
|
||||
/**
|
||||
* Payment request for the melt quote.
|
||||
*/
|
||||
request?: string;
|
||||
/**
|
||||
* Unit of the melt quote.
|
||||
*/
|
||||
unit?: string;
|
||||
} & ApiError;
|
||||
export type MeltQuoteResponse = PartialMeltQuoteResponse & {
|
||||
request: string;
|
||||
unit: string;
|
||||
};
|
||||
export declare const MeltQuoteState: {
|
||||
readonly UNPAID: "UNPAID";
|
||||
readonly PENDING: "PENDING";
|
||||
readonly PAID: "PAID";
|
||||
};
|
||||
export type MeltQuoteState = (typeof MeltQuoteState)[keyof typeof MeltQuoteState];
|
||||
export type MintContactInfo = {
|
||||
method: string;
|
||||
info: string;
|
||||
};
|
||||
export declare const MintQuoteState: {
|
||||
readonly UNPAID: "UNPAID";
|
||||
readonly PAID: "PAID";
|
||||
readonly ISSUED: "ISSUED";
|
||||
};
|
||||
export type MintQuoteState = (typeof MintQuoteState)[keyof typeof MintQuoteState];
|
||||
/**
|
||||
* Response from the mint after requesting a mint
|
||||
*/
|
||||
export type PartialMintQuoteResponse = {
|
||||
/**
|
||||
* Payment request
|
||||
*/
|
||||
request: string;
|
||||
/**
|
||||
* Quote ID
|
||||
*/
|
||||
quote: string;
|
||||
/**
|
||||
* State of the mint quote
|
||||
*/
|
||||
state: MintQuoteState;
|
||||
/**
|
||||
* Timestamp of when the quote expires
|
||||
*/
|
||||
expiry: number;
|
||||
/**
|
||||
* Public key the quote is locked to
|
||||
*/
|
||||
pubkey?: string;
|
||||
/**
|
||||
* Unit of the quote
|
||||
*/
|
||||
unit?: string;
|
||||
/**
|
||||
* Amount requested for mint quote
|
||||
*/
|
||||
amount?: number;
|
||||
} & ApiError;
|
||||
export type MintQuoteResponse = PartialMintQuoteResponse & {
|
||||
amount: number;
|
||||
unit: string;
|
||||
};
|
||||
export type LockedMintQuoteResponse = MintQuoteResponse & {
|
||||
pubkey: string;
|
||||
};
|
||||
/**
|
||||
* Response from the mint after requesting a mint
|
||||
*/
|
||||
export type MintResponse = {
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
/**
|
||||
* Response from mint at /v1/restore endpoint
|
||||
*/
|
||||
export type PostRestoreResponse = {
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
};
|
||||
export type SerializedDLEQ = {
|
||||
s: string;
|
||||
e: string;
|
||||
r?: string;
|
||||
};
|
||||
/**
|
||||
* Blinded signature as it is received from the mint
|
||||
*/
|
||||
export type SerializedBlindedSignature = {
|
||||
/**
|
||||
* keyset id for indicating which public key was used to sign the blinded message
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Amount denominated in Satoshi
|
||||
*/
|
||||
amount: number;
|
||||
/**
|
||||
* Blinded signature
|
||||
*/
|
||||
C_: string;
|
||||
/**
|
||||
* DLEQ Proof
|
||||
*/
|
||||
dleq?: SerializedDLEQ;
|
||||
};
|
||||
/**
|
||||
* Ecash to other MoE swap method, displayed in @type {GetInfoResponse}
|
||||
*/
|
||||
export type SwapMethod = {
|
||||
method: string;
|
||||
unit: string;
|
||||
min_amount: number;
|
||||
max_amount: number;
|
||||
};
|
||||
/**
|
||||
* Response from the mint after performing a split action
|
||||
*/
|
||||
export type SwapResponse = {
|
||||
/**
|
||||
* represents the outputs after the split
|
||||
*/
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
/**
|
||||
* MPP supported methods
|
||||
*/
|
||||
export type MPPMethod = {
|
||||
method: string;
|
||||
unit: string;
|
||||
};
|
||||
/**
|
||||
* WebSocket supported methods
|
||||
*/
|
||||
export type WebSocketSupport = {
|
||||
method: string;
|
||||
unit: string;
|
||||
commands: Array<string>;
|
||||
};
|
||||
/**
|
||||
* Response from the mint after blind auth minting
|
||||
*/
|
||||
export type BlindAuthMintResponse = {
|
||||
signatures: Array<SerializedBlindedSignature>;
|
||||
} & ApiError;
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { SerializedDLEQ } from '../mint';
|
||||
export * from './payloads';
|
||||
export * from './responses';
|
||||
export * from './tokens';
|
||||
export * from './paymentRequests';
|
||||
/**
|
||||
* represents a single Cashu proof.
|
||||
*/
|
||||
export type Proof = {
|
||||
/**
|
||||
* Keyset id, used to link proofs to a mint an its MintKeys.
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Amount denominated in Satoshis. Has to match the amount of the mints signing key.
|
||||
*/
|
||||
amount: number;
|
||||
/**
|
||||
* The initial secret that was (randomly) chosen for the creation of this proof.
|
||||
*/
|
||||
secret: string;
|
||||
/**
|
||||
* The unblinded signature for this secret, signed by the mints private key.
|
||||
*/
|
||||
C: string;
|
||||
/**
|
||||
* DLEQ proof
|
||||
*/
|
||||
dleq?: SerializedDLEQ;
|
||||
/**
|
||||
* The witness for this proof.
|
||||
*/
|
||||
witness?: string | P2PKWitness | HTLCWitness;
|
||||
};
|
||||
/**
|
||||
* P2PK witness
|
||||
*/
|
||||
export type P2PKWitness = {
|
||||
/**
|
||||
* An array of signatures in hex format
|
||||
*/
|
||||
signatures?: Array<string>;
|
||||
};
|
||||
/**
|
||||
* HTLC witness
|
||||
*/
|
||||
export type HTLCWitness = {
|
||||
/**
|
||||
* preimage
|
||||
*/
|
||||
preimage: string;
|
||||
/**
|
||||
* An array of signatures in hex format
|
||||
*/
|
||||
signatures?: Array<string>;
|
||||
};
|
||||
/**
|
||||
* response when after receiving a single TokenEntry
|
||||
*/
|
||||
export type ReceiveTokenEntryResponse = {
|
||||
/**
|
||||
* Received proofs
|
||||
*/
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when paying a lightning invoice.
|
||||
*/
|
||||
export type PaymentPayload = {
|
||||
/**
|
||||
* Payment request/Lighting invoice that should get paid by the mint.
|
||||
*/
|
||||
pr: string;
|
||||
/**
|
||||
* Proofs, matching Lightning invoices amount + fees.
|
||||
*/
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
/**
|
||||
* @deprecated Token V2
|
||||
* should no longer be used
|
||||
*/
|
||||
export type TokenV2 = {
|
||||
proofs: Array<Proof>;
|
||||
mints: Array<{
|
||||
url: string;
|
||||
ids: Array<string>;
|
||||
}>;
|
||||
};
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
import { OutputData } from '../../OutputData';
|
||||
import { Proof } from './index';
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when melting. Includes Return for overpaid fees
|
||||
*/
|
||||
export type MeltPayload = {
|
||||
/**
|
||||
* ID of the melt quote
|
||||
*/
|
||||
quote: string;
|
||||
/**
|
||||
* Inputs (Proofs) to be melted
|
||||
*/
|
||||
inputs: Array<Proof>;
|
||||
/**
|
||||
* Blank outputs (blinded messages) that can be filled by the mint to return overpaid fees
|
||||
*/
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be send to the mint to request a melt quote
|
||||
*/
|
||||
export type MeltQuotePayload = {
|
||||
/**
|
||||
* Unit to be melted
|
||||
*/
|
||||
unit: string;
|
||||
/**
|
||||
* Request to be melted to
|
||||
*/
|
||||
request: string;
|
||||
/**
|
||||
* Melt Quote options (e.g. multi-path payments NUT-15)
|
||||
*/
|
||||
options?: MeltQuoteOptions;
|
||||
};
|
||||
/**
|
||||
* Melt quote specific options
|
||||
*/
|
||||
export type MeltQuoteOptions = {
|
||||
mpp: MPPOption;
|
||||
};
|
||||
/**
|
||||
* Multi path payments option
|
||||
*/
|
||||
export type MPPOption = {
|
||||
amount: number;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when requesting a mint
|
||||
*/
|
||||
export type MintPayload = {
|
||||
/**
|
||||
* Quote ID received from the mint.
|
||||
*/
|
||||
quote: string;
|
||||
/**
|
||||
* Outputs (blinded messages) to be signed by the mint.
|
||||
*/
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
/**
|
||||
* Public key the quote is locked to
|
||||
*/
|
||||
signature?: string;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when requesting a mint
|
||||
*/
|
||||
export type MintQuotePayload = {
|
||||
/**
|
||||
* Unit to be minted
|
||||
*/
|
||||
unit: string;
|
||||
/**
|
||||
* Amount to be minted
|
||||
*/
|
||||
amount: number;
|
||||
/**
|
||||
* Description for the invoice
|
||||
*/
|
||||
description?: string;
|
||||
/**
|
||||
* Public key to lock the quote to
|
||||
*/
|
||||
pubkey?: string;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when performing a split action
|
||||
*/
|
||||
export type SwapPayload = {
|
||||
/**
|
||||
* Inputs to the split operation
|
||||
*/
|
||||
inputs: Array<Proof>;
|
||||
/**
|
||||
* Outputs (blinded messages) to be signed by the mint
|
||||
*/
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
/**
|
||||
* blinded message for sending to the mint
|
||||
*/
|
||||
export type SerializedBlindedMessage = {
|
||||
/**
|
||||
* amount
|
||||
*/
|
||||
amount: number;
|
||||
/**
|
||||
* Blinded message
|
||||
*/
|
||||
B_: string;
|
||||
/**
|
||||
* Keyset id
|
||||
*/
|
||||
id: string;
|
||||
};
|
||||
/**
|
||||
* Payload that needs to be sent to the mint when requesting blind auth tokens
|
||||
*/
|
||||
export type BlindAuthMintPayload = {
|
||||
/**
|
||||
* Outputs (blinded messages) to be signed by the mint.
|
||||
*/
|
||||
outputs: Array<SerializedBlindedMessage>;
|
||||
};
|
||||
/**
|
||||
* includes all data required to swap inputs for outputs and construct proofs from them.
|
||||
*/
|
||||
export type SwapTransaction = {
|
||||
/**
|
||||
* payload that will be sent to the mint for a swap
|
||||
*/
|
||||
payload: SwapPayload;
|
||||
/**
|
||||
* blinding data required to construct proofs
|
||||
*/
|
||||
outputData: Array<OutputData>;
|
||||
/**
|
||||
* list of booleans to determine which proofs to keep
|
||||
*/
|
||||
keepVector: Array<boolean>;
|
||||
/**
|
||||
* indices that can be used to restore original output data
|
||||
*/
|
||||
sortedIndices: Array<number>;
|
||||
};
|
||||
Generated
Vendored
+46
@@ -0,0 +1,46 @@
|
||||
import { Proof } from './index';
|
||||
export type RawTransport = {
|
||||
t: PaymentRequestTransportType;
|
||||
a: string;
|
||||
g?: Array<Array<string>>;
|
||||
};
|
||||
export type RawNUT10Option = {
|
||||
k: string;
|
||||
d: string;
|
||||
t: Array<Array<string>>;
|
||||
};
|
||||
export type RawPaymentRequest = {
|
||||
i?: string;
|
||||
a?: number;
|
||||
u?: string;
|
||||
s?: boolean;
|
||||
m?: Array<string>;
|
||||
d?: string;
|
||||
t?: Array<RawTransport>;
|
||||
nut10?: RawNUT10Option;
|
||||
};
|
||||
export type PaymentRequestTransport = {
|
||||
type: PaymentRequestTransportType;
|
||||
target: string;
|
||||
tags?: Array<Array<string>>;
|
||||
};
|
||||
export declare enum PaymentRequestTransportType {
|
||||
POST = "post",
|
||||
NOSTR = "nostr"
|
||||
}
|
||||
export type PaymentRequestPayload = {
|
||||
id?: string;
|
||||
memo?: string;
|
||||
unit: string;
|
||||
mint: string;
|
||||
proofs: Array<Proof>;
|
||||
};
|
||||
/** Used to express a spending condition that proofs should be encumbered with */
|
||||
export type NUT10Option = {
|
||||
/** The kind of spending condition */
|
||||
kind: string;
|
||||
/** Expresses the spending condition relative to the kind */
|
||||
data: string;
|
||||
/** Tags associated with the spending condition for additional data */
|
||||
tags: Array<Array<string>>;
|
||||
};
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { MeltQuoteResponse } from '../mint';
|
||||
import { Proof, Token } from './index';
|
||||
/**
|
||||
* Response after paying a Lightning invoice
|
||||
*/
|
||||
export type MeltProofsResponse = {
|
||||
/**
|
||||
* if false, the proofs have not been invalidated and the payment can be tried later again with the same proofs
|
||||
*/
|
||||
quote: MeltQuoteResponse;
|
||||
/**
|
||||
* Return/Change from overpaid fees. This happens due to Lighting fee estimation being inaccurate
|
||||
*/
|
||||
change: Array<Proof>;
|
||||
};
|
||||
/**
|
||||
* Response when receiving a complete token.
|
||||
*/
|
||||
export type ReceiveResponse = {
|
||||
/**
|
||||
* Successfully received Cashu Token
|
||||
*/
|
||||
token: Token;
|
||||
/**
|
||||
* TokenEntries that had errors. No error will be thrown, but clients can choose to handle tokens with errors accordingly.
|
||||
*/
|
||||
tokensWithErrors: Token | undefined;
|
||||
};
|
||||
/**
|
||||
* response after sending
|
||||
*/
|
||||
export type SendResponse = {
|
||||
/**
|
||||
* Proofs that exceeded the needed amount
|
||||
*/
|
||||
keep: Array<Proof>;
|
||||
/**
|
||||
* Proofs to be sent, matching the chosen amount
|
||||
*/
|
||||
send: Array<Proof>;
|
||||
serialized?: Array<{
|
||||
proof: Proof;
|
||||
keep: boolean;
|
||||
}>;
|
||||
};
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { Proof } from './index';
|
||||
/**
|
||||
* A Cashu token
|
||||
*/
|
||||
export type Token = {
|
||||
/**
|
||||
* the mints URL
|
||||
*/
|
||||
mint: string;
|
||||
/**
|
||||
* a list of proofs
|
||||
*/
|
||||
proofs: Array<Proof>;
|
||||
/**
|
||||
* a message to send along with the token
|
||||
*/
|
||||
memo?: string;
|
||||
/**
|
||||
* the unit of the token
|
||||
*/
|
||||
unit?: string;
|
||||
};
|
||||
export type V4DLEQTemplate = {
|
||||
/**
|
||||
* challenge
|
||||
*/
|
||||
e: Uint8Array;
|
||||
/**
|
||||
* response
|
||||
*/
|
||||
s: Uint8Array;
|
||||
/**
|
||||
* blinding factor
|
||||
*/
|
||||
r: Uint8Array;
|
||||
};
|
||||
/**
|
||||
* Template for a Proof inside a V4 Token
|
||||
*/
|
||||
export type V4ProofTemplate = {
|
||||
/**
|
||||
* Amount
|
||||
*/
|
||||
a: number;
|
||||
/**
|
||||
* Secret
|
||||
*/
|
||||
s: string;
|
||||
/**
|
||||
* Signature
|
||||
*/
|
||||
c: Uint8Array;
|
||||
/**
|
||||
* DLEQ
|
||||
*/
|
||||
d?: V4DLEQTemplate;
|
||||
/**
|
||||
* Witness
|
||||
*/
|
||||
w?: string;
|
||||
};
|
||||
/**
|
||||
* TokenEntry in a V4 Token
|
||||
*/
|
||||
export type V4InnerToken = {
|
||||
/**
|
||||
* ID
|
||||
*/
|
||||
i: Uint8Array;
|
||||
/**
|
||||
* Proofs
|
||||
*/
|
||||
p: Array<V4ProofTemplate>;
|
||||
};
|
||||
/**
|
||||
* Template for a V4 Token
|
||||
*/
|
||||
export type TokenV4Template = {
|
||||
/**
|
||||
* TokenEntries
|
||||
*/
|
||||
t: Array<V4InnerToken>;
|
||||
/**
|
||||
* Memo
|
||||
*/
|
||||
d: string;
|
||||
/**
|
||||
* Mint Url
|
||||
*/
|
||||
m: string;
|
||||
/**
|
||||
* Unit
|
||||
*/
|
||||
u: string;
|
||||
};
|
||||
/**
|
||||
* A Cashu token
|
||||
*/
|
||||
export type DeprecatedToken = {
|
||||
/**
|
||||
* token entries
|
||||
*/
|
||||
token: Array<TokenEntry>;
|
||||
/**
|
||||
* a message to send along with the token
|
||||
*/
|
||||
memo?: string;
|
||||
/**
|
||||
* the unit of the token
|
||||
*/
|
||||
unit?: string;
|
||||
};
|
||||
/**
|
||||
* TokenEntry that stores proofs and mints
|
||||
*/
|
||||
type TokenEntry = {
|
||||
/**
|
||||
* a list of proofs
|
||||
*/
|
||||
proofs: Array<Proof>;
|
||||
/**
|
||||
* the mints URL
|
||||
*/
|
||||
mint: string;
|
||||
};
|
||||
export {};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export type OnOpenSuccess = () => void;
|
||||
export type OnOpenError = (err: unknown) => void;
|
||||
export type SubscriptionCanceller = () => void;
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
type RequestArgs = {
|
||||
endpoint: string;
|
||||
requestBody?: Record<string, unknown>;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
type RequestOptions = RequestArgs & Omit<RequestInit, 'body' | 'headers'>;
|
||||
/**
|
||||
* An object containing any custom settings that you want to apply to the global fetch method.
|
||||
* @param options See possible options here: https://developer.mozilla.org/en-US/docs/Web/API/fetch#options
|
||||
*/
|
||||
export declare function setGlobalRequestOptions(options: Partial<RequestOptions>): void;
|
||||
export default function request<T>(options: RequestOptions): Promise<T>;
|
||||
export {};
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import { PaymentRequest } from './model/PaymentRequest.js';
|
||||
import { Keys, MintKeys, Proof, Token } from './model/types/index.js';
|
||||
/**
|
||||
* Splits the amount into denominations of the provided @param keyset
|
||||
* @param value amount to split
|
||||
* @param keyset keys to look up split amounts
|
||||
* @param split? optional custom split amounts
|
||||
* @param order? optional order for split amounts (default: "asc")
|
||||
* @returns Array of split amounts
|
||||
* @throws Error if @param split amount is greater than @param value amount
|
||||
*/
|
||||
export declare function splitAmount(value: number, keyset: Keys, split?: Array<number>, order?: 'desc' | 'asc'): Array<number>;
|
||||
/**
|
||||
* Creates a list of amounts to keep based on the proofs we have and the proofs we want to reach.
|
||||
* @param proofsWeHave complete set of proofs stored (from current mint)
|
||||
* @param amountToKeep amount to keep
|
||||
* @param keys keys of current keyset
|
||||
* @param targetCount the target number of proofs to reach
|
||||
* @returns an array of amounts to keep
|
||||
*/
|
||||
export declare function getKeepAmounts(proofsWeHave: Array<Proof>, amountToKeep: number, keys: Keys, targetCount: number): Array<number>;
|
||||
/**
|
||||
* returns the amounts in the keyset sorted by the order specified
|
||||
* @param keyset to search in
|
||||
* @param order order to sort the amounts in
|
||||
* @returns the amounts in the keyset sorted by the order specified
|
||||
*/
|
||||
export declare function getKeysetAmounts(keyset: Keys, order?: 'asc' | 'desc'): Array<number>;
|
||||
/**
|
||||
* Checks if the provided amount is in the keyset.
|
||||
* @param amount amount to check
|
||||
* @param keyset to search in
|
||||
* @returns true if the amount is in the keyset, false otherwise
|
||||
*/
|
||||
export declare function hasCorrespondingKey(amount: number, keyset: Keys): boolean;
|
||||
/**
|
||||
* Converts a bytes array to a number.
|
||||
* @param bytes to convert to number
|
||||
* @returns number
|
||||
*/
|
||||
export declare function bytesToNumber(bytes: Uint8Array): bigint;
|
||||
/**
|
||||
* Converts a hex string to a number.
|
||||
* @param hex to convert to number
|
||||
* @returns number
|
||||
*/
|
||||
export declare function hexToNumber(hex: string): bigint;
|
||||
/**
|
||||
* Converts a number to a hex string of 64 characters.
|
||||
* @param number (bigint) to conver to hex
|
||||
* @returns hex string start-padded to 64 characters
|
||||
*/
|
||||
export declare function numberToHexPadded64(number: bigint): string;
|
||||
/**
|
||||
* Checks wether a proof or a list of proofs contains a non-hex id
|
||||
* @param p Proof or list of proofs
|
||||
* @returns boolean
|
||||
*/
|
||||
export declare function hasNonHexId(p: Proof | Array<Proof>): boolean;
|
||||
export declare function bigIntStringify<T>(_key: unknown, value: T): string | T;
|
||||
/**
|
||||
* Helper function to encode a v3 cashu token
|
||||
* @param token to encode
|
||||
* @returns encoded token
|
||||
*/
|
||||
export declare function getEncodedTokenV3(token: Token): string;
|
||||
/**
|
||||
* Helper function to encode a cashu token (defaults to v4 if keyset id allows it)
|
||||
* @param token
|
||||
* @param [opts]
|
||||
*/
|
||||
export declare function getEncodedToken(token: Token, opts?: {
|
||||
version: 3 | 4;
|
||||
}): string;
|
||||
export declare function getEncodedTokenV4(token: Token): string;
|
||||
/**
|
||||
* Helper function to decode cashu tokens into object
|
||||
* @param token an encoded cashu token (cashuAey...)
|
||||
* @returns cashu token object
|
||||
*/
|
||||
export declare function getDecodedToken(token: string): Token;
|
||||
/**
|
||||
* Helper function to decode different versions of cashu tokens into an object
|
||||
* @param token an encoded cashu token (cashuAey...)
|
||||
* @returns cashu Token object
|
||||
*/
|
||||
export declare function handleTokens(token: string): Token;
|
||||
/**
|
||||
* Returns the keyset id of a set of keys
|
||||
* @param keys keys object to derive keyset id from
|
||||
* @returns
|
||||
*/
|
||||
export declare function deriveKeysetId(keys: Keys): string;
|
||||
export declare function mergeUInt8Arrays(a1: Uint8Array, a2: Uint8Array): Uint8Array;
|
||||
export declare function sortProofsById(proofs: Array<Proof>): Proof[];
|
||||
export declare function isObj(v: unknown): v is object;
|
||||
export declare function checkResponse(data: {
|
||||
error?: string;
|
||||
detail?: string;
|
||||
}): void;
|
||||
export declare function joinUrls(...parts: Array<string>): string;
|
||||
export declare function sanitizeUrl(url: string): string;
|
||||
export declare function sumProofs(proofs: Array<Proof>): number;
|
||||
export declare function decodePaymentRequest(paymentRequest: string): PaymentRequest;
|
||||
export declare class MessageNode {
|
||||
private _value;
|
||||
private _next;
|
||||
get value(): string;
|
||||
set value(message: string);
|
||||
get next(): MessageNode | null;
|
||||
set next(node: MessageNode | null);
|
||||
constructor(message: string);
|
||||
}
|
||||
export declare class MessageQueue {
|
||||
private _first;
|
||||
private _last;
|
||||
get first(): MessageNode | null;
|
||||
set first(messageNode: MessageNode | null);
|
||||
get last(): MessageNode | null;
|
||||
set last(messageNode: MessageNode | null);
|
||||
private _size;
|
||||
get size(): number;
|
||||
set size(v: number);
|
||||
constructor();
|
||||
enqueue(message: string): boolean;
|
||||
dequeue(): string | null;
|
||||
}
|
||||
/**
|
||||
* Removes all traces of DLEQs from a list of proofs
|
||||
* @param proofs The list of proofs that dleq should be stripped from
|
||||
*/
|
||||
export declare function stripDleq(proofs: Array<Proof>): Array<Omit<Proof, 'dleq'>>;
|
||||
/**
|
||||
* Checks that the proof has a valid DLEQ proof according to
|
||||
* keyset `keys`
|
||||
* @param proof The proof subject to verification
|
||||
* @param keyset The Mint's keyset to be used for verification
|
||||
* @returns true if verification succeeded, false otherwise
|
||||
* @throws Error if @param proof does not match any key in @param keyset
|
||||
*/
|
||||
export declare function hasValidDleq(proof: Proof, keyset: MintKeys): boolean;
|
||||
/**
|
||||
* Helper function to encode a cashu auth token authA
|
||||
* @param proof
|
||||
*/
|
||||
export declare function getEncodedAuthToken(proof: Proof): string;
|
||||
export declare function getEncodedTokenBinary(token: Token): Uint8Array;
|
||||
export declare function getDecodedTokenBinary(bytes: Uint8Array): Token;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* per protocol definition since tokenV3 tokens have a prefix and a version number
|
||||
*/
|
||||
declare const TOKEN_VERSION = "A";
|
||||
declare const TOKEN_PREFIX = "cashu";
|
||||
export { TOKEN_VERSION, TOKEN_PREFIX };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export declare function injectWebSocketImpl(ws: any): void;
|
||||
export declare function getWebSocketImpl(): {
|
||||
new (url: string | URL, protocols?: string | string[]): WebSocket;
|
||||
prototype: WebSocket;
|
||||
readonly CONNECTING: 0;
|
||||
readonly OPEN: 1;
|
||||
readonly CLOSING: 2;
|
||||
readonly CLOSED: 3;
|
||||
};
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
# Version 1.0.0 Migration guide
|
||||
|
||||
⚠️ Upgrading to version 1.0.0 will come with breaking changes! Please follow the migration guide for a smooth transition to the new version.
|
||||
|
||||
## Context
|
||||
|
||||
In Version 1.0.0 the api version of mints has been upgraded to `v1`. Please read the `v1` [v1 cleanup PR](https://github.com/cashubtc/nuts/pull/55) to understand more about how the API has changed.
|
||||
|
||||
## Breaking changes
|
||||
|
||||
### ⚠️ Important! When upgrading to this version, the `hash2curve` function and the `default secret format` have changed. This means deterministic secret derivation will produce NOT THE SAME SECRETS as before. When upgrading to this version, wallets that have been using deterministic secrets (seed phrase) must reset counters and then `self spend`/`refresh` all proofs, so that the backups continue working.
|
||||
|
||||
---
|
||||
|
||||
### Decoding LN invoices
|
||||
|
||||
**Removed LN invoice decode:**
|
||||
Decoding LN invoices is no longer used inside the lib.
|
||||
|
||||
**How to fix:** If you need to decode LN invoices, you can use
|
||||
|
||||
> npm i [@gandlaf21/bolt11-decode](https://www.npmjs.com/package/@gandlaf21/bolt11-decode)
|
||||
|
||||
---
|
||||
|
||||
### `CashuWallet` interface changes
|
||||
|
||||
**`receive()` no longer supports multi-token tokens**
|
||||
|
||||
To reduce complexity, simplify error handling and to prepare for token V4, this feature has been removed. only the first token inside a token will be processed
|
||||
|
||||
**optional function AND constructor parameters are now in an onpional `options?` Object**
|
||||
|
||||
Utility functions now have an `options` object for optional parameters, instead of passing them directly
|
||||
|
||||
**`requestMint(amount: number)` --> `createMintQuote(amount: number)`**
|
||||
Now returns the following:
|
||||
|
||||
```typescript
|
||||
type MintQuoteResponse = {
|
||||
request: string;
|
||||
quote: string;
|
||||
paid: boolean;
|
||||
expiry: number;
|
||||
state: MintQuoteState;
|
||||
};
|
||||
```
|
||||
|
||||
where `request` is the invoice to be paid, and `quote` is the identifier used to pass to `mintTokens()`.
|
||||
|
||||
**`requestTokens()` --> `mintTokens()`**
|
||||
|
||||
---
|
||||
|
||||
**`createMeltQuote(invoice: string)`** is now used to get fee estimation and conversion quotes instead of `getFee()` and returns:
|
||||
|
||||
```typescript
|
||||
type MeltQuoteResponse = {
|
||||
quote: string;
|
||||
amount: number;
|
||||
fee_reserve: number;
|
||||
paid: boolean;
|
||||
expiry: number;
|
||||
payment_preimage: string;
|
||||
state: MeltQuoteState;
|
||||
change?: Array<SerializedBlindedSignature>;
|
||||
};
|
||||
```
|
||||
|
||||
where `quote` is the identifier to pass to `meltTokens()`
|
||||
|
||||
---
|
||||
|
||||
**`receive()`** and **`receiveTokenEntry()`** now return `Array<Proofs>`
|
||||
|
||||
where `Proofs` are the newly created `Proofs` from the received token. Will now throw an error instead of returning `proofsWithError`
|
||||
|
||||
---
|
||||
|
||||
### Model changes
|
||||
|
||||
**`MintKeys`--> `Keys`**:
|
||||
`MintKeys` now include the `keys`, `id` and `unit`
|
||||
|
||||
```typescript
|
||||
type MintKeys = {
|
||||
id: string;
|
||||
unit: string;
|
||||
keys: Keys;
|
||||
};
|
||||
|
||||
type Keys = { [amount: number]: string };
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**`MintKeyset`**:
|
||||
Used to be a string array, but now contains the additional fields `active` and `unit`
|
||||
|
||||
```typescript
|
||||
type MintKeyset = {
|
||||
id: string;
|
||||
unit: string;
|
||||
active: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**`BlindedMessages`:** now include the field `id`, corresponding with the mints `keysetId`
|
||||
|
||||
```typescript
|
||||
type BlindedMessage {
|
||||
amount: number;
|
||||
B_: ProjPointType<bigint>;
|
||||
id: string;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pattern changes
|
||||
|
||||
**removed `newKeys` from returns**: Functions no longer return `newKeys`. Wallets now specify the keyset they use in the BlindedMessage via the `id` field.
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
# Version 2.0.0 Migration guide
|
||||
|
||||
⚠️ Upgrading to version 2.0.0 will come with breaking changes! Please follow the migration guide for a smooth transition to the new version.
|
||||
|
||||
## Breaking changes
|
||||
|
||||
### `CashuWallet` interface changes
|
||||
|
||||
#### removed `payLnInvoice` helper
|
||||
|
||||
The helper function was removed. Instead users will have to manage a melt quote manually:
|
||||
|
||||
```ts
|
||||
const quote = await wallet.createMeltQuote(invoice);
|
||||
const totalAmount = quote.fee_reserve + invoiceAmount;
|
||||
const { keep, send } = await wallet.send(totalAmount, proofs);
|
||||
const payRes = await wallet.meltProofs(quote, send);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Preference for outputs are now passed as a object of simple arrays
|
||||
|
||||
**`AmountPreference`** is not used anymore.
|
||||
|
||||
`preference?: Array<AmountPreference>;` -> `outputAmounts?: OutputAmounts;`
|
||||
|
||||
where
|
||||
|
||||
```typescript
|
||||
export type OutputAmounts = {
|
||||
sendAmounts: Array<number>;
|
||||
keepAmounts?: Array<number>;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### CashuWallet can no longer be instantiated using BIP39 mnemonic!
|
||||
|
||||
In order to reduce the bundle size, BIP39 has been removed as a dependency of cashu-ts. Therefore users that want to use deterministic secrets with a BIP39 menmonic will have to convert the wordlist into a seed manually and then instantiate the wallet using:
|
||||
|
||||
```ts
|
||||
const wallet = new CashuWallet(mint, { bip39seed: uint8ArrayOfSeed });
|
||||
```
|
||||
|
||||
#### `checkProofsStates` replaces `checkProofsSpent`
|
||||
|
||||
To check the state of a `Proof`, call `CashuWallet.checkProofsStates`. `checkProofsStates` now returns an array of `ProofState`'s, one for each `Proof` provided. The spent states are in `ProofState.state` and can have the values `CheckStateEnum.SPENT`, `CheckStateEnum.UNSPENT`, and `CheckStateEnum.PENDING`. `ProofState` also contains a `witness` if present.
|
||||
|
||||
---
|
||||
|
||||
#### renamed functions
|
||||
|
||||
- in `SendResponse`, `returnChange` is now called `keep`
|
||||
- `CashuWallet.mintTokens()` is now called `CashuWallet.mintProofs()` and returns <Promise<Array<Proof>> instead of Promise<{proofs: Array<Proof>}>
|
||||
- `CashuWallet.meltTokens()` is now called `CashuWallet.meltProofs()`
|
||||
- `CashuMint.split()` is now called `CashuMint.swap()`
|
||||
|
||||
---
|
||||
|
||||
### Type changes
|
||||
|
||||
#### Wallet payload types
|
||||
|
||||
- `BlindedTransaction` has been removed
|
||||
- `BlindedMessageData` has been replaced by `BlindingData`
|
||||
- In `BlindingData` `rs` has been renamed to `blindingFactors`
|
||||
|
||||
---
|
||||
|
||||
#### Token Types
|
||||
|
||||
- The `Token` type no longer reassembles the token v3 structure, but instead is a simple object type:
|
||||
|
||||
```ts
|
||||
type Token = {
|
||||
mint: string;
|
||||
proofs: Array<Proof>;
|
||||
memo?: string;
|
||||
unit?: string;
|
||||
};
|
||||
```
|
||||
|
||||
- The old `Token` type got renamed to `DeprecatedToken`
|
||||
|
||||
---
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "@cashu/cashu-ts",
|
||||
"version": "2.5.2",
|
||||
"description": "cashu library for communicating with a cashu mint",
|
||||
"type": "module",
|
||||
"main": "lib/cashu-ts.cjs.js",
|
||||
"module": "lib/cashu-ts.es.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/cashubtc/cashu-ts"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cashubtc/cashu-ts/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"compile": "vite build",
|
||||
"compile:standalone": "BUILD_FORMAT=iife vite build",
|
||||
"test": "vitest run --coverage --exclude ./test/integration.test.ts --exclude ./test/auth.test.ts",
|
||||
"test-integration": "vitest run ./test/integration.test.ts --coverage",
|
||||
"dev": "tsc --watch",
|
||||
"lint": "eslint --ext .js,.ts . --fix",
|
||||
"format": "prettier --write .",
|
||||
"check-format": "prettier --check .",
|
||||
"typedoc": "typedoc src/index.ts",
|
||||
"api:check": "api-extractor run",
|
||||
"api:update": "api-extractor run --local"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"require": "./lib/cashu-ts.cjs.js",
|
||||
"import": "./lib/cashu-ts.es.js",
|
||||
"types": "./lib/types/index.d.ts"
|
||||
},
|
||||
"./crypto/util": {
|
||||
"types": "./modules/util/index.d.ts",
|
||||
"import": "./modules/esm/util/index.js",
|
||||
"default": "./modules/util/index.js"
|
||||
}
|
||||
},
|
||||
"keywords": [
|
||||
"cashu"
|
||||
],
|
||||
"author": "gandlaf21",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@microsoft/api-extractor": "^7.52.4",
|
||||
"@types/node-fetch": "^2.6.4",
|
||||
"@types/ws": "^8.5.10",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.2",
|
||||
"@typescript-eslint/parser": "^5.59.2",
|
||||
"@vitest/browser": "^2.1.5",
|
||||
"@vitest/coverage-v8": "^2.1.5",
|
||||
"eslint": "^8.39.0",
|
||||
"eslint-config-standard-with-typescript": "^34.0.1",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-n": "^15.7.0",
|
||||
"eslint-plugin-promise": "^6.1.1",
|
||||
"mock-socket": "^9.3.1",
|
||||
"msw": "^2.6.6",
|
||||
"node-fetch": "^2.7.0",
|
||||
"playwright": "^1.49.0",
|
||||
"prettier": "^2.8.8",
|
||||
"ts-node": "^10.9.1",
|
||||
"typedoc": "^0.27.5",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^5.4.11",
|
||||
"vite-plugin-dts": "^4.4.0",
|
||||
"vitest": "^2.1.5",
|
||||
"ws": "^8.16.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.6.0",
|
||||
"@noble/hashes": "^1.5.0",
|
||||
"@scure/bip32": "^1.5.0",
|
||||
"buffer": "^6.0.3"
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+998
@@ -0,0 +1,998 @@
|
||||
# noble-curves
|
||||
|
||||
Audited & minimal JS implementation of elliptic curve cryptography.
|
||||
|
||||
- 🔒 [**Audited**](#security) by independent security firms
|
||||
- 🔻 Tree-shakeable: unused code is excluded from your builds
|
||||
- 🏎 Fast: hand-optimized for caveats of JS engines
|
||||
- 🔍 Reliable: cross-library / wycheproof tests and fuzzing ensure correctness
|
||||
- ➰ Short Weierstrass, Edwards, Montgomery curves
|
||||
- ✍️ ECDSA, EdDSA, Schnorr, BLS, ECDH, hashing to curves, Poseidon ZK-friendly hash
|
||||
- 🔖 SUF-CMA, SBS (non-repudiation), ZIP215 (consensus friendliness) features for ed25519 & ed448
|
||||
- 🪶 93KB (36KB gzipped) for everything with hashes, 26KB (11KB gzipped) for single-curve build
|
||||
|
||||
Curves have 4KB sister projects
|
||||
[secp256k1](https://github.com/paulmillr/noble-secp256k1) & [ed25519](https://github.com/paulmillr/noble-ed25519).
|
||||
They have smaller attack surface, but less features.
|
||||
|
||||
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-curves/discussions) for questions and support.
|
||||
|
||||
### This library belongs to _noble_ cryptography
|
||||
|
||||
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
|
||||
|
||||
- Zero or minimal dependencies
|
||||
- Highly readable TypeScript / JS code
|
||||
- PGP-signed releases and transparent NPM builds
|
||||
- All libraries:
|
||||
[ciphers](https://github.com/paulmillr/noble-ciphers),
|
||||
[curves](https://github.com/paulmillr/noble-curves),
|
||||
[hashes](https://github.com/paulmillr/noble-hashes),
|
||||
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
|
||||
4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
|
||||
[ed25519](https://github.com/paulmillr/noble-ed25519)
|
||||
- [Check out homepage](https://paulmillr.com/noble/)
|
||||
for reading resources, documentation and apps built with noble
|
||||
|
||||
## Usage
|
||||
|
||||
> `npm install @noble/curves`
|
||||
|
||||
> `deno add jsr:@noble/curves`
|
||||
|
||||
> `deno doc jsr:@noble/curves` # command-line documentation
|
||||
|
||||
We support all major platforms and runtimes.
|
||||
For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
|
||||
A standalone file [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available.
|
||||
|
||||
```ts
|
||||
// import * from '@noble/curves'; // Error: use sub-imports, to ensure small app size
|
||||
import { secp256k1, schnorr } from '@noble/curves/secp256k1';
|
||||
import { ed25519, ed25519ph, ed25519ctx, x25519 } from '@noble/curves/ed25519';
|
||||
import { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448';
|
||||
import { p256, p384, p521 } from '@noble/curves/nist';
|
||||
import { bls12_381 } from '@noble/curves/bls12-381';
|
||||
import { bn254 } from '@noble/curves/bn254';
|
||||
import { jubjub, babyjubjub } from '@noble/curves/misc';
|
||||
import { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from '@noble/curves/abstract/utils';
|
||||
```
|
||||
|
||||
- [ECDSA signatures over secp256k1 and others](#ecdsa-signatures-over-secp256k1-and-others)
|
||||
- [Hedged ECDSA with noise](#hedged-ecdsa-with-noise)
|
||||
- [ECDH: Diffie-Hellman shared secrets](#ecdh-diffie-hellman-shared-secrets)
|
||||
- [secp256k1 Schnorr signatures from BIP340](#secp256k1-schnorr-signatures-from-bip340)
|
||||
- [ed25519](#ed25519) / [X25519](#x25519) / [ristretto255](#ristretto255)
|
||||
- [ed448](#ed448) / [X448](#x448) / [decaf448](#decaf448)
|
||||
- [bls12-381](#bls12-381)
|
||||
- [bn254 aka alt_bn128](#bn254-aka-alt_bn128)
|
||||
- [misc curves](#misc-curves)
|
||||
- [Low-level methods](#low-level-methods)
|
||||
- [Abstract API](#abstract-api)
|
||||
- [weierstrass](#weierstrass-short-weierstrass-curve), [edwards](#edwards-twisted-edwards-curve), [montgomery](#montgomery-montgomery-curve), [bls](#bls-barreto-lynn-scott-curves)
|
||||
- [hash-to-curve](#hash-to-curve-hashing-strings-to-curve-points), [poseidon](#poseidon-poseidon-hash)
|
||||
- [modular](#modular-modular-arithmetics-utilities)
|
||||
- [fft](#fft-fast-fourier-transform)
|
||||
- [Creating private keys from hashes](#creating-private-keys-from-hashes)
|
||||
- [utils](#utils-useful-utilities)
|
||||
- [Security](#security)
|
||||
- [Speed](#speed)
|
||||
- [Upgrading](#upgrading)
|
||||
- [Contributing & testing](#contributing--testing)
|
||||
- [License](#license)
|
||||
|
||||
### Implementations
|
||||
|
||||
#### ECDSA signatures over secp256k1 and others
|
||||
|
||||
```ts
|
||||
import { secp256k1 } from '@noble/curves/secp256k1';
|
||||
// import { p256 } from '@noble/curves/nist'; // or p384 / p521
|
||||
|
||||
const priv = secp256k1.utils.randomPrivateKey();
|
||||
const pub = secp256k1.getPublicKey(priv);
|
||||
const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
|
||||
const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
|
||||
const isValid = secp256k1.verify(sig, msg, pub) === true;
|
||||
|
||||
// hex strings are also supported besides Uint8Array-s:
|
||||
const privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236';
|
||||
const pub2 = secp256k1.getPublicKey(privHex);
|
||||
|
||||
// public key recovery
|
||||
// let sig = secp256k1.Signature.fromCompact(sigHex); // or .fromDER(sigDERHex)
|
||||
// sig = sig.addRecoveryBit(bit); // bit is not serialized into compact / der format
|
||||
sig.recoverPublicKey(msg).toRawBytes(); // === pub; // public key recovery
|
||||
```
|
||||
|
||||
The same code would work for NIST P256 (secp256r1), P384 (secp384r1) & P521 (secp521r1).
|
||||
|
||||
#### Hedged ECDSA with noise
|
||||
|
||||
```ts
|
||||
const noisySignature = secp256k1.sign(msg, priv, { extraEntropy: true });
|
||||
const ent = new Uint8Array(32).fill(3); // set custom entropy
|
||||
const noisySignature2 = secp256k1.sign(msg, priv, { extraEntropy: ent });
|
||||
```
|
||||
|
||||
Hedged ECDSA is add-on, providing improved protection against fault attacks.
|
||||
It adds noise to signatures. The technique is used by default in BIP340; we also implement them
|
||||
optionally for ECDSA. Check out blog post
|
||||
[Deterministic signatures are not your friends](https://paulmillr.com/posts/deterministic-signatures/)
|
||||
and [spec draft](https://datatracker.ietf.org/doc/draft-irtf-cfrg-det-sigs-with-noise/).
|
||||
|
||||
#### ECDH: Diffie-Hellman shared secrets
|
||||
|
||||
```ts
|
||||
const someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey());
|
||||
const shared = secp256k1.getSharedSecret(priv, someonesPub);
|
||||
// NOTE:
|
||||
// - `shared` includes parity byte: strip it using shared.slice(1)
|
||||
// - `shared` is not hashed: more secure way is sha256(shared) or hkdf(shared)
|
||||
```
|
||||
|
||||
#### secp256k1 Schnorr signatures from BIP340
|
||||
|
||||
```ts
|
||||
import { schnorr } from '@noble/curves/secp256k1';
|
||||
const priv = schnorr.utils.randomPrivateKey();
|
||||
const pub = schnorr.getPublicKey(priv);
|
||||
const msg = new TextEncoder().encode('hello');
|
||||
const sig = schnorr.sign(msg, priv);
|
||||
const isValid = schnorr.verify(sig, msg, pub);
|
||||
```
|
||||
|
||||
#### ed25519
|
||||
|
||||
```ts
|
||||
import { ed25519 } from '@noble/curves/ed25519';
|
||||
const priv = ed25519.utils.randomPrivateKey();
|
||||
const pub = ed25519.getPublicKey(priv);
|
||||
const msg = new TextEncoder().encode('hello');
|
||||
const sig = ed25519.sign(msg, priv);
|
||||
ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
|
||||
ed25519.verify(sig, msg, pub, { zip215: false }); // SBS / e-voting / RFC8032 / FIPS 186-5
|
||||
|
||||
// Variants from RFC8032: with context, prehashed
|
||||
import { ed25519ctx, ed25519ph } from '@noble/curves/ed25519';
|
||||
```
|
||||
|
||||
Default `verify` behavior follows ZIP215 and
|
||||
can be used in consensus-critical applications.
|
||||
If you need SBS (Strongly Binding Signatures) and FIPS 186-5 compliance,
|
||||
use `zip215: false`. Check out [Edwards Signatures section for more info](#edwards-twisted-edwards-curve).
|
||||
Both options have SUF-CMA (strong unforgeability under chosen message attacks).
|
||||
|
||||
#### X25519
|
||||
|
||||
```ts
|
||||
// X25519 aka ECDH on Curve25519 from [RFC7748](https://www.rfc-editor.org/rfc/rfc7748)
|
||||
import { x25519 } from '@noble/curves/ed25519';
|
||||
const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';
|
||||
const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';
|
||||
x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases
|
||||
x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);
|
||||
x25519.getPublicKey(x25519.utils.randomPrivateKey());
|
||||
|
||||
// ed25519 => x25519 conversion
|
||||
import { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519';
|
||||
edwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey()));
|
||||
edwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey());
|
||||
```
|
||||
|
||||
#### ristretto255
|
||||
|
||||
```ts
|
||||
// ristretto255 from [RFC9496](https://www.rfc-editor.org/rfc/rfc9496)
|
||||
import { utf8ToBytes } from '@noble/hashes/utils';
|
||||
import { sha512 } from '@noble/hashes/sha512';
|
||||
import {
|
||||
hashToCurve,
|
||||
encodeToCurve,
|
||||
RistrettoPoint,
|
||||
hashToRistretto255,
|
||||
} from '@noble/curves/ed25519';
|
||||
|
||||
const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee');
|
||||
hashToCurve(msg);
|
||||
|
||||
const rp = RistrettoPoint.fromHex(
|
||||
'6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919'
|
||||
);
|
||||
RistrettoPoint.BASE.multiply(2n).add(rp).subtract(RistrettoPoint.BASE).toRawBytes();
|
||||
RistrettoPoint.ZERO.equals(dp) === false;
|
||||
// pre-hashed hash-to-curve
|
||||
RistrettoPoint.hashToCurve(sha512(msg));
|
||||
// full hash-to-curve including domain separation tag
|
||||
hashToRistretto255(msg, { DST: 'ristretto255_XMD:SHA-512_R255MAP_RO_' });
|
||||
```
|
||||
|
||||
#### ed448
|
||||
|
||||
```ts
|
||||
import { ed448 } from '@noble/curves/ed448';
|
||||
const priv = ed448.utils.randomPrivateKey();
|
||||
const pub = ed448.getPublicKey(priv);
|
||||
const msg = new TextEncoder().encode('whatsup');
|
||||
const sig = ed448.sign(msg, priv);
|
||||
ed448.verify(sig, msg, pub);
|
||||
|
||||
// Variants from RFC8032: prehashed
|
||||
import { ed448ph } from '@noble/curves/ed448';
|
||||
```
|
||||
|
||||
#### X448
|
||||
|
||||
```ts
|
||||
// X448 aka ECDH on Curve448 from [RFC7748](https://www.rfc-editor.org/rfc/rfc7748)
|
||||
import { x448 } from '@noble/curves/ed448';
|
||||
x448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases
|
||||
x448.getPublicKey(priv) === x448.scalarMultBase(priv);
|
||||
|
||||
// ed448 => x448 conversion
|
||||
import { edwardsToMontgomeryPub } from '@noble/curves/ed448';
|
||||
edwardsToMontgomeryPub(ed448.getPublicKey(ed448.utils.randomPrivateKey()));
|
||||
```
|
||||
|
||||
#### decaf448
|
||||
|
||||
```ts
|
||||
// decaf448 from [RFC9496](https://www.rfc-editor.org/rfc/rfc9496)
|
||||
import { utf8ToBytes } from '@noble/hashes/utils';
|
||||
import { shake256 } from '@noble/hashes/sha3';
|
||||
import { hashToCurve, encodeToCurve, DecafPoint, hashToDecaf448 } from '@noble/curves/ed448';
|
||||
|
||||
const msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee');
|
||||
hashToCurve(msg);
|
||||
|
||||
const dp = DecafPoint.fromHex(
|
||||
'c898eb4f87f97c564c6fd61fc7e49689314a1f818ec85eeb3bd5514ac816d38778f69ef347a89fca817e66defdedce178c7cc709b2116e75'
|
||||
);
|
||||
DecafPoint.BASE.multiply(2n).add(dp).subtract(DecafPoint.BASE).toRawBytes();
|
||||
DecafPoint.ZERO.equals(dp) === false;
|
||||
// pre-hashed hash-to-curve
|
||||
DecafPoint.hashToCurve(shake256(msg, { dkLen: 112 }));
|
||||
// full hash-to-curve including domain separation tag
|
||||
hashToDecaf448(msg, { DST: 'decaf448_XOF:SHAKE256_D448MAP_RO_' });
|
||||
```
|
||||
|
||||
#### bls12-381
|
||||
|
||||
```ts
|
||||
import { bls12_381 as bls } from '@noble/curves/bls12-381';
|
||||
|
||||
// G1 keys, G2 signatures
|
||||
const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c';
|
||||
const message = '64726e3da8';
|
||||
const publicKey = bls.getPublicKey(privateKey);
|
||||
const signature = bls.sign(message, privateKey);
|
||||
const isValid = bls.verify(signature, message, publicKey);
|
||||
console.log({ publicKey, signature, isValid });
|
||||
|
||||
// G2 keys, G1 signatures
|
||||
// getPublicKeyForShortSignatures(privateKey)
|
||||
// signShortSignature(message, privateKey)
|
||||
// verifyShortSignature(signature, message, publicKey)
|
||||
// aggregateShortSignatures(signatures)
|
||||
|
||||
// Custom DST
|
||||
const htfEthereum = { DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' };
|
||||
const signatureEth = bls.sign(message, privateKey, htfEthereum);
|
||||
const isValidEth = bls.verify(signature, message, publicKey, htfEthereum);
|
||||
|
||||
// Aggregation
|
||||
const aggregatedKey = bls.aggregatePublicKeys([
|
||||
bls.utils.randomPrivateKey(),
|
||||
bls.utils.randomPrivateKey(),
|
||||
]);
|
||||
// const aggregatedSig = bls.aggregateSignatures(sigs)
|
||||
|
||||
// Pairings, with and without final exponentiation
|
||||
// bls.pairing(PointG1, PointG2);
|
||||
// bls.pairing(PointG1, PointG2, false);
|
||||
// bls.fields.Fp12.finalExponentiate(bls.fields.Fp12.mul(PointG1, PointG2));
|
||||
|
||||
// Others
|
||||
// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE;
|
||||
// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr;
|
||||
```
|
||||
|
||||
See [abstract/bls](#bls-barreto-lynn-scott-curves).
|
||||
For example usage, check out [the implementation of BLS EVM precompiles](https://github.com/ethereumjs/ethereumjs-monorepo/blob/361f4edbc239e795a411ac2da7e5567298b9e7e5/packages/evm/src/precompiles/bls12_381/noble.ts).
|
||||
|
||||
#### bn254 aka alt_bn128
|
||||
|
||||
```ts
|
||||
import { bn254 } from '@noble/curves/bn254';
|
||||
|
||||
console.log(bn254.G1, bn254.G2, bn254.pairing);
|
||||
```
|
||||
|
||||
The API mirrors [BLS](#bls12-381). The curve was previously called alt_bn128.
|
||||
The implementation is compatible with [EIP-196](https://eips.ethereum.org/EIPS/eip-196) and
|
||||
[EIP-197](https://eips.ethereum.org/EIPS/eip-197).
|
||||
|
||||
We don't implement Point methods toHex / toRawBytes.
|
||||
To work around this limitation, has to initialize points on their own from BigInts.
|
||||
Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109).
|
||||
Points of divergence:
|
||||
|
||||
- Endianness: LE vs BE (byte-swapped)
|
||||
- Flags as first hex bits (similar to BLS) vs no-flags
|
||||
- Imaginary part last in G2 vs first (c0, c1 vs c1, c0)
|
||||
|
||||
For example usage, check out [the implementation of bn254 EVM precompiles](https://github.com/paulmillr/noble-curves/blob/3ed792f8ad9932765b84d1064afea8663a255457/test/bn254.test.js#L697).
|
||||
|
||||
#### misc curves
|
||||
|
||||
```ts
|
||||
import { jubjub, babyjubjub } from '@noble/curves/misc';
|
||||
```
|
||||
|
||||
Miscellaneous, rarely used curves are contained in the module.
|
||||
Jubjub curves have Fp over scalar fields of other curves. They are friendly to ZK proofs.
|
||||
jubjub Fp = bls n. babyjubjub Fp = bn254 n.
|
||||
|
||||
#### Low-level methods
|
||||
|
||||
```ts
|
||||
import { secp256k1 } from '@noble/curves/secp256k1';
|
||||
|
||||
// Curve's variables
|
||||
// Every curve has `CURVE` object that contains its parameters, field, and others
|
||||
console.log(secp256k1.CURVE.p); // field modulus
|
||||
console.log(secp256k1.CURVE.n); // curve order
|
||||
console.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params
|
||||
console.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates
|
||||
|
||||
// MSM
|
||||
const p = secp256k1.ProjectivePoint;
|
||||
const points = [p.BASE, p.BASE.multiply(2n), p.BASE.multiply(4n), p.BASE.multiply(8n)];
|
||||
p.msm(points, [3n, 5n, 7n, 11n]).equals(p.BASE.multiply(129n)); // 129*G
|
||||
```
|
||||
|
||||
Multi-scalar-multiplication (MSM) is basically `(Pa + Qb + Rc + ...)`.
|
||||
It's 10-30x faster vs naive addition for large amount of points.
|
||||
Pippenger algorithm is used underneath.
|
||||
|
||||
## Abstract API
|
||||
|
||||
Implementations use [noble-hashes](https://github.com/paulmillr/noble-hashes).
|
||||
If you want to use a different hashing library, abstract API doesn't depend on them.
|
||||
|
||||
Abstract API allows to define custom curves. All arithmetics is done with JS
|
||||
bigints over finite fields, which is defined from `modular` sub-module. For
|
||||
scalar multiplication, we use
|
||||
[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/).
|
||||
Precomputes are enabled for weierstrass and edwards BASE points of a curve. You
|
||||
could precompute any other point (e.g. for ECDH) using `utils.precompute()`
|
||||
method: check out examples.
|
||||
|
||||
### weierstrass: Short Weierstrass curve
|
||||
|
||||
```ts
|
||||
import { weierstrass } from '@noble/curves/abstract/weierstrass';
|
||||
import { Field } from '@noble/curves/abstract/modular';
|
||||
import { sha256 } from '@noble/hashes/sha256';
|
||||
import { hmac } from '@noble/hashes/hmac';
|
||||
import { concatBytes, randomBytes } from '@noble/hashes/utils';
|
||||
|
||||
const hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) =>
|
||||
hmac(sha256, key, concatBytes(...msgs));
|
||||
|
||||
// secQ (not secP) - secq256k1 is a cycle of secp256k1 with Fp/N flipped.
|
||||
// https://personaelabs.org/posts/spartan-ecdsa
|
||||
// https://zcash.github.io/halo2/background/curves.html#cycles-of-curves
|
||||
const secq256k1 = weierstrass({
|
||||
a: 0n,
|
||||
b: 7n,
|
||||
Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n),
|
||||
n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n,
|
||||
Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n,
|
||||
Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n,
|
||||
hash: sha256,
|
||||
hmac: hmacSha256,
|
||||
randomBytes,
|
||||
});
|
||||
|
||||
// NIST secp192r1 aka p192
|
||||
// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/secg/secp192r1
|
||||
const secp192r1 = weierstrass({
|
||||
a: 0xfffffffffffffffffffffffffffffffefffffffffffffffcn,
|
||||
b: 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1n,
|
||||
Fp: Field(0xfffffffffffffffffffffffffffffffeffffffffffffffffn),
|
||||
n: 0xffffffffffffffffffffffff99def836146bc9b1b4d22831n,
|
||||
Gx: 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012n,
|
||||
Gy: 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811n,
|
||||
hash: sha256,
|
||||
hmac: hmacSha256,
|
||||
randomBytes,
|
||||
});
|
||||
```
|
||||
|
||||
Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass`
|
||||
expects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h`
|
||||
and coordinates `Gx`, `Gy` of generator point.
|
||||
`hmac` and `hash` must be specified for deterministic `k` generation.
|
||||
|
||||
**Weierstrass points:**
|
||||
|
||||
- Are exported as `ProjectivePoint`
|
||||
- Are represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
|
||||
- Use complete exception-free formulas for addition and doubling
|
||||
- Can be decoded/encoded from/to Uint8Array / hex strings using
|
||||
`ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()`
|
||||
- Have `assertValidity()` which checks for being on-curve
|
||||
- Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates
|
||||
|
||||
**ECDSA signatures:**
|
||||
|
||||
- Are represented by `Signature` instances with `r, s` and optional `recovery` properties
|
||||
- Have `recoverPublicKey()`, `toCompactRawBytes()` and `toDERRawBytes()` methods
|
||||
- Can be prehashed, or non-prehashed:
|
||||
- `sign(msgHash, privKey)` (default, prehash: false) - you did hashing before
|
||||
- `sign(msg, privKey, {prehash: true})` - curves will do hashing for you
|
||||
- Are generated deterministically, following [RFC6979](https://www.rfc-editor.org/rfc/rfc6979).
|
||||
- Consider [hedged ECDSA with noise](#hedged-ecdsa-with-noise) for adding randomness into
|
||||
for signatures, to get improved security against fault attacks.
|
||||
|
||||
More examples:
|
||||
|
||||
```typescript
|
||||
// All curves expose same generic interface.
|
||||
const priv = secq256k1.utils.randomPrivateKey();
|
||||
secq256k1.getPublicKey(priv); // Convert private key to public.
|
||||
const sig = secq256k1.sign(msg, priv); // Sign msg with private key.
|
||||
const sig2 = secq256k1.sign(msg, priv, { prehash: true }); // hash(msg)
|
||||
secq256k1.verify(sig, msg, priv); // Verify if sig is correct.
|
||||
|
||||
// Default behavior is "try DER, then try compact if fails". Can be explicit:
|
||||
secq256k1.verify(sig.toCompactHex(), msg, priv, { format: 'compact' });
|
||||
|
||||
const Point = secq256k1.ProjectivePoint;
|
||||
const point = Point.BASE; // Elliptic curve Point class and BASE point static var.
|
||||
point.add(point).equals(point.double()); // add(), equals(), double() methods
|
||||
point.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var
|
||||
point.negate(); // Flips point over x/y coordinate.
|
||||
point.multiply(31415n); // Multiplication of Point by scalar.
|
||||
|
||||
point.assertValidity(); // Checks for being on-curve
|
||||
point.toAffine(); // Converts to 2d affine xy coordinates
|
||||
|
||||
secq256k1.CURVE.n;
|
||||
secq256k1.CURVE.p;
|
||||
secq256k1.CURVE.Fp.mod();
|
||||
secq256k1.CURVE.hash();
|
||||
|
||||
// precomputes
|
||||
const fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey));
|
||||
fast.multiply(privKey); // much faster ECDH now
|
||||
```
|
||||
|
||||
### edwards: Twisted Edwards curve
|
||||
|
||||
```ts
|
||||
import { twistedEdwards } from '@noble/curves/abstract/edwards';
|
||||
import { Field } from '@noble/curves/abstract/modular';
|
||||
import { sha512 } from '@noble/hashes/sha512';
|
||||
import { randomBytes } from '@noble/hashes/utils';
|
||||
|
||||
const Fp = Field(2n ** 255n - 19n);
|
||||
const ed25519 = twistedEdwards({
|
||||
a: Fp.create(-1n),
|
||||
d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p
|
||||
Fp: Fp,
|
||||
n: 2n ** 252n + 27742317777372353535851937790883648493n,
|
||||
h: 8n,
|
||||
Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n,
|
||||
Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n,
|
||||
hash: sha512,
|
||||
randomBytes,
|
||||
adjustScalarBytes(bytes) {
|
||||
// optional; but mandatory in ed25519
|
||||
bytes[0] &= 248;
|
||||
bytes[31] &= 127;
|
||||
bytes[31] |= 64;
|
||||
return bytes;
|
||||
},
|
||||
} as const);
|
||||
```
|
||||
|
||||
Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`.
|
||||
You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h`
|
||||
and coordinates `Gx`, `Gy` of generator point.
|
||||
For EdDSA signatures, `hash` param required.
|
||||
`adjustScalarBytes` which instructs how to change private scalars could be specified.
|
||||
|
||||
**Edwards points:**
|
||||
|
||||
- Are exported as `ExtendedPoint`
|
||||
- Are represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z)
|
||||
- Use complete exception-free formulas for addition and doubling
|
||||
- Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()`
|
||||
- Have `assertValidity()` which checks for being on-curve
|
||||
- Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates
|
||||
- Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions
|
||||
|
||||
**EdDSA signatures:**
|
||||
|
||||
- `zip215: true` is default behavior. It has slightly looser verification logic
|
||||
to be [consensus-friendly](https://hdevalence.ca/blog/2020-10-04-its-25519am), following [ZIP215](https://zips.z.cash/zip-0215) rules
|
||||
- `zip215: false` switches verification criteria to strict
|
||||
[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final)
|
||||
and additionally provides [non-repudiation with SBS](https://eprint.iacr.org/2020/1244),
|
||||
which is useful for:
|
||||
- Contract Signing: if A signed an agreement with B using key that allows repudiation, it can later claim that it signed a different contract
|
||||
- E-voting: malicious voters may pick keys that allow repudiation in order to deny results
|
||||
- Blockchains: transaction of amount X might also be valid for a different amount Y
|
||||
- Both modes have SUF-CMA (strong unforgeability under chosen message attacks).
|
||||
|
||||
Check out [RFC9496](https://www.rfc-editor.org/rfc/rfc9496) for description of
|
||||
ristretto and decaf groups which we implement.
|
||||
|
||||
### montgomery: Montgomery curve
|
||||
|
||||
The module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748.
|
||||
Proper Elliptic Curve Points are not implemented yet.
|
||||
|
||||
### bls: Barreto-Lynn-Scott curves
|
||||
|
||||
The module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction.
|
||||
They allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and
|
||||
use aggregated, batch-verifiable
|
||||
[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716),
|
||||
using Boneh-Lynn-Shacham signature scheme.
|
||||
|
||||
The module doesn't expose `CURVE` property: use `G1.CURVE`, `G2.CURVE` instead.
|
||||
Only BLS12-381 is currently implemented.
|
||||
Defining BLS12-377 and BLS24 should be straightforward.
|
||||
|
||||
The default BLS uses short public keys (with public keys in G1 and signatures in G2).
|
||||
Short signatures (public keys in G2 and signatures in G1) are also supported.
|
||||
|
||||
### hash-to-curve: Hashing strings to curve points
|
||||
|
||||
The module allows to hash arbitrary strings to elliptic curve points. Implements [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380).
|
||||
|
||||
Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security:
|
||||
|
||||
```ts
|
||||
import { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1';
|
||||
import { randomBytes } from '@noble/hashes/utils';
|
||||
hashToCurve('0102abcd');
|
||||
console.log(hashToCurve(randomBytes()));
|
||||
console.log(encodeToCurve(randomBytes()));
|
||||
|
||||
import { bls12_381 } from '@noble/curves/bls12-381';
|
||||
bls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' });
|
||||
bls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' });
|
||||
```
|
||||
|
||||
Low-level methods from the spec:
|
||||
|
||||
```ts
|
||||
// produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
|
||||
function expand_message_xmd(
|
||||
msg: Uint8Array,
|
||||
DST: Uint8Array,
|
||||
lenInBytes: number,
|
||||
H: CHash // For CHash see abstract/weierstrass docs section
|
||||
): Uint8Array;
|
||||
// produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
function expand_message_xof(
|
||||
msg: Uint8Array,
|
||||
DST: Uint8Array,
|
||||
lenInBytes: number,
|
||||
k: number,
|
||||
H: CHash
|
||||
): Uint8Array;
|
||||
// Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F
|
||||
function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][];
|
||||
|
||||
/**
|
||||
* * `DST` is a domain separation tag, defined in section 2.2.5
|
||||
* * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
|
||||
* * `m` is extension degree (1 for prime fields)
|
||||
* * `k` is the target security target in bits (e.g. 128), from section 5.1
|
||||
* * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
|
||||
* * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
|
||||
*/
|
||||
type UnicodeOrBytes = string | Uint8Array;
|
||||
type Opts = {
|
||||
DST: UnicodeOrBytes;
|
||||
p: bigint;
|
||||
m: number;
|
||||
k: number;
|
||||
expand?: 'xmd' | 'xof';
|
||||
hash: CHash;
|
||||
};
|
||||
```
|
||||
|
||||
### poseidon: Poseidon hash
|
||||
|
||||
Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash:
|
||||
permutation and sponge.
|
||||
|
||||
There are many poseidon variants with different constants.
|
||||
We don't provide them: you should construct them manually.
|
||||
Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
|
||||
|
||||
```ts
|
||||
import { poseidon, poseidonSponge } from '@noble/curves/abstract/poseidon';
|
||||
|
||||
const rate = 2;
|
||||
const capacity = 1;
|
||||
const { mds, roundConstants } = poseidon.grainGenConstants({
|
||||
Fp,
|
||||
t: rate + capacity,
|
||||
roundsFull: 8,
|
||||
roundsPartial: 31,
|
||||
});
|
||||
const opts = {
|
||||
Fp,
|
||||
rate,
|
||||
capacity,
|
||||
sboxPower: 17,
|
||||
mds,
|
||||
roundConstants,
|
||||
roundsFull: 8,
|
||||
roundsPartial: 31,
|
||||
};
|
||||
const permutation = poseidon.poseidon(opts);
|
||||
const sponge = poseidon.poseidonSponge(opts); // use carefully, not specced
|
||||
```
|
||||
|
||||
### modular: Modular arithmetics utilities
|
||||
|
||||
```ts
|
||||
import * as mod from '@noble/curves/abstract/modular';
|
||||
|
||||
// Finite Field utils
|
||||
const fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19
|
||||
fp.mul(591n, 932n); // multiplication
|
||||
fp.pow(481n, 11024858120n); // exponentiation
|
||||
fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17)
|
||||
fp.inv(5n); // modular inverse
|
||||
fp.sqrt(21n); // square root
|
||||
|
||||
// Non-Field generic utils are also available
|
||||
mod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10
|
||||
mod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse
|
||||
mod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion
|
||||
```
|
||||
|
||||
Field operations are not constant-time: they are using JS bigints, see [security](#security).
|
||||
The fact is mostly irrelevant, but the important method to keep in mind is `pow`,
|
||||
which may leak exponent bits, when used naïvely.
|
||||
|
||||
`mod.Field` is always **field over prime number**. Non-prime fields aren't supported for now.
|
||||
We don't test for prime-ness for speed and because algorithms are probabilistic anyway.
|
||||
Initializing a non-prime field could make your app suspectible to
|
||||
DoS (infilite loop) on Tonelli-Shanks square root calculation.
|
||||
|
||||
Unlike `mod.inv`, `mod.invertBatch` won't throw on `0`: make sure to throw an error yourself.
|
||||
|
||||
### fft: Fast Fourier Transform
|
||||
|
||||
Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
|
||||
API may change at any time. The code has not been audited. Feature requests are welcome.
|
||||
|
||||
```ts
|
||||
import * as fft from '@noble/curves/abstract/fft.js';
|
||||
```
|
||||
|
||||
#### Creating private keys from hashes
|
||||
|
||||
You can't simply make a 32-byte private key from a 32-byte hash.
|
||||
Doing so will make the key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/).
|
||||
|
||||
To make the bias negligible, we follow [FIPS 186-5 A.2](https://csrc.nist.gov/publications/detail/fips/186/5/final)
|
||||
and [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
|
||||
This means, for 32-byte key, we would need 48-byte hash to get 2^-128 bias, which matches curve security level.
|
||||
|
||||
`hashToPrivateScalar()` that hashes to **private key** was created for this purpose.
|
||||
Use [abstract/hash-to-curve](#hash-to-curve-hashing-strings-to-curve-points)
|
||||
if you need to hash to **public key**.
|
||||
|
||||
```ts
|
||||
import { p256 } from '@noble/curves/nist';
|
||||
import { sha256 } from '@noble/hashes/sha256';
|
||||
import { hkdf } from '@noble/hashes/hkdf';
|
||||
import * as mod from '@noble/curves/abstract/modular';
|
||||
const someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2)
|
||||
const derived = hkdf(sha256, someKey, undefined, 'application', 48); // 48 bytes for 32-byte priv
|
||||
const validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n);
|
||||
```
|
||||
|
||||
### utils: Useful utilities
|
||||
|
||||
```ts
|
||||
import * as utils from '@noble/curves/abstract/utils';
|
||||
|
||||
utils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));
|
||||
utils.hexToBytes('deadbeef');
|
||||
utils.numberToHexUnpadded(123n);
|
||||
utils.hexToNumber();
|
||||
|
||||
utils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));
|
||||
utils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));
|
||||
utils.numberToBytesBE(123n, 32);
|
||||
utils.numberToBytesLE(123n, 64);
|
||||
|
||||
utils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef]));
|
||||
utils.nLength(255n);
|
||||
utils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde]));
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
The library has been independently audited:
|
||||
|
||||
- at version 1.6.0, in Sep 2024, by [Cure53](https://cure53.de)
|
||||
- PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf)
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.6.0..main)
|
||||
- Scope: ed25519, ed448, their add-ons, bls12-381, bn254,
|
||||
hash-to-curve, low-level primitives bls, tower, edwards, montgomery.
|
||||
- The audit has been funded by [OpenSats](https://opensats.org)
|
||||
- at version 1.2.0, in Sep 2023, by [Kudelski Security](https://kudelskisecurity.com)
|
||||
- PDFs: [in-repo](./audit/2023-09-kudelski-audit-starknet.pdf)
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.2.0..main)
|
||||
- Scope: [scure-starknet](https://github.com/paulmillr/scure-starknet) and its related
|
||||
abstract modules of noble-curves: `curve`, `modular`, `poseidon`, `weierstrass`
|
||||
- The audit has been funded by [Starkware](https://starkware.co)
|
||||
- at version 0.7.3, in Feb 2023, by [Trail of Bits](https://www.trailofbits.com)
|
||||
- PDFs: [website](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf),
|
||||
[in-repo](./audit/2023-01-trailofbits-audit-curves.pdf)
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main)
|
||||
- Scope: abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass` and
|
||||
top-level modules `_shortw_utils` and `secp256k1`
|
||||
- The audit has been funded by [Ryan Shea](https://www.shea.io)
|
||||
|
||||
It is tested against property-based, cross-library and Wycheproof vectors,
|
||||
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
|
||||
|
||||
If you see anything unusual: investigate and report.
|
||||
|
||||
### Constant-timeness
|
||||
|
||||
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
|
||||
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
|
||||
in a scripting language. Which means _any other JS library can't have
|
||||
constant-timeness_. Even statically typed Rust, a language without GC,
|
||||
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
|
||||
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
|
||||
Use low-level libraries & languages.
|
||||
|
||||
### Supply chain security
|
||||
|
||||
- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures
|
||||
- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs
|
||||
- Use GitHub CLI to verify single-file builds:
|
||||
`gh attestation verify --owner paulmillr noble-curves.js`
|
||||
- **Rare releasing** is followed to ensure less re-audit need for end-users
|
||||
- **Dependencies** are minimized and locked-down: any dependency could get hacked and users will be downloading malware with every install.
|
||||
- We make sure to use as few dependencies as possible
|
||||
- Automatic dep updates are prevented by locking-down version ranges; diffs are checked with `npm-diff`
|
||||
- **Dev Dependencies** are disabled for end-users; they are only used to develop / build the source code
|
||||
|
||||
For this package, there is 1 dependency; and a few dev dependencies:
|
||||
|
||||
- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality
|
||||
- micro-bmark, micro-should and jsbt are used for benchmarking / testing / build tooling and developed by the same author
|
||||
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation. It's hard to audit their source code thoroughly and fully because of their size
|
||||
|
||||
### Randomness
|
||||
|
||||
We're deferring to built-in
|
||||
[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
|
||||
which is considered cryptographically secure (CSPRNG).
|
||||
|
||||
In the past, browsers had bugs that made it weak: it may happen again.
|
||||
Implementing a userspace CSPRNG to get resilient to the weakness
|
||||
is even worse: there is no reliable userspace source of quality entropy.
|
||||
|
||||
### Quantum computers
|
||||
|
||||
Cryptographically relevant quantum computer, if built, will allow to
|
||||
break elliptic curve cryptography (both ECDSA / EdDSA & ECDH) using Shor's algorithm.
|
||||
|
||||
Consider switching to newer / hybrid algorithms, such as SPHINCS+. They are available in
|
||||
[noble-post-quantum](https://github.com/paulmillr/noble-post-quantum).
|
||||
|
||||
NIST prohibits classical cryptography (RSA, DSA, ECDSA, ECDH) [after 2035](https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf). Australian ASD prohibits it [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
|
||||
|
||||
## Speed
|
||||
|
||||
```sh
|
||||
npm run bench:install && npm run bench
|
||||
```
|
||||
|
||||
During first call of most methods, `init` is done, which calculates base point precomputes.
|
||||
The method consumes 20MB+ of memory and takes some time.
|
||||
You can adjust how many precomputes are generated,
|
||||
by using `_setWindowSize`. Check out the source code.
|
||||
|
||||
Benchmark results on Apple M4:
|
||||
|
||||
```
|
||||
# secp256k1
|
||||
init 10ms
|
||||
getPublicKey x 9,099 ops/sec @ 109μs/op
|
||||
sign x 7,182 ops/sec @ 139μs/op
|
||||
verify x 1,188 ops/sec @ 841μs/op
|
||||
getSharedSecret x 735 ops/sec @ 1ms/op
|
||||
recoverPublicKey x 1,265 ops/sec @ 790μs/op
|
||||
schnorr.sign x 957 ops/sec @ 1ms/op
|
||||
schnorr.verify x 1,210 ops/sec @ 825μs/op
|
||||
|
||||
# ed25519
|
||||
init 14ms
|
||||
getPublicKey x 14,216 ops/sec @ 70μs/op
|
||||
sign x 6,849 ops/sec @ 145μs/op
|
||||
verify x 1,400 ops/sec @ 713μs/op
|
||||
|
||||
# ed448
|
||||
init 37ms
|
||||
getPublicKey x 5,273 ops/sec @ 189μs/op
|
||||
sign x 2,494 ops/sec @ 400μs/op
|
||||
verify x 476 ops/sec @ 2ms/op
|
||||
|
||||
# p256
|
||||
init 17ms
|
||||
getPublicKey x 8,977 ops/sec @ 111μs/op
|
||||
sign x 7,236 ops/sec @ 138μs/op
|
||||
verify x 877 ops/sec @ 1ms/op
|
||||
|
||||
# p384
|
||||
init 42ms
|
||||
getPublicKey x 4,084 ops/sec @ 244μs/op
|
||||
sign x 3,247 ops/sec @ 307μs/op
|
||||
verify x 331 ops/sec @ 3ms/op
|
||||
|
||||
# p521
|
||||
init 83ms
|
||||
getPublicKey x 2,049 ops/sec @ 487μs/op
|
||||
sign x 1,748 ops/sec @ 571μs/op
|
||||
verify x 170 ops/sec @ 5ms/op
|
||||
|
||||
# ristretto255
|
||||
add x 931,966 ops/sec @ 1μs/op
|
||||
multiply x 15,444 ops/sec @ 64μs/op
|
||||
encode x 21,367 ops/sec @ 46μs/op
|
||||
decode x 21,715 ops/sec @ 46μs/op
|
||||
|
||||
# decaf448
|
||||
add x 478,011 ops/sec @ 2μs/op
|
||||
multiply x 416 ops/sec @ 2ms/op
|
||||
encode x 8,562 ops/sec @ 116μs/op
|
||||
decode x 8,636 ops/sec @ 115μs/op
|
||||
|
||||
# ECDH
|
||||
x25519 x 1,981 ops/sec @ 504μs/op
|
||||
x448 x 743 ops/sec @ 1ms/op
|
||||
secp256k1 x 728 ops/sec @ 1ms/op
|
||||
p256 x 705 ops/sec @ 1ms/op
|
||||
p384 x 268 ops/sec @ 3ms/op
|
||||
p521 x 137 ops/sec @ 7ms/op
|
||||
|
||||
# hash-to-curve
|
||||
hashToPrivateScalar x 1,754,385 ops/sec @ 570ns/op
|
||||
hash_to_field x 135,703 ops/sec @ 7μs/op
|
||||
hashToCurve secp256k1 x 3,194 ops/sec @ 313μs/op
|
||||
hashToCurve p256 x 5,962 ops/sec @ 167μs/op
|
||||
hashToCurve p384 x 2,230 ops/sec @ 448μs/op
|
||||
hashToCurve p521 x 1,063 ops/sec @ 940μs/op
|
||||
hashToCurve ed25519 x 4,047 ops/sec @ 247μs/op
|
||||
hashToCurve ed448 x 1,691 ops/sec @ 591μs/op
|
||||
hash_to_ristretto255 x 8,733 ops/sec @ 114μs/op
|
||||
hash_to_decaf448 x 3,882 ops/sec @ 257μs/op
|
||||
|
||||
# modular over secp256k1 P field
|
||||
invert a x 866,551 ops/sec @ 1μs/op
|
||||
invert b x 693,962 ops/sec @ 1μs/op
|
||||
sqrt p = 3 mod 4 x 25,738 ops/sec @ 38μs/op
|
||||
sqrt tonneli-shanks x 847 ops/sec @ 1ms/op
|
||||
|
||||
# bls12-381
|
||||
init 22ms
|
||||
getPublicKey x 1,325 ops/sec @ 754μs/op
|
||||
sign x 80 ops/sec @ 12ms/op
|
||||
verify x 62 ops/sec @ 15ms/op
|
||||
pairing x 166 ops/sec @ 6ms/op
|
||||
pairing10 x 54 ops/sec @ 18ms/op ± 23.48% (15ms..36ms)
|
||||
MSM 4096 scalars x points 3286ms
|
||||
aggregatePublicKeys/8 x 173 ops/sec @ 5ms/op
|
||||
aggregatePublicKeys/32 x 46 ops/sec @ 21ms/op
|
||||
aggregatePublicKeys/128 x 11 ops/sec @ 84ms/op
|
||||
aggregatePublicKeys/512 x 2 ops/sec @ 335ms/op
|
||||
aggregatePublicKeys/2048 x 0 ops/sec @ 1346ms/op
|
||||
aggregateSignatures/8 x 82 ops/sec @ 12ms/op
|
||||
aggregateSignatures/32 x 21 ops/sec @ 45ms/op
|
||||
aggregateSignatures/128 x 5 ops/sec @ 178ms/op
|
||||
aggregateSignatures/512 x 1 ops/sec @ 705ms/op
|
||||
aggregateSignatures/2048 x 0 ops/sec @ 2823ms/op
|
||||
```
|
||||
|
||||
## Upgrading
|
||||
|
||||
Previously, the library was split into single-feature packages
|
||||
[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1),
|
||||
[noble-ed25519](https://github.com/paulmillr/noble-ed25519) and
|
||||
[noble-bls12-381](https://github.com/paulmillr/noble-bls12-381).
|
||||
|
||||
Curves continue their original work. The single-feature packages changed their
|
||||
direction towards providing minimal 4kb implementations of cryptography,
|
||||
which means they have less features.
|
||||
|
||||
Upgrading from noble-secp256k1 2.0 or noble-ed25519 2.0: no changes, libraries are compatible.
|
||||
|
||||
Upgrading from noble-secp256k1 1.7:
|
||||
|
||||
- `getPublicKey`
|
||||
- now produce 33-byte compressed signatures by default
|
||||
- to use old behavior, which produced 65-byte uncompressed keys, set
|
||||
argument `isCompressed` to `false`: `getPublicKey(priv, false)`
|
||||
- `sign`
|
||||
- is now sync
|
||||
- now returns `Signature` instance with `{ r, s, recovery }` properties
|
||||
- `canonical` option was renamed to `lowS`
|
||||
- `recovered` option has been removed because recovery bit is always returned now
|
||||
- `der` option has been removed. There are 2 options:
|
||||
1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`.
|
||||
Compact encoding is simply a concatenation of 32-byte r and 32-byte s.
|
||||
2. If you must use DER encoding, switch to noble-curves (see above).
|
||||
- `verify`
|
||||
- is now sync
|
||||
- `strict` option was renamed to `lowS`
|
||||
- `getSharedSecret`
|
||||
- now produce 33-byte compressed signatures by default
|
||||
- to use old behavior, which produced 65-byte uncompressed keys, set
|
||||
argument `isCompressed` to `false`: `getSharedSecret(a, b, false)`
|
||||
- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)`
|
||||
- `number` type for private keys have been removed: use `bigint` instead
|
||||
- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz)
|
||||
- `utils` were split into `utils` (same api as in noble-curves) and
|
||||
`etc` (`hmacSha256Sync` and others)
|
||||
|
||||
Upgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7:
|
||||
|
||||
- Methods are now sync by default
|
||||
- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs
|
||||
- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt)
|
||||
- `Signature` was removed: just use raw bytes or hex now
|
||||
- `utils` were split into `utils` (same api as in noble-curves) and
|
||||
`etc` (`sha512Sync` and others)
|
||||
- `getSharedSecret` was moved to `x25519` module
|
||||
- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods
|
||||
|
||||
Upgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381):
|
||||
|
||||
- Methods and classes were renamed:
|
||||
- PointG1 -> G1.Point, PointG2 -> G2.Point
|
||||
- PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode
|
||||
- Fp2 ORDER was corrected
|
||||
|
||||
## Contributing & testing
|
||||
|
||||
- `npm install && npm run build && npm test` will build the code and run tests.
|
||||
- `npm run lint` / `npm run format` will run linter / fix linter issues.
|
||||
- `npm run bench` will run benchmarks, which may need their deps first (`npm run bench:install`)
|
||||
- `npm run build:release` will build single file
|
||||
|
||||
Check out [github.com/paulmillr/guidelines](https://github.com/paulmillr/guidelines)
|
||||
for general coding practices and rules.
|
||||
|
||||
See [paulmillr.com/noble](https://paulmillr.com/noble/)
|
||||
for useful resources, articles, documentation and demos
|
||||
related to the library.
|
||||
|
||||
MuSig2 signature scheme and BIP324 ElligatorSwift mapping for secp256k1
|
||||
are available [in a separate package](https://github.com/paulmillr/scure-btc-signer).
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
|
||||
|
||||
See LICENSE file.
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { randomBytes } from '@noble/hashes/utils';
|
||||
import type { CHash } from './abstract/utils.ts';
|
||||
import { type CurveFn, type CurveType } from './abstract/weierstrass.ts';
|
||||
/** connects noble-curves to noble-hashes */
|
||||
export declare function getHash(hash: CHash): {
|
||||
hash: CHash;
|
||||
hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;
|
||||
randomBytes: typeof randomBytes;
|
||||
};
|
||||
/** Same API as @noble/hashes, with ability to create curve with custom hash */
|
||||
export type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;
|
||||
export type CurveFnWithCreate = CurveFn & {
|
||||
create: (hash: CHash) => CurveFn;
|
||||
};
|
||||
export declare function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate;
|
||||
//# sourceMappingURL=_shortw_utils.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_shortw_utils.d.ts","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,SAAS,EAAe,MAAM,2BAA2B,CAAC;AAEtF,4CAA4C;AAC5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,GAAG;IACpC,IAAI,EAAE,KAAK,CAAC;IACZ,IAAI,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,KAAK,UAAU,CAAC;IAC7D,WAAW,EAAE,OAAO,WAAW,CAAC;CACjC,CAMA;AACD,+EAA+E;AAC/E,MAAM,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAClF,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG;IAAE,MAAM,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,OAAO,CAAA;CAAE,CAAC;AAE/E,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,GAAG,iBAAiB,CAGjF"}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getHash = getHash;
|
||||
exports.createCurve = createCurve;
|
||||
/**
|
||||
* Utilities for short weierstrass curves, combined with noble-hashes.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const hmac_1 = require("@noble/hashes/hmac");
|
||||
const utils_1 = require("@noble/hashes/utils");
|
||||
const weierstrass_ts_1 = require("./abstract/weierstrass.js");
|
||||
/** connects noble-curves to noble-hashes */
|
||||
function getHash(hash) {
|
||||
return {
|
||||
hash,
|
||||
hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)),
|
||||
randomBytes: utils_1.randomBytes,
|
||||
};
|
||||
}
|
||||
function createCurve(curveDef, defHash) {
|
||||
const create = (hash) => (0, weierstrass_ts_1.weierstrass)({ ...curveDef, ...getHash(hash) });
|
||||
return { ...create(defHash), create };
|
||||
}
|
||||
//# sourceMappingURL=_shortw_utils.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_shortw_utils.js","sourceRoot":"","sources":["src/_shortw_utils.ts"],"names":[],"mappings":";;AAWA,0BAUC;AAKD,kCAGC;AA7BD;;;GAGG;AACH,sEAAsE;AACtE,6CAA0C;AAC1C,+CAA+D;AAE/D,8DAAsF;AAEtF,4CAA4C;AAC5C,SAAgB,OAAO,CAAC,IAAW;IAKjC,OAAO;QACL,IAAI;QACJ,IAAI,EAAE,CAAC,GAAe,EAAE,GAAG,IAAkB,EAAE,EAAE,CAAC,IAAA,WAAI,EAAC,IAAI,EAAE,GAAG,EAAE,IAAA,mBAAW,EAAC,GAAG,IAAI,CAAC,CAAC;QACvF,WAAW,EAAX,mBAAW;KACZ,CAAC;AACJ,CAAC;AAKD,SAAgB,WAAW,CAAC,QAAkB,EAAE,OAAc;IAC5D,MAAM,MAAM,GAAG,CAAC,IAAW,EAAW,EAAE,CAAC,IAAA,4BAAW,EAAC,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACxF,OAAO,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;AACxC,CAAC"}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* BLS (Barreto-Lynn-Scott) family of pairing-friendly curves.
|
||||
* BLS != BLS.
|
||||
* The file implements BLS (Boneh-Lynn-Shacham) signatures.
|
||||
* Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)
|
||||
* families of pairing-friendly curves.
|
||||
* Consists of two curves: G1 and G2:
|
||||
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
|
||||
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
|
||||
* - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
|
||||
* Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
|
||||
* Pairing is used to aggregate and verify signatures.
|
||||
* There are two main ways to use it:
|
||||
* 1. Fp for short private keys, Fp₂ for signatures
|
||||
* 2. Fp for short signatures, Fp₂ for private keys
|
||||
* @module
|
||||
**/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type htfBasicOpts, type Opts as HTFOpts, type MapToCurve, createHasher } from './hash-to-curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
import type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6 } from './tower.ts';
|
||||
import { type CHash, type Hex, type PrivKey } from './utils.ts';
|
||||
import { type CurvePointsRes, type CurvePointsType, type ProjPointType } from './weierstrass.ts';
|
||||
type Fp = bigint;
|
||||
export type TwistType = 'multiplicative' | 'divisive';
|
||||
export type ShortSignatureCoder<Fp> = {
|
||||
fromHex(hex: Hex): ProjPointType<Fp>;
|
||||
toRawBytes(point: ProjPointType<Fp>): Uint8Array;
|
||||
toHex(point: ProjPointType<Fp>): string;
|
||||
};
|
||||
export type SignatureCoder<Fp> = {
|
||||
fromHex(hex: Hex): ProjPointType<Fp>;
|
||||
toRawBytes(point: ProjPointType<Fp>): Uint8Array;
|
||||
toHex(point: ProjPointType<Fp>): string;
|
||||
};
|
||||
export type PostPrecomputePointAddFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => {
|
||||
Rx: Fp2;
|
||||
Ry: Fp2;
|
||||
Rz: Fp2;
|
||||
};
|
||||
export type PostPrecomputeFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2, pointAdd: PostPrecomputePointAddFn) => void;
|
||||
export type CurveType = {
|
||||
G1: Omit<CurvePointsType<Fp>, 'n'> & {
|
||||
ShortSignature: SignatureCoder<Fp>;
|
||||
mapToCurve: MapToCurve<Fp>;
|
||||
htfDefaults: HTFOpts;
|
||||
};
|
||||
G2: Omit<CurvePointsType<Fp2>, 'n'> & {
|
||||
Signature: SignatureCoder<Fp2>;
|
||||
mapToCurve: MapToCurve<Fp2>;
|
||||
htfDefaults: HTFOpts;
|
||||
};
|
||||
fields: {
|
||||
Fp: IField<Fp>;
|
||||
Fr: IField<bigint>;
|
||||
Fp2: Fp2Bls;
|
||||
Fp6: IField<Fp6>;
|
||||
Fp12: Fp12Bls;
|
||||
};
|
||||
params: {
|
||||
ateLoopSize: bigint;
|
||||
xNegative: boolean;
|
||||
r: bigint;
|
||||
twistType: TwistType;
|
||||
};
|
||||
htfDefaults: HTFOpts;
|
||||
hash: CHash;
|
||||
randomBytes: (bytesLength?: number) => Uint8Array;
|
||||
postPrecompute?: PostPrecomputeFn;
|
||||
};
|
||||
type PrecomputeSingle = [Fp2, Fp2, Fp2][];
|
||||
type Precompute = PrecomputeSingle[];
|
||||
export type CurveFn = {
|
||||
getPublicKey: (privateKey: PrivKey) => Uint8Array;
|
||||
getPublicKeyForShortSignatures: (privateKey: PrivKey) => Uint8Array;
|
||||
sign: {
|
||||
(message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array;
|
||||
(message: ProjPointType<Fp2>, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType<Fp2>;
|
||||
};
|
||||
signShortSignature: {
|
||||
(message: Hex, privateKey: PrivKey, htfOpts?: htfBasicOpts): Uint8Array;
|
||||
(message: ProjPointType<Fp>, privateKey: PrivKey, htfOpts?: htfBasicOpts): ProjPointType<Fp>;
|
||||
};
|
||||
verify: (signature: Hex | ProjPointType<Fp2>, message: Hex | ProjPointType<Fp2>, publicKey: Hex | ProjPointType<Fp>, htfOpts?: htfBasicOpts) => boolean;
|
||||
verifyShortSignature: (signature: Hex | ProjPointType<Fp>, message: Hex | ProjPointType<Fp>, publicKey: Hex | ProjPointType<Fp2>, htfOpts?: htfBasicOpts) => boolean;
|
||||
verifyBatch: (signature: Hex | ProjPointType<Fp2>, messages: (Hex | ProjPointType<Fp2>)[], publicKeys: (Hex | ProjPointType<Fp>)[], htfOpts?: htfBasicOpts) => boolean;
|
||||
aggregatePublicKeys: {
|
||||
(publicKeys: Hex[]): Uint8Array;
|
||||
(publicKeys: ProjPointType<Fp>[]): ProjPointType<Fp>;
|
||||
};
|
||||
aggregateSignatures: {
|
||||
(signatures: Hex[]): Uint8Array;
|
||||
(signatures: ProjPointType<Fp2>[]): ProjPointType<Fp2>;
|
||||
};
|
||||
aggregateShortSignatures: {
|
||||
(signatures: Hex[]): Uint8Array;
|
||||
(signatures: ProjPointType<Fp>[]): ProjPointType<Fp>;
|
||||
};
|
||||
millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12;
|
||||
pairing: (P: ProjPointType<Fp>, Q: ProjPointType<Fp2>, withFinalExponent?: boolean) => Fp12;
|
||||
pairingBatch: (pairs: {
|
||||
g1: ProjPointType<Fp>;
|
||||
g2: ProjPointType<Fp2>;
|
||||
}[], withFinalExponent?: boolean) => Fp12;
|
||||
G1: CurvePointsRes<Fp> & ReturnType<typeof createHasher<Fp>>;
|
||||
G2: CurvePointsRes<Fp2> & ReturnType<typeof createHasher<Fp2>>;
|
||||
Signature: SignatureCoder<Fp2>;
|
||||
ShortSignature: ShortSignatureCoder<Fp>;
|
||||
params: {
|
||||
ateLoopSize: bigint;
|
||||
r: bigint;
|
||||
G1b: bigint;
|
||||
G2b: Fp2;
|
||||
};
|
||||
fields: {
|
||||
Fp: IField<Fp>;
|
||||
Fp2: Fp2Bls;
|
||||
Fp6: IField<Fp6>;
|
||||
Fp12: Fp12Bls;
|
||||
Fr: IField<bigint>;
|
||||
};
|
||||
utils: {
|
||||
randomPrivateKey: () => Uint8Array;
|
||||
calcPairingPrecomputes: (p: ProjPointType<Fp2>) => Precompute;
|
||||
};
|
||||
};
|
||||
export declare function bls(CURVE: CurveType): CurveFn;
|
||||
export {};
|
||||
//# sourceMappingURL=bls.d.ts.map
|
||||
+1
File diff suppressed because one or more lines are too long
+355
@@ -0,0 +1,355 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.bls = bls;
|
||||
/**
|
||||
* BLS (Barreto-Lynn-Scott) family of pairing-friendly curves.
|
||||
* BLS != BLS.
|
||||
* The file implements BLS (Boneh-Lynn-Shacham) signatures.
|
||||
* Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)
|
||||
* families of pairing-friendly curves.
|
||||
* Consists of two curves: G1 and G2:
|
||||
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
|
||||
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
|
||||
* - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
|
||||
* Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
|
||||
* Pairing is used to aggregate and verify signatures.
|
||||
* There are two main ways to use it:
|
||||
* 1. Fp for short private keys, Fp₂ for signatures
|
||||
* 2. Fp for short signatures, Fp₂ for private keys
|
||||
* @module
|
||||
**/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
// TODO: import { AffinePoint } from './curve.ts';
|
||||
const hash_to_curve_ts_1 = require("./hash-to-curve.js");
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
const weierstrass_ts_1 = require("./weierstrass.js");
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
|
||||
// Not used with BLS12-381 (no sequential `11` in X). Useful for other curves.
|
||||
function NAfDecomposition(a) {
|
||||
const res = [];
|
||||
// a>1 because of marker bit
|
||||
for (; a > _1n; a >>= _1n) {
|
||||
if ((a & _1n) === _0n)
|
||||
res.unshift(0);
|
||||
else if ((a & _3n) === _3n) {
|
||||
res.unshift(-1);
|
||||
a += _1n;
|
||||
}
|
||||
else
|
||||
res.unshift(1);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function bls(CURVE) {
|
||||
// Fields are specific for curve, so for now we'll need to pass them with opts
|
||||
const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;
|
||||
const BLS_X_IS_NEGATIVE = CURVE.params.xNegative;
|
||||
const TWIST = CURVE.params.twistType;
|
||||
// Point on G1 curve: (x, y)
|
||||
const G1_ = (0, weierstrass_ts_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 });
|
||||
const G1 = Object.assign(G1_, (0, hash_to_curve_ts_1.createHasher)(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
|
||||
...CURVE.htfDefaults,
|
||||
...CURVE.G1.htfDefaults,
|
||||
}));
|
||||
// Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
|
||||
const G2_ = (0, weierstrass_ts_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 });
|
||||
const G2 = Object.assign(G2_, (0, hash_to_curve_ts_1.createHasher)(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {
|
||||
...CURVE.htfDefaults,
|
||||
...CURVE.G2.htfDefaults,
|
||||
}));
|
||||
// Applies sparse multiplication as line function
|
||||
let lineFunction;
|
||||
if (TWIST === 'multiplicative') {
|
||||
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
|
||||
}
|
||||
else if (TWIST === 'divisive') {
|
||||
// NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of
|
||||
// precompute calculations.
|
||||
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
|
||||
}
|
||||
else
|
||||
throw new Error('bls: unknown twist type');
|
||||
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));
|
||||
function pointDouble(ell, Rx, Ry, Rz) {
|
||||
const t0 = Fp2.sqr(Ry); // Ry²
|
||||
const t1 = Fp2.sqr(Rz); // Rz²
|
||||
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B
|
||||
const t3 = Fp2.mul(t2, _3n); // 3 * T2
|
||||
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0
|
||||
const c0 = Fp2.sub(t2, t0); // T2 - T0 (i)
|
||||
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx²
|
||||
const c2 = Fp2.neg(t4); // -T4 (-h)
|
||||
ell.push([c0, c1, c2]);
|
||||
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2
|
||||
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2²
|
||||
Rz = Fp2.mul(t0, t4); // T0 * T4
|
||||
return { Rx, Ry, Rz };
|
||||
}
|
||||
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
|
||||
// Addition
|
||||
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz
|
||||
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz
|
||||
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy
|
||||
const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry
|
||||
const c2 = t1; // == Rx - Qx * Rz
|
||||
ell.push([c0, c1, c2]);
|
||||
const t2 = Fp2.sqr(t1); // T1²
|
||||
const t3 = Fp2.mul(t2, t1); // T2 * T1
|
||||
const t4 = Fp2.mul(t2, Rx); // T2 * Rx
|
||||
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz
|
||||
Rx = Fp2.mul(t1, t5); // T1 * T5
|
||||
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry
|
||||
Rz = Fp2.mul(Rz, t3); // Rz * T3
|
||||
return { Rx, Ry, Rz };
|
||||
}
|
||||
// Pre-compute coefficients for sparse multiplication
|
||||
// Point addition and point double calculations is reused for coefficients
|
||||
// pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine
|
||||
// add + double in windowed precomputes here, otherwise it would be single op (since X is static)
|
||||
const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize);
|
||||
const calcPairingPrecomputes = (0, utils_ts_1.memoized)((point) => {
|
||||
const p = point;
|
||||
const { x, y } = p.toAffine();
|
||||
// prettier-ignore
|
||||
const Qx = x, Qy = y, negQy = Fp2.neg(y);
|
||||
// prettier-ignore
|
||||
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
|
||||
const ell = [];
|
||||
for (const bit of ATE_NAF) {
|
||||
const cur = [];
|
||||
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
|
||||
if (bit)
|
||||
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
|
||||
ell.push(cur);
|
||||
}
|
||||
if (CURVE.postPrecompute) {
|
||||
const last = ell[ell.length - 1];
|
||||
CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
|
||||
}
|
||||
return ell;
|
||||
});
|
||||
function millerLoopBatch(pairs, withFinalExponent = false) {
|
||||
let f12 = Fp12.ONE;
|
||||
if (pairs.length) {
|
||||
const ellLen = pairs[0][0].length;
|
||||
for (let i = 0; i < ellLen; i++) {
|
||||
f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings
|
||||
// NOTE: we apply multiple pairings in parallel here
|
||||
for (const [ell, Px, Py] of pairs) {
|
||||
for (const [c0, c1, c2] of ell[i])
|
||||
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (BLS_X_IS_NEGATIVE)
|
||||
f12 = Fp12.conjugate(f12);
|
||||
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
|
||||
}
|
||||
// Calculates product of multiple pairings
|
||||
// This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))`
|
||||
function pairingBatch(pairs, withFinalExponent = true) {
|
||||
const res = [];
|
||||
// Cache precomputed toAffine for all points
|
||||
G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1));
|
||||
G2.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2));
|
||||
for (const { g1, g2 } of pairs) {
|
||||
if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G2.ProjectivePoint.ZERO))
|
||||
throw new Error('pairing is not available for ZERO point');
|
||||
// This uses toAffine inside
|
||||
g1.assertValidity();
|
||||
g2.assertValidity();
|
||||
const Qa = g1.toAffine();
|
||||
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
|
||||
}
|
||||
return millerLoopBatch(res, withFinalExponent);
|
||||
}
|
||||
// Calculates bilinear pairing
|
||||
function pairing(Q, P, withFinalExponent = true) {
|
||||
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
|
||||
}
|
||||
const utils = {
|
||||
randomPrivateKey: () => {
|
||||
const length = (0, modular_ts_1.getMinHashLength)(Fr.ORDER);
|
||||
return (0, modular_ts_1.mapHashToField)(CURVE.randomBytes(length), Fr.ORDER);
|
||||
},
|
||||
calcPairingPrecomputes,
|
||||
};
|
||||
const { ShortSignature } = CURVE.G1;
|
||||
const { Signature } = CURVE.G2;
|
||||
function normP1(point) {
|
||||
return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);
|
||||
}
|
||||
function normP1Hash(point, htfOpts) {
|
||||
return point instanceof G1.ProjectivePoint
|
||||
? point
|
||||
: G1.hashToCurve((0, utils_ts_1.ensureBytes)('point', point), htfOpts);
|
||||
}
|
||||
function normP2(point) {
|
||||
return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point);
|
||||
}
|
||||
function normP2Hash(point, htfOpts) {
|
||||
return point instanceof G2.ProjectivePoint
|
||||
? point
|
||||
: G2.hashToCurve((0, utils_ts_1.ensureBytes)('point', point), htfOpts);
|
||||
}
|
||||
// Multiplies generator (G1) by private key.
|
||||
// P = pk x G
|
||||
function getPublicKey(privateKey) {
|
||||
return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
|
||||
}
|
||||
// Multiplies generator (G2) by private key.
|
||||
// P = pk x G
|
||||
function getPublicKeyForShortSignatures(privateKey) {
|
||||
return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
|
||||
}
|
||||
function sign(message, privateKey, htfOpts) {
|
||||
const msgPoint = normP2Hash(message, htfOpts);
|
||||
msgPoint.assertValidity();
|
||||
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
|
||||
if (message instanceof G2.ProjectivePoint)
|
||||
return sigPoint;
|
||||
return Signature.toRawBytes(sigPoint);
|
||||
}
|
||||
function signShortSignature(message, privateKey, htfOpts) {
|
||||
const msgPoint = normP1Hash(message, htfOpts);
|
||||
msgPoint.assertValidity();
|
||||
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
|
||||
if (message instanceof G1.ProjectivePoint)
|
||||
return sigPoint;
|
||||
return ShortSignature.toRawBytes(sigPoint);
|
||||
}
|
||||
// Checks if pairing of public key & hash is equal to pairing of generator & signature.
|
||||
// e(P, H(m)) == e(G, S)
|
||||
function verify(signature, message, publicKey, htfOpts) {
|
||||
const P = normP1(publicKey);
|
||||
const Hm = normP2Hash(message, htfOpts);
|
||||
const G = G1.ProjectivePoint.BASE;
|
||||
const S = normP2(signature);
|
||||
const exp = pairingBatch([
|
||||
{ g1: P.negate(), g2: Hm }, // ePHM = pairing(P.negate(), Hm, false);
|
||||
{ g1: G, g2: S }, // eGS = pairing(G, S, false);
|
||||
]);
|
||||
return Fp12.eql(exp, Fp12.ONE);
|
||||
}
|
||||
// Checks if pairing of public key & hash is equal to pairing of generator & signature.
|
||||
// e(S, G) == e(H(m), P)
|
||||
function verifyShortSignature(signature, message, publicKey, htfOpts) {
|
||||
const P = normP2(publicKey);
|
||||
const Hm = normP1Hash(message, htfOpts);
|
||||
const G = G2.ProjectivePoint.BASE;
|
||||
const S = normP1(signature);
|
||||
const exp = pairingBatch([
|
||||
{ g1: Hm, g2: P }, // eHmP = pairing(Hm, P, false);
|
||||
{ g1: S, g2: G.negate() }, // eSG = pairing(S, G.negate(), false);
|
||||
]);
|
||||
return Fp12.eql(exp, Fp12.ONE);
|
||||
}
|
||||
function aNonEmpty(arr) {
|
||||
if (!Array.isArray(arr) || arr.length === 0)
|
||||
throw new Error('expected non-empty array');
|
||||
}
|
||||
function aggregatePublicKeys(publicKeys) {
|
||||
aNonEmpty(publicKeys);
|
||||
const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
|
||||
const aggAffine = agg; //.toAffine();
|
||||
if (publicKeys[0] instanceof G1.ProjectivePoint) {
|
||||
aggAffine.assertValidity();
|
||||
return aggAffine;
|
||||
}
|
||||
// toRawBytes ensures point validity
|
||||
return aggAffine.toRawBytes(true);
|
||||
}
|
||||
function aggregateSignatures(signatures) {
|
||||
aNonEmpty(signatures);
|
||||
const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO);
|
||||
const aggAffine = agg; //.toAffine();
|
||||
if (signatures[0] instanceof G2.ProjectivePoint) {
|
||||
aggAffine.assertValidity();
|
||||
return aggAffine;
|
||||
}
|
||||
return Signature.toRawBytes(aggAffine);
|
||||
}
|
||||
function aggregateShortSignatures(signatures) {
|
||||
aNonEmpty(signatures);
|
||||
const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);
|
||||
const aggAffine = agg; //.toAffine();
|
||||
if (signatures[0] instanceof G1.ProjectivePoint) {
|
||||
aggAffine.assertValidity();
|
||||
return aggAffine;
|
||||
}
|
||||
return ShortSignature.toRawBytes(aggAffine);
|
||||
}
|
||||
// https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
|
||||
// e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
|
||||
function verifyBatch(signature,
|
||||
// TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?
|
||||
messages, publicKeys, htfOpts) {
|
||||
aNonEmpty(messages);
|
||||
if (publicKeys.length !== messages.length)
|
||||
throw new Error('amount of public keys and messages should be equal');
|
||||
const sig = normP2(signature);
|
||||
const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
|
||||
const nPublicKeys = publicKeys.map(normP1);
|
||||
// NOTE: this works only for exact same object
|
||||
const messagePubKeyMap = new Map();
|
||||
for (let i = 0; i < nPublicKeys.length; i++) {
|
||||
const pub = nPublicKeys[i];
|
||||
const msg = nMessages[i];
|
||||
let keys = messagePubKeyMap.get(msg);
|
||||
if (keys === undefined) {
|
||||
keys = [];
|
||||
messagePubKeyMap.set(msg, keys);
|
||||
}
|
||||
keys.push(pub);
|
||||
}
|
||||
const paired = [];
|
||||
try {
|
||||
for (const [msg, keys] of messagePubKeyMap) {
|
||||
const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg));
|
||||
paired.push({ g1: groupPublicKey, g2: msg });
|
||||
}
|
||||
paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig });
|
||||
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
G1.ProjectivePoint.BASE._setWindowSize(4);
|
||||
return {
|
||||
getPublicKey,
|
||||
getPublicKeyForShortSignatures,
|
||||
sign,
|
||||
signShortSignature,
|
||||
verify,
|
||||
verifyBatch,
|
||||
verifyShortSignature,
|
||||
aggregatePublicKeys,
|
||||
aggregateSignatures,
|
||||
aggregateShortSignatures,
|
||||
millerLoopBatch,
|
||||
pairing,
|
||||
pairingBatch,
|
||||
G1,
|
||||
G2,
|
||||
Signature,
|
||||
ShortSignature,
|
||||
fields: {
|
||||
Fr,
|
||||
Fp,
|
||||
Fp2,
|
||||
Fp6,
|
||||
Fp12,
|
||||
},
|
||||
params: {
|
||||
ateLoopSize: CURVE.params.ateLoopSize,
|
||||
r: CURVE.params.r,
|
||||
G1b: CURVE.G1.b,
|
||||
G2b: CURVE.G2.b,
|
||||
},
|
||||
utils,
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=bls.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+109
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Methods for elliptic curve multiplication by scalars.
|
||||
* Contains wNAF, pippenger
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type IField } from './modular.ts';
|
||||
export type AffinePoint<T> = {
|
||||
x: T;
|
||||
y: T;
|
||||
} & {
|
||||
z?: never;
|
||||
t?: never;
|
||||
};
|
||||
export interface Group<T extends Group<T>> {
|
||||
double(): T;
|
||||
negate(): T;
|
||||
add(other: T): T;
|
||||
subtract(other: T): T;
|
||||
equals(other: T): boolean;
|
||||
multiply(scalar: bigint): T;
|
||||
}
|
||||
export type GroupConstructor<T> = {
|
||||
BASE: T;
|
||||
ZERO: T;
|
||||
};
|
||||
export type Mapper<T> = (i: T[]) => T[];
|
||||
/** Internal wNAF opts for specific W and scalarBits */
|
||||
export type WOpts = {
|
||||
windows: number;
|
||||
windowSize: number;
|
||||
mask: bigint;
|
||||
maxNumber: number;
|
||||
shiftBy: bigint;
|
||||
};
|
||||
export type IWNAF<T extends Group<T>> = {
|
||||
constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;
|
||||
hasPrecomputes(elm: T): boolean;
|
||||
unsafeLadder(elm: T, n: bigint, p?: T): T;
|
||||
precomputeWindow(elm: T, W: number): Group<T>[];
|
||||
getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];
|
||||
wNAF(W: number, precomputes: T[], n: bigint): {
|
||||
p: T;
|
||||
f: T;
|
||||
};
|
||||
wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;
|
||||
wNAFCached(P: T, n: bigint, transform: Mapper<T>): {
|
||||
p: T;
|
||||
f: T;
|
||||
};
|
||||
wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;
|
||||
setWindowSize(P: T, W: number): void;
|
||||
};
|
||||
/**
|
||||
* Elliptic curve multiplication of Point by scalar. Fragile.
|
||||
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
||||
* Creates precomputation tables for fast multiplication:
|
||||
* - private scalar is split by fixed size windows of W bits
|
||||
* - every window point is collected from window's table & added to accumulator
|
||||
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
||||
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
||||
* - +1 window is neccessary for wNAF
|
||||
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
||||
*
|
||||
* @todo Research returning 2d JS array of windows, instead of a single window.
|
||||
* This would allow windows to be in different memory locations
|
||||
*/
|
||||
export declare function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T>;
|
||||
/**
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
||||
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
||||
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @param scalars array of L scalars (aka private keys / bigints)
|
||||
*/
|
||||
export declare function pippenger<T extends Group<T>>(c: GroupConstructor<T>, fieldN: IField<bigint>, points: T[], scalars: bigint[]): T;
|
||||
/**
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @returns function which multiplies points with scaars
|
||||
*/
|
||||
export declare function precomputeMSMUnsafe<T extends Group<T>>(c: GroupConstructor<T>, fieldN: IField<bigint>, points: T[], windowSize: number): (scalars: bigint[]) => T;
|
||||
/**
|
||||
* Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.
|
||||
* Though generator can be different (Fp2 / Fp6 for BLS).
|
||||
*/
|
||||
export type BasicCurve<T> = {
|
||||
Fp: IField<T>;
|
||||
n: bigint;
|
||||
nBitLength?: number;
|
||||
nByteLength?: number;
|
||||
h: bigint;
|
||||
hEff?: bigint;
|
||||
Gx: T;
|
||||
Gy: T;
|
||||
allowInfinityPoint?: boolean;
|
||||
};
|
||||
export declare function validateBasic<FP, T>(curve: BasicCurve<FP> & T): Readonly<{
|
||||
readonly nBitLength: number;
|
||||
readonly nByteLength: number;
|
||||
} & BasicCurve<FP> & T & {
|
||||
p: bigint;
|
||||
}>;
|
||||
//# sourceMappingURL=curve.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"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"}
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.wNAF = wNAF;
|
||||
exports.pippenger = pippenger;
|
||||
exports.precomputeMSMUnsafe = precomputeMSMUnsafe;
|
||||
exports.validateBasic = validateBasic;
|
||||
/**
|
||||
* Methods for elliptic curve multiplication by scalars.
|
||||
* Contains wNAF, pippenger
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
function constTimeNegate(condition, item) {
|
||||
const neg = item.negate();
|
||||
return condition ? neg : item;
|
||||
}
|
||||
function validateW(W, bits) {
|
||||
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
||||
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
||||
}
|
||||
function calcWOpts(W, scalarBits) {
|
||||
validateW(W, scalarBits);
|
||||
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
||||
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
||||
const maxNumber = 2 ** W; // W=8 256
|
||||
const mask = (0, utils_ts_1.bitMask)(W); // W=8 255 == mask 0b11111111
|
||||
const shiftBy = BigInt(W); // W=8 8
|
||||
return { windows, windowSize, mask, maxNumber, shiftBy };
|
||||
}
|
||||
function calcOffsets(n, window, wOpts) {
|
||||
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
||||
let wbits = Number(n & mask); // extract W bits.
|
||||
let nextN = n >> shiftBy; // shift number by W bits.
|
||||
// What actually happens here:
|
||||
// const highestBit = Number(mask ^ (mask >> 1n));
|
||||
// let wbits2 = wbits - 1; // skip zero
|
||||
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
||||
// split if bits > max: +224 => 256-32
|
||||
if (wbits > windowSize) {
|
||||
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
||||
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
||||
nextN += _1n; // +256 (carry)
|
||||
}
|
||||
const offsetStart = window * windowSize;
|
||||
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
|
||||
const isZero = wbits === 0; // is current window slice a 0?
|
||||
const isNeg = wbits < 0; // is current window slice negative?
|
||||
const isNegF = window % 2 !== 0; // fake random statement for noise
|
||||
const offsetF = offsetStart; // fake offset for noise
|
||||
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
||||
}
|
||||
function validateMSMPoints(points, c) {
|
||||
if (!Array.isArray(points))
|
||||
throw new Error('array expected');
|
||||
points.forEach((p, i) => {
|
||||
if (!(p instanceof c))
|
||||
throw new Error('invalid point at index ' + i);
|
||||
});
|
||||
}
|
||||
function validateMSMScalars(scalars, field) {
|
||||
if (!Array.isArray(scalars))
|
||||
throw new Error('array of scalars expected');
|
||||
scalars.forEach((s, i) => {
|
||||
if (!field.isValid(s))
|
||||
throw new Error('invalid scalar at index ' + i);
|
||||
});
|
||||
}
|
||||
// Since points in different groups cannot be equal (different object constructor),
|
||||
// we can have single place to store precomputes.
|
||||
// Allows to make points frozen / immutable.
|
||||
const pointPrecomputes = new WeakMap();
|
||||
const pointWindowSizes = new WeakMap();
|
||||
function getW(P) {
|
||||
return pointWindowSizes.get(P) || 1;
|
||||
}
|
||||
/**
|
||||
* Elliptic curve multiplication of Point by scalar. Fragile.
|
||||
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
||||
* Creates precomputation tables for fast multiplication:
|
||||
* - private scalar is split by fixed size windows of W bits
|
||||
* - every window point is collected from window's table & added to accumulator
|
||||
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
||||
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
||||
* - +1 window is neccessary for wNAF
|
||||
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
||||
*
|
||||
* @todo Research returning 2d JS array of windows, instead of a single window.
|
||||
* This would allow windows to be in different memory locations
|
||||
*/
|
||||
function wNAF(c, bits) {
|
||||
return {
|
||||
constTimeNegate,
|
||||
hasPrecomputes(elm) {
|
||||
return getW(elm) !== 1;
|
||||
},
|
||||
// non-const time multiplication ladder
|
||||
unsafeLadder(elm, n, p = c.ZERO) {
|
||||
let d = elm;
|
||||
while (n > _0n) {
|
||||
if (n & _1n)
|
||||
p = p.add(d);
|
||||
d = d.double();
|
||||
n >>= _1n;
|
||||
}
|
||||
return p;
|
||||
},
|
||||
/**
|
||||
* Creates a wNAF precomputation window. Used for caching.
|
||||
* Default window size is set by `utils.precompute()` and is equal to 8.
|
||||
* Number of precomputed points depends on the curve size:
|
||||
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
||||
* - 𝑊 is the window size
|
||||
* - 𝑛 is the bitlength of the curve order.
|
||||
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
||||
* @param elm Point instance
|
||||
* @param W window size
|
||||
* @returns precomputed point tables flattened to a single array
|
||||
*/
|
||||
precomputeWindow(elm, W) {
|
||||
const { windows, windowSize } = calcWOpts(W, bits);
|
||||
const points = [];
|
||||
let p = elm;
|
||||
let base = p;
|
||||
for (let window = 0; window < windows; window++) {
|
||||
base = p;
|
||||
points.push(base);
|
||||
// i=1, bc we skip 0
|
||||
for (let i = 1; i < windowSize; i++) {
|
||||
base = base.add(p);
|
||||
points.push(base);
|
||||
}
|
||||
p = base.double();
|
||||
}
|
||||
return points;
|
||||
},
|
||||
/**
|
||||
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* @param W window size
|
||||
* @param precomputes precomputed tables
|
||||
* @param n scalar (we don't check here, but should be less than curve order)
|
||||
* @returns real and fake (for const-time) points
|
||||
*/
|
||||
wNAF(W, precomputes, n) {
|
||||
// Smaller version:
|
||||
// https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
||||
// TODO: check the scalar is less than group order?
|
||||
// wNAF behavior is undefined otherwise. But have to carefully remove
|
||||
// other checks before wNAF. ORDER == bits here.
|
||||
// Accumulators
|
||||
let p = c.ZERO;
|
||||
let f = c.BASE;
|
||||
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
||||
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
||||
// there is negate now: it is possible that negated element from low value
|
||||
// would be the same as high element, which will create carry into next window.
|
||||
// It's not obvious how this can fail, but still worth investigating later.
|
||||
const wo = calcWOpts(W, bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
||||
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// bits are 0: add garbage to fake point
|
||||
// Important part for const-time getPublicKey: add random "noise" point to f.
|
||||
f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
|
||||
}
|
||||
else {
|
||||
// bits are 1: add to result point
|
||||
p = p.add(constTimeNegate(isNeg, precomputes[offset]));
|
||||
}
|
||||
}
|
||||
// Return both real and fake points: JIT won't eliminate f.
|
||||
// At this point there is a way to F be infinity-point even if p is not,
|
||||
// which makes it less const-time: around 1 bigint multiply.
|
||||
return { p, f };
|
||||
},
|
||||
/**
|
||||
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* @param W window size
|
||||
* @param precomputes precomputed tables
|
||||
* @param n scalar (we don't check here, but should be less than curve order)
|
||||
* @param acc accumulator point to add result of multiplication
|
||||
* @returns point
|
||||
*/
|
||||
wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
|
||||
const wo = calcWOpts(W, bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
if (n === _0n)
|
||||
break; // Early-exit, skip 0 value
|
||||
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// Window bits are 0: skip processing.
|
||||
// Move to next window.
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
const item = precomputes[offset];
|
||||
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
getPrecomputes(W, P, transform) {
|
||||
// Calculate precomputes on a first run, reuse them after
|
||||
let comp = pointPrecomputes.get(P);
|
||||
if (!comp) {
|
||||
comp = this.precomputeWindow(P, W);
|
||||
if (W !== 1)
|
||||
pointPrecomputes.set(P, transform(comp));
|
||||
}
|
||||
return comp;
|
||||
},
|
||||
wNAFCached(P, n, transform) {
|
||||
const W = getW(P);
|
||||
return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
|
||||
},
|
||||
wNAFCachedUnsafe(P, n, transform, prev) {
|
||||
const W = getW(P);
|
||||
if (W === 1)
|
||||
return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
|
||||
return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
|
||||
},
|
||||
// We calculate precomputes for elliptic curve point multiplication
|
||||
// using windowed method. This specifies window size and
|
||||
// stores precomputed values. Usually only base point would be precomputed.
|
||||
setWindowSize(P, W) {
|
||||
validateW(W, bits);
|
||||
pointWindowSizes.set(P, W);
|
||||
pointPrecomputes.delete(P);
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
||||
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
||||
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @param scalars array of L scalars (aka private keys / bigints)
|
||||
*/
|
||||
function pippenger(c, fieldN, points, scalars) {
|
||||
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
||||
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
||||
// TODO:
|
||||
// - https://eprint.iacr.org/2024/750.pdf
|
||||
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
||||
// 0 is accepted in scalars
|
||||
validateMSMPoints(points, c);
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
const plength = points.length;
|
||||
const slength = scalars.length;
|
||||
if (plength !== slength)
|
||||
throw new Error('arrays of points and scalars must have equal length');
|
||||
// if (plength === 0) throw new Error('array must be of length >= 2');
|
||||
const zero = c.ZERO;
|
||||
const wbits = (0, utils_ts_1.bitLen)(BigInt(plength));
|
||||
let windowSize = 1; // bits
|
||||
if (wbits > 12)
|
||||
windowSize = wbits - 3;
|
||||
else if (wbits > 4)
|
||||
windowSize = wbits - 2;
|
||||
else if (wbits > 0)
|
||||
windowSize = 2;
|
||||
const MASK = (0, utils_ts_1.bitMask)(windowSize);
|
||||
const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
|
||||
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
||||
let sum = zero;
|
||||
for (let i = lastBits; i >= 0; i -= windowSize) {
|
||||
buckets.fill(zero);
|
||||
for (let j = 0; j < slength; j++) {
|
||||
const scalar = scalars[j];
|
||||
const wbits = Number((scalar >> BigInt(i)) & MASK);
|
||||
buckets[wbits] = buckets[wbits].add(points[j]);
|
||||
}
|
||||
let resI = zero; // not using this will do small speed-up, but will lose ct
|
||||
// Skip first bucket, because it is zero
|
||||
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
||||
sumI = sumI.add(buckets[j]);
|
||||
resI = resI.add(sumI);
|
||||
}
|
||||
sum = sum.add(resI);
|
||||
if (i !== 0)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
sum = sum.double();
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
/**
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @returns function which multiplies points with scaars
|
||||
*/
|
||||
function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
|
||||
/**
|
||||
* Performance Analysis of Window-based Precomputation
|
||||
*
|
||||
* Base Case (256-bit scalar, 8-bit window):
|
||||
* - Standard precomputation requires:
|
||||
* - 31 additions per scalar × 256 scalars = 7,936 ops
|
||||
* - Plus 255 summary additions = 8,191 total ops
|
||||
* Note: Summary additions can be optimized via accumulator
|
||||
*
|
||||
* Chunked Precomputation Analysis:
|
||||
* - Using 32 chunks requires:
|
||||
* - 255 additions per chunk
|
||||
* - 256 doublings
|
||||
* - Total: (255 × 32) + 256 = 8,416 ops
|
||||
*
|
||||
* Memory Usage Comparison:
|
||||
* Window Size | Standard Points | Chunked Points
|
||||
* ------------|-----------------|---------------
|
||||
* 4-bit | 520 | 15
|
||||
* 8-bit | 4,224 | 255
|
||||
* 10-bit | 13,824 | 1,023
|
||||
* 16-bit | 557,056 | 65,535
|
||||
*
|
||||
* Key Advantages:
|
||||
* 1. Enables larger window sizes due to reduced memory overhead
|
||||
* 2. More efficient for smaller scalar counts:
|
||||
* - 16 chunks: (16 × 255) + 256 = 4,336 ops
|
||||
* - ~2x faster than standard 8,191 ops
|
||||
*
|
||||
* Limitations:
|
||||
* - Not suitable for plain precomputes (requires 256 constant doublings)
|
||||
* - Performance degrades with larger scalar counts:
|
||||
* - Optimal for ~256 scalars
|
||||
* - Less efficient for 4096+ scalars (Pippenger preferred)
|
||||
*/
|
||||
validateW(windowSize, fieldN.BITS);
|
||||
validateMSMPoints(points, c);
|
||||
const zero = c.ZERO;
|
||||
const tableSize = 2 ** windowSize - 1; // table size (without zero)
|
||||
const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
|
||||
const MASK = (0, utils_ts_1.bitMask)(windowSize);
|
||||
const tables = points.map((p) => {
|
||||
const res = [];
|
||||
for (let i = 0, acc = p; i < tableSize; i++) {
|
||||
res.push(acc);
|
||||
acc = acc.add(p);
|
||||
}
|
||||
return res;
|
||||
});
|
||||
return (scalars) => {
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
if (scalars.length > points.length)
|
||||
throw new Error('array of scalars must be smaller than array of points');
|
||||
let res = zero;
|
||||
for (let i = 0; i < chunks; i++) {
|
||||
// No need to double if accumulator is still zero.
|
||||
if (res !== zero)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
res = res.double();
|
||||
const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
|
||||
for (let j = 0; j < scalars.length; j++) {
|
||||
const n = scalars[j];
|
||||
const curr = Number((n >> shiftBy) & MASK);
|
||||
if (!curr)
|
||||
continue; // skip zero scalars chunks
|
||||
res = res.add(tables[j][curr - 1]);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
function validateBasic(curve) {
|
||||
(0, modular_ts_1.validateField)(curve.Fp);
|
||||
(0, utils_ts_1.validateObject)(curve, {
|
||||
n: 'bigint',
|
||||
h: 'bigint',
|
||||
Gx: 'field',
|
||||
Gy: 'field',
|
||||
}, {
|
||||
nBitLength: 'isSafeInteger',
|
||||
nByteLength: 'isSafeInteger',
|
||||
});
|
||||
// Set defaults
|
||||
return Object.freeze({
|
||||
...(0, modular_ts_1.nLength)(curve.n, curve.nBitLength),
|
||||
...curve,
|
||||
...{ p: curve.Fp.ORDER },
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=curve.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+92
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
||||
* For design rationale of types / exports, see weierstrass module documentation.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type AffinePoint, type BasicCurve, type Group, type GroupConstructor } from './curve.ts';
|
||||
import { type FHash, type Hex } from './utils.ts';
|
||||
/** Edwards curves must declare params a & d. */
|
||||
export type CurveType = BasicCurve<bigint> & {
|
||||
a: bigint;
|
||||
d: bigint;
|
||||
hash: FHash;
|
||||
randomBytes: (bytesLength?: number) => Uint8Array;
|
||||
adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;
|
||||
domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
|
||||
uvRatio?: (u: bigint, v: bigint) => {
|
||||
isValid: boolean;
|
||||
value: bigint;
|
||||
};
|
||||
prehash?: FHash;
|
||||
mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>;
|
||||
};
|
||||
export type CurveTypeWithLength = Readonly<CurveType & {
|
||||
nByteLength: number;
|
||||
nBitLength: number;
|
||||
}>;
|
||||
declare function validateOpts(curve: CurveType): CurveTypeWithLength;
|
||||
/** Instance of Extended Point with coordinates in X, Y, Z, T. */
|
||||
export interface ExtPointType extends Group<ExtPointType> {
|
||||
readonly ex: bigint;
|
||||
readonly ey: bigint;
|
||||
readonly ez: bigint;
|
||||
readonly et: bigint;
|
||||
get x(): bigint;
|
||||
get y(): bigint;
|
||||
assertValidity(): void;
|
||||
multiply(scalar: bigint): ExtPointType;
|
||||
multiplyUnsafe(scalar: bigint): ExtPointType;
|
||||
isSmallOrder(): boolean;
|
||||
isTorsionFree(): boolean;
|
||||
clearCofactor(): ExtPointType;
|
||||
toAffine(iz?: bigint): AffinePoint<bigint>;
|
||||
toRawBytes(isCompressed?: boolean): Uint8Array;
|
||||
toHex(isCompressed?: boolean): string;
|
||||
_setWindowSize(windowSize: number): void;
|
||||
}
|
||||
/** Static methods of Extended Point with coordinates in X, Y, Z, T. */
|
||||
export interface ExtPointConstructor extends GroupConstructor<ExtPointType> {
|
||||
new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;
|
||||
fromAffine(p: AffinePoint<bigint>): ExtPointType;
|
||||
fromHex(hex: Hex): ExtPointType;
|
||||
fromPrivateKey(privateKey: Hex): ExtPointType;
|
||||
msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;
|
||||
}
|
||||
/**
|
||||
* Edwards Curve interface.
|
||||
* Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.
|
||||
*/
|
||||
export type CurveFn = {
|
||||
CURVE: ReturnType<typeof validateOpts>;
|
||||
getPublicKey: (privateKey: Hex) => Uint8Array;
|
||||
sign: (message: Hex, privateKey: Hex, options?: {
|
||||
context?: Hex;
|
||||
}) => Uint8Array;
|
||||
verify: (sig: Hex, message: Hex, publicKey: Hex, options?: {
|
||||
context?: Hex;
|
||||
zip215: boolean;
|
||||
}) => boolean;
|
||||
ExtendedPoint: ExtPointConstructor;
|
||||
utils: {
|
||||
randomPrivateKey: () => Uint8Array;
|
||||
getExtendedPublicKey: (key: Hex) => {
|
||||
head: Uint8Array;
|
||||
prefix: Uint8Array;
|
||||
scalar: bigint;
|
||||
point: ExtPointType;
|
||||
pointBytes: Uint8Array;
|
||||
};
|
||||
precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Creates Twisted Edwards curve with EdDSA signatures.
|
||||
* @example
|
||||
* import { Field } from '@noble/curves/abstract/modular';
|
||||
* // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h
|
||||
* const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })
|
||||
*/
|
||||
export declare function twistedEdwards(curveDef: CurveType): CurveFn;
|
||||
export {};
|
||||
//# sourceMappingURL=edwards.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"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"}
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.twistedEdwards = twistedEdwards;
|
||||
/**
|
||||
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
||||
* For design rationale of types / exports, see weierstrass module documentation.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
// prettier-ignore
|
||||
const curve_ts_1 = require("./curve.js");
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
// prettier-ignore
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);
|
||||
// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
|
||||
const VERIFY_DEFAULT = { zip215: true };
|
||||
function validateOpts(curve) {
|
||||
const opts = (0, curve_ts_1.validateBasic)(curve);
|
||||
(0, utils_ts_1.validateObject)(curve, {
|
||||
hash: 'function',
|
||||
a: 'bigint',
|
||||
d: 'bigint',
|
||||
randomBytes: 'function',
|
||||
}, {
|
||||
adjustScalarBytes: 'function',
|
||||
domain: 'function',
|
||||
uvRatio: 'function',
|
||||
mapToCurve: 'function',
|
||||
});
|
||||
// Set defaults
|
||||
return Object.freeze({ ...opts });
|
||||
}
|
||||
/**
|
||||
* Creates Twisted Edwards curve with EdDSA signatures.
|
||||
* @example
|
||||
* import { Field } from '@noble/curves/abstract/modular';
|
||||
* // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h
|
||||
* const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })
|
||||
*/
|
||||
function twistedEdwards(curveDef) {
|
||||
const CURVE = validateOpts(curveDef);
|
||||
const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
|
||||
// Important:
|
||||
// There are some places where Fp.BYTES is used instead of nByteLength.
|
||||
// So far, everything has been tested with curves of Fp.BYTES == nByteLength.
|
||||
// TODO: test and find curves which behave otherwise.
|
||||
const MASK = _2n << (BigInt(nByteLength * 8) - _1n);
|
||||
const modP = Fp.create; // Function overrides
|
||||
const Fn = (0, modular_ts_1.Field)(CURVE.n, CURVE.nBitLength);
|
||||
function isEdValidXY(x, y) {
|
||||
const x2 = Fp.sqr(x);
|
||||
const y2 = Fp.sqr(y);
|
||||
const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
|
||||
const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
|
||||
return Fp.eql(left, right);
|
||||
}
|
||||
// Validate whether the passed curve params are valid.
|
||||
// equation ax² + y² = 1 + dx²y² should work for generator point.
|
||||
if (!isEdValidXY(CURVE.Gx, CURVE.Gy))
|
||||
throw new Error('bad curve params: generator point');
|
||||
// sqrt(u/v)
|
||||
const uvRatio = CURVE.uvRatio ||
|
||||
((u, v) => {
|
||||
try {
|
||||
return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
|
||||
}
|
||||
catch (e) {
|
||||
return { isValid: false, value: _0n };
|
||||
}
|
||||
});
|
||||
const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
|
||||
const domain = CURVE.domain ||
|
||||
((data, ctx, phflag) => {
|
||||
(0, utils_ts_1.abool)('phflag', phflag);
|
||||
if (ctx.length || phflag)
|
||||
throw new Error('Contexts/pre-hash are not supported');
|
||||
return data;
|
||||
}); // NOOP
|
||||
// 0 <= n < MASK
|
||||
// Coordinates larger than Fp.ORDER are allowed for zip215
|
||||
function aCoordinate(title, n, banZero = false) {
|
||||
const min = banZero ? _1n : _0n;
|
||||
(0, utils_ts_1.aInRange)('coordinate ' + title, n, min, MASK);
|
||||
}
|
||||
function aextpoint(other) {
|
||||
if (!(other instanceof Point))
|
||||
throw new Error('ExtendedPoint expected');
|
||||
}
|
||||
// Converts Extended point to default (x, y) coordinates.
|
||||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||||
const toAffineMemo = (0, utils_ts_1.memoized)((p, iz) => {
|
||||
const { ex: x, ey: y, ez: z } = p;
|
||||
const is0 = p.is0();
|
||||
if (iz == null)
|
||||
iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily
|
||||
const ax = modP(x * iz);
|
||||
const ay = modP(y * iz);
|
||||
const zz = modP(z * iz);
|
||||
if (is0)
|
||||
return { x: _0n, y: _1n };
|
||||
if (zz !== _1n)
|
||||
throw new Error('invZ was invalid');
|
||||
return { x: ax, y: ay };
|
||||
});
|
||||
const assertValidMemo = (0, utils_ts_1.memoized)((p) => {
|
||||
const { a, d } = CURVE;
|
||||
if (p.is0())
|
||||
throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
|
||||
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
|
||||
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
|
||||
const { ex: X, ey: Y, ez: Z, et: T } = p;
|
||||
const X2 = modP(X * X); // X²
|
||||
const Y2 = modP(Y * Y); // Y²
|
||||
const Z2 = modP(Z * Z); // Z²
|
||||
const Z4 = modP(Z2 * Z2); // Z⁴
|
||||
const aX2 = modP(X2 * a); // aX²
|
||||
const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
|
||||
const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
|
||||
if (left !== right)
|
||||
throw new Error('bad point: equation left != right (1)');
|
||||
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
|
||||
const XY = modP(X * Y);
|
||||
const ZT = modP(Z * T);
|
||||
if (XY !== ZT)
|
||||
throw new Error('bad point: equation left != right (2)');
|
||||
return true;
|
||||
});
|
||||
// Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).
|
||||
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
|
||||
class Point {
|
||||
constructor(ex, ey, ez, et) {
|
||||
aCoordinate('x', ex);
|
||||
aCoordinate('y', ey);
|
||||
aCoordinate('z', ez, true);
|
||||
aCoordinate('t', et);
|
||||
this.ex = ex;
|
||||
this.ey = ey;
|
||||
this.ez = ez;
|
||||
this.et = et;
|
||||
Object.freeze(this);
|
||||
}
|
||||
get x() {
|
||||
return this.toAffine().x;
|
||||
}
|
||||
get y() {
|
||||
return this.toAffine().y;
|
||||
}
|
||||
static fromAffine(p) {
|
||||
if (p instanceof Point)
|
||||
throw new Error('extended point not allowed');
|
||||
const { x, y } = p || {};
|
||||
aCoordinate('x', x);
|
||||
aCoordinate('y', y);
|
||||
return new Point(x, y, _1n, modP(x * y));
|
||||
}
|
||||
static normalizeZ(points) {
|
||||
const toInv = (0, modular_ts_1.FpInvertBatch)(Fp, points.map((p) => p.ez));
|
||||
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
|
||||
}
|
||||
// Multiscalar Multiplication
|
||||
static msm(points, scalars) {
|
||||
return (0, curve_ts_1.pippenger)(Point, Fn, points, scalars);
|
||||
}
|
||||
// "Private method", don't use it directly
|
||||
_setWindowSize(windowSize) {
|
||||
wnaf.setWindowSize(this, windowSize);
|
||||
}
|
||||
// Not required for fromHex(), which always creates valid points.
|
||||
// Could be useful for fromAffine().
|
||||
assertValidity() {
|
||||
assertValidMemo(this);
|
||||
}
|
||||
// Compare one point to another.
|
||||
equals(other) {
|
||||
aextpoint(other);
|
||||
const { ex: X1, ey: Y1, ez: Z1 } = this;
|
||||
const { ex: X2, ey: Y2, ez: Z2 } = other;
|
||||
const X1Z2 = modP(X1 * Z2);
|
||||
const X2Z1 = modP(X2 * Z1);
|
||||
const Y1Z2 = modP(Y1 * Z2);
|
||||
const Y2Z1 = modP(Y2 * Z1);
|
||||
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
||||
}
|
||||
is0() {
|
||||
return this.equals(Point.ZERO);
|
||||
}
|
||||
negate() {
|
||||
// Flips point sign to a negative one (-x, y in affine coords)
|
||||
return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
|
||||
}
|
||||
// Fast algo for doubling Extended Point.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
||||
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
||||
double() {
|
||||
const { a } = CURVE;
|
||||
const { ex: X1, ey: Y1, ez: Z1 } = this;
|
||||
const A = modP(X1 * X1); // A = X12
|
||||
const B = modP(Y1 * Y1); // B = Y12
|
||||
const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
|
||||
const D = modP(a * A); // D = a*A
|
||||
const x1y1 = X1 + Y1;
|
||||
const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
|
||||
const G = D + B; // G = D+B
|
||||
const F = G - C; // F = G-C
|
||||
const H = D - B; // H = D-B
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
// Fast algo for adding 2 Extended Points.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
||||
// Cost: 9M + 1*a + 1*d + 7add.
|
||||
add(other) {
|
||||
aextpoint(other);
|
||||
const { a, d } = CURVE;
|
||||
const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
|
||||
const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
|
||||
const A = modP(X1 * X2); // A = X1*X2
|
||||
const B = modP(Y1 * Y2); // B = Y1*Y2
|
||||
const C = modP(T1 * d * T2); // C = T1*d*T2
|
||||
const D = modP(Z1 * Z2); // D = Z1*Z2
|
||||
const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
|
||||
const F = D - C; // F = D-C
|
||||
const G = D + C; // G = D+C
|
||||
const H = modP(B - a * A); // H = B-a*A
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
subtract(other) {
|
||||
return this.add(other.negate());
|
||||
}
|
||||
wNAF(n) {
|
||||
return wnaf.wNAFCached(this, n, Point.normalizeZ);
|
||||
}
|
||||
// Constant-time multiplication.
|
||||
multiply(scalar) {
|
||||
const n = scalar;
|
||||
(0, utils_ts_1.aInRange)('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L
|
||||
const { p, f } = this.wNAF(n);
|
||||
return Point.normalizeZ([p, f])[0];
|
||||
}
|
||||
// Non-constant-time multiplication. Uses double-and-add algorithm.
|
||||
// It's faster, but should only be used when you don't care about
|
||||
// an exposed private key e.g. sig verification.
|
||||
// Does NOT allow scalars higher than CURVE.n.
|
||||
// Accepts optional accumulator to merge with multiply (important for sparse scalars)
|
||||
multiplyUnsafe(scalar, acc = Point.ZERO) {
|
||||
const n = scalar;
|
||||
(0, utils_ts_1.aInRange)('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L
|
||||
if (n === _0n)
|
||||
return I;
|
||||
if (this.is0() || n === _1n)
|
||||
return this;
|
||||
return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
|
||||
}
|
||||
// Checks if point is of small order.
|
||||
// If you add something to small order point, you will have "dirty"
|
||||
// point with torsion component.
|
||||
// Multiplies point by cofactor and checks if the result is 0.
|
||||
isSmallOrder() {
|
||||
return this.multiplyUnsafe(cofactor).is0();
|
||||
}
|
||||
// Multiplies point by curve order and checks if the result is 0.
|
||||
// Returns `false` is the point is dirty.
|
||||
isTorsionFree() {
|
||||
return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
|
||||
}
|
||||
// Converts Extended point to default (x, y) coordinates.
|
||||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||||
toAffine(iz) {
|
||||
return toAffineMemo(this, iz);
|
||||
}
|
||||
clearCofactor() {
|
||||
const { h: cofactor } = CURVE;
|
||||
if (cofactor === _1n)
|
||||
return this;
|
||||
return this.multiplyUnsafe(cofactor);
|
||||
}
|
||||
// Converts hash string or Uint8Array to Point.
|
||||
// Uses algo from RFC8032 5.1.3.
|
||||
static fromHex(hex, zip215 = false) {
|
||||
const { d, a } = CURVE;
|
||||
const len = Fp.BYTES;
|
||||
hex = (0, utils_ts_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array
|
||||
(0, utils_ts_1.abool)('zip215', zip215);
|
||||
const normed = hex.slice(); // copy again, we'll manipulate it
|
||||
const lastByte = hex[len - 1]; // select last byte
|
||||
normed[len - 1] = lastByte & ~0x80; // clear last bit
|
||||
const y = (0, utils_ts_1.bytesToNumberLE)(normed);
|
||||
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
||||
// RFC8032 prohibits >= p, but ZIP215 doesn't
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
const max = zip215 ? MASK : Fp.ORDER;
|
||||
(0, utils_ts_1.aInRange)('pointHex.y', y, _0n, max);
|
||||
// Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
|
||||
// ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
|
||||
const y2 = modP(y * y); // denominator is always non-0 mod p.
|
||||
const u = modP(y2 - _1n); // u = y² - 1
|
||||
const v = modP(d * y2 - a); // v = d y² + 1.
|
||||
let { isValid, value: x } = uvRatio(u, v); // √(u/v)
|
||||
if (!isValid)
|
||||
throw new Error('Point.fromHex: invalid y coordinate');
|
||||
const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
|
||||
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
|
||||
if (!zip215 && x === _0n && isLastByteOdd)
|
||||
// if x=0 and x_0 = 1, fail
|
||||
throw new Error('Point.fromHex: x=0 and x_0=1');
|
||||
if (isLastByteOdd !== isXOdd)
|
||||
x = modP(-x); // if x_0 != x mod 2, set x = p-x
|
||||
return Point.fromAffine({ x, y });
|
||||
}
|
||||
static fromPrivateKey(privKey) {
|
||||
const { scalar } = getPrivateScalar(privKey);
|
||||
return G.multiply(scalar); // reduced one call of `toRawBytes`
|
||||
}
|
||||
toRawBytes() {
|
||||
const { x, y } = this.toAffine();
|
||||
const bytes = (0, utils_ts_1.numberToBytesLE)(y, Fp.BYTES); // each y has 2 x values (x, -y)
|
||||
bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y
|
||||
return bytes; // and use the last byte to encode sign of x
|
||||
}
|
||||
toHex() {
|
||||
return (0, utils_ts_1.bytesToHex)(this.toRawBytes()); // Same as toRawBytes, but returns string.
|
||||
}
|
||||
}
|
||||
// base / generator point
|
||||
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
|
||||
// zero / infinity / identity point
|
||||
Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
|
||||
const { BASE: G, ZERO: I } = Point;
|
||||
const wnaf = (0, curve_ts_1.wNAF)(Point, nByteLength * 8);
|
||||
function modN(a) {
|
||||
return (0, modular_ts_1.mod)(a, CURVE_ORDER);
|
||||
}
|
||||
// Little-endian SHA512 with modulo n
|
||||
function modN_LE(hash) {
|
||||
return modN((0, utils_ts_1.bytesToNumberLE)(hash));
|
||||
}
|
||||
// Get the hashed private scalar per RFC8032 5.1.5
|
||||
function getPrivateScalar(key) {
|
||||
const len = Fp.BYTES;
|
||||
key = (0, utils_ts_1.ensureBytes)('private key', key, len);
|
||||
// Hash private key with curve's hash function to produce uniformingly random input
|
||||
// Check byte lengths: ensure(64, h(ensure(32, key)))
|
||||
const hashed = (0, utils_ts_1.ensureBytes)('hashed private key', cHash(key), 2 * len);
|
||||
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
|
||||
const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
|
||||
const scalar = modN_LE(head); // The actual private scalar
|
||||
return { head, prefix, scalar };
|
||||
}
|
||||
// Convenience method that creates public key from scalar. RFC8032 5.1.5
|
||||
function getExtendedPublicKey(key) {
|
||||
const { head, prefix, scalar } = getPrivateScalar(key);
|
||||
const point = G.multiply(scalar); // Point on Edwards curve aka public key
|
||||
const pointBytes = point.toRawBytes(); // Uint8Array representation
|
||||
return { head, prefix, scalar, point, pointBytes };
|
||||
}
|
||||
// Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
|
||||
function getPublicKey(privKey) {
|
||||
return getExtendedPublicKey(privKey).pointBytes;
|
||||
}
|
||||
// int('LE', SHA512(dom2(F, C) || msgs)) mod N
|
||||
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
||||
const msg = (0, utils_ts_1.concatBytes)(...msgs);
|
||||
return modN_LE(cHash(domain(msg, (0, utils_ts_1.ensureBytes)('context', context), !!prehash)));
|
||||
}
|
||||
/** Signs message with privateKey. RFC8032 5.1.6 */
|
||||
function sign(msg, privKey, options = {}) {
|
||||
msg = (0, utils_ts_1.ensureBytes)('message', msg);
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph etc.
|
||||
const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
|
||||
const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
|
||||
const R = G.multiply(r).toRawBytes(); // R = rG
|
||||
const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
|
||||
const s = modN(r + k * scalar); // S = (r + k * s) mod L
|
||||
(0, utils_ts_1.aInRange)('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l
|
||||
const res = (0, utils_ts_1.concatBytes)(R, (0, utils_ts_1.numberToBytesLE)(s, Fp.BYTES));
|
||||
return (0, utils_ts_1.ensureBytes)('result', res, Fp.BYTES * 2); // 64-byte signature
|
||||
}
|
||||
const verifyOpts = VERIFY_DEFAULT;
|
||||
/**
|
||||
* Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
|
||||
* An extended group equation is checked.
|
||||
*/
|
||||
function verify(sig, msg, publicKey, options = verifyOpts) {
|
||||
const { context, zip215 } = options;
|
||||
const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
|
||||
sig = (0, utils_ts_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.
|
||||
msg = (0, utils_ts_1.ensureBytes)('message', msg);
|
||||
publicKey = (0, utils_ts_1.ensureBytes)('publicKey', publicKey, len);
|
||||
if (zip215 !== undefined)
|
||||
(0, utils_ts_1.abool)('zip215', zip215);
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph, etc
|
||||
const s = (0, utils_ts_1.bytesToNumberLE)(sig.slice(len, 2 * len));
|
||||
let A, R, SB;
|
||||
try {
|
||||
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
A = Point.fromHex(publicKey, zip215);
|
||||
R = Point.fromHex(sig.slice(0, len), zip215);
|
||||
SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
if (!zip215 && A.isSmallOrder())
|
||||
return false;
|
||||
const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
|
||||
const RkA = R.add(A.multiplyUnsafe(k));
|
||||
// Extended group equation
|
||||
// [8][S]B = [8]R + [8][k]A'
|
||||
return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
|
||||
}
|
||||
G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
||||
const utils = {
|
||||
getExtendedPublicKey,
|
||||
/** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */
|
||||
randomPrivateKey: () => randomBytes(Fp.BYTES),
|
||||
/**
|
||||
* We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
|
||||
* values. This slows down first getPublicKey() by milliseconds (see Speed section),
|
||||
* but allows to speed-up subsequent getPublicKey() calls up to 20x.
|
||||
* @param windowSize 2, 4, 8, 16
|
||||
*/
|
||||
precompute(windowSize = 8, point = Point.BASE) {
|
||||
point._setWindowSize(windowSize);
|
||||
point.multiply(BigInt(3));
|
||||
return point;
|
||||
},
|
||||
};
|
||||
return {
|
||||
CURVE,
|
||||
getPublicKey,
|
||||
sign,
|
||||
verify,
|
||||
ExtendedPoint: Point,
|
||||
utils,
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=edwards.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+120
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
|
||||
* API may change at any time. The code has not been audited. Feature requests are welcome.
|
||||
* @module
|
||||
*/
|
||||
import type { IField } from './modular.ts';
|
||||
export interface MutableArrayLike<T> {
|
||||
[index: number]: T;
|
||||
length: number;
|
||||
slice(start?: number, end?: number): this;
|
||||
[Symbol.iterator](): Iterator<T>;
|
||||
}
|
||||
/** Checks if integer is in form of `1 << X` */
|
||||
export declare function isPowerOfTwo(x: number): boolean;
|
||||
export declare function nextPowerOfTwo(n: number): number;
|
||||
export declare function reverseBits(n: number, bits: number): number;
|
||||
/** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
|
||||
export declare function log2(n: number): number;
|
||||
/**
|
||||
* Moves lowest bit to highest position, which at first step splits
|
||||
* array on even and odd indices, then it applied again to each part,
|
||||
* which is core of fft
|
||||
*/
|
||||
export declare function bitReversalInplace<T extends MutableArrayLike<any>>(values: T): T;
|
||||
export declare function bitReversalPermutation<T>(values: T[]): T[];
|
||||
/** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
|
||||
export declare function rootsOfUnity(field: IField<bigint>, generator?: bigint): {
|
||||
roots: (bits: number) => bigint[];
|
||||
brp(bits: number): bigint[];
|
||||
inverse(bits: number): bigint[];
|
||||
omega: (bits: number) => bigint;
|
||||
clear: () => void;
|
||||
};
|
||||
export type Polynomial<T> = MutableArrayLike<T>;
|
||||
/**
|
||||
* Maps great to Field<bigint>, but not to Group (EC points):
|
||||
* - inv from scalar field
|
||||
* - we need multiplyUnsafe here, instead of multiply for speed
|
||||
* - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse
|
||||
*/
|
||||
export type FFTOpts<T, R> = {
|
||||
add: (a: T, b: T) => T;
|
||||
sub: (a: T, b: T) => T;
|
||||
mul: (a: T, scalar: R) => T;
|
||||
inv: (a: R) => R;
|
||||
};
|
||||
export type FFTCoreOpts<R> = {
|
||||
N: number;
|
||||
roots: Polynomial<R>;
|
||||
dit: boolean;
|
||||
invertButterflies?: boolean;
|
||||
skipStages?: number;
|
||||
brp?: boolean;
|
||||
};
|
||||
export type FFTCoreLoop<T> = <P extends Polynomial<T>>(values: P) => P;
|
||||
/**
|
||||
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
||||
*
|
||||
* - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
|
||||
* - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), Gentleman–Sande
|
||||
*
|
||||
* DIT takes brp input, returns natural output.
|
||||
* DIF takes natural input, returns brp output.
|
||||
*
|
||||
* The output is actually identical. Time / frequence distinction is not meaningful
|
||||
* for Polynomial multiplication in fields.
|
||||
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
||||
*
|
||||
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
||||
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
||||
*/
|
||||
export declare const FFTCore: <T, R>(opts: FFTOpts<T, R>, coreOpts: FFTCoreOpts<R>) => FFTCoreLoop<T>;
|
||||
/**
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
* Naming mirrors other libraries.
|
||||
*/
|
||||
export declare const FFT: <T>(roots: ReturnType<typeof rootsOfUnity>, opts: FFTOpts<T, bigint>) => {
|
||||
direct<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
inverse<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
};
|
||||
export type CreatePolyFn<P extends Polynomial<T>, T> = (len: number, elm?: T) => P;
|
||||
export type PolyFn<P extends Polynomial<T>, T> = {
|
||||
roots: ReturnType<typeof rootsOfUnity>;
|
||||
create: CreatePolyFn<P, T>;
|
||||
length?: number;
|
||||
degree: (a: P) => number;
|
||||
extend: (a: P, len: number) => P;
|
||||
add: (a: P, b: P) => P;
|
||||
sub: (a: P, b: P) => P;
|
||||
mul: (a: P, b: P | T) => P;
|
||||
dot: (a: P, b: P) => P;
|
||||
convolve: (a: P, b: P) => P;
|
||||
shift: (p: P, factor: bigint) => P;
|
||||
clone: (a: P) => P;
|
||||
eval: (a: P, basis: P) => T;
|
||||
monomial: {
|
||||
basis: (x: T, n: number) => P;
|
||||
eval: (a: P, x: T) => T;
|
||||
};
|
||||
lagrange: {
|
||||
basis: (x: T, n: number, brp?: boolean) => P;
|
||||
eval: (a: P, x: T, brp?: boolean) => T;
|
||||
};
|
||||
vanishing: (roots: P) => P;
|
||||
};
|
||||
/**
|
||||
* Poly wants a cracker.
|
||||
*
|
||||
* Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is
|
||||
* function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:
|
||||
*
|
||||
* - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`
|
||||
* - **Basis** is array of functions
|
||||
* - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)
|
||||
* - **Array size** is domain size
|
||||
* - **Lattice** is matrix (Polynomial of Polynomials)
|
||||
*/
|
||||
export declare function poly<T>(field: IField<T>, roots: ReturnType<typeof rootsOfUnity>, create?: undefined, fft?: ReturnType<typeof FFT<T>>, length?: number): PolyFn<T[], T>;
|
||||
export declare function poly<T, P extends Polynomial<T>>(field: IField<T>, roots: ReturnType<typeof rootsOfUnity>, create: CreatePolyFn<P, T>, fft?: ReturnType<typeof FFT<T>>, length?: number): PolyFn<P, T>;
|
||||
//# sourceMappingURL=fft.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"fft.d.ts","sourceRoot":"","sources":["../src/abstract/fft.ts"],"names":[],"mappings":"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"}
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FFT = exports.FFTCore = void 0;
|
||||
exports.isPowerOfTwo = isPowerOfTwo;
|
||||
exports.nextPowerOfTwo = nextPowerOfTwo;
|
||||
exports.reverseBits = reverseBits;
|
||||
exports.log2 = log2;
|
||||
exports.bitReversalInplace = bitReversalInplace;
|
||||
exports.bitReversalPermutation = bitReversalPermutation;
|
||||
exports.rootsOfUnity = rootsOfUnity;
|
||||
exports.poly = poly;
|
||||
function checkU32(n) {
|
||||
// 0xff_ff_ff_ff
|
||||
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
|
||||
throw new Error('wrong u32 integer:' + n);
|
||||
return n;
|
||||
}
|
||||
/** Checks if integer is in form of `1 << X` */
|
||||
function isPowerOfTwo(x) {
|
||||
checkU32(x);
|
||||
return (x & (x - 1)) === 0 && x !== 0;
|
||||
}
|
||||
function nextPowerOfTwo(n) {
|
||||
checkU32(n);
|
||||
if (n <= 1)
|
||||
return 1;
|
||||
return (1 << (log2(n - 1) + 1)) >>> 0;
|
||||
}
|
||||
function reverseBits(n, bits) {
|
||||
checkU32(n);
|
||||
let reversed = 0;
|
||||
for (let i = 0; i < bits; i++, n >>>= 1)
|
||||
reversed = (reversed << 1) | (n & 1);
|
||||
return reversed;
|
||||
}
|
||||
/** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
|
||||
function log2(n) {
|
||||
checkU32(n);
|
||||
return 31 - Math.clz32(n);
|
||||
}
|
||||
/**
|
||||
* Moves lowest bit to highest position, which at first step splits
|
||||
* array on even and odd indices, then it applied again to each part,
|
||||
* which is core of fft
|
||||
*/
|
||||
function bitReversalInplace(values) {
|
||||
const n = values.length;
|
||||
if (n < 2 || !isPowerOfTwo(n))
|
||||
throw new Error('n must be a power of 2 and greater than 1. Got ' + n);
|
||||
const bits = log2(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const j = reverseBits(i, bits);
|
||||
if (i < j) {
|
||||
const tmp = values[i];
|
||||
values[i] = values[j];
|
||||
values[j] = tmp;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
function bitReversalPermutation(values) {
|
||||
return bitReversalInplace(values.slice());
|
||||
}
|
||||
const _1n = /** @__PURE__ */ BigInt(1);
|
||||
function findGenerator(field) {
|
||||
let G = BigInt(2);
|
||||
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)
|
||||
;
|
||||
return G;
|
||||
}
|
||||
/** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
|
||||
function rootsOfUnity(field, generator) {
|
||||
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
|
||||
let oddFactor = field.ORDER - _1n;
|
||||
let powerOfTwo = 0;
|
||||
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)
|
||||
;
|
||||
// Find non quadratic residue
|
||||
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
|
||||
// Powers of generator
|
||||
const omegas = new Array(powerOfTwo + 1);
|
||||
omegas[powerOfTwo] = field.pow(G, oddFactor);
|
||||
for (let i = powerOfTwo; i > 0; i--)
|
||||
omegas[i - 1] = field.sqr(omegas[i]);
|
||||
// Compute all roots of unity for powers up to maxPower
|
||||
const rootsCache = [];
|
||||
const checkBits = (bits) => {
|
||||
checkU32(bits);
|
||||
if (bits > 31 || bits > powerOfTwo)
|
||||
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
|
||||
return bits;
|
||||
};
|
||||
const precomputeRoots = (maxPower) => {
|
||||
checkBits(maxPower);
|
||||
for (let power = maxPower; power >= 0; power--) {
|
||||
if (rootsCache[power])
|
||||
continue; // Skip if we've already computed roots for this power
|
||||
const rootsAtPower = [];
|
||||
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
|
||||
rootsAtPower.push(cur);
|
||||
rootsCache[power] = rootsAtPower;
|
||||
}
|
||||
return rootsCache[maxPower];
|
||||
};
|
||||
const brpCache = new Map();
|
||||
const inverseCache = new Map();
|
||||
// NOTE: we use bits instead of power, because power = 2**bits,
|
||||
// but power is not neccesary isPowerOfTwo(power)!
|
||||
return {
|
||||
roots: (bits) => {
|
||||
const b = checkBits(bits);
|
||||
return precomputeRoots(b);
|
||||
},
|
||||
brp(bits) {
|
||||
const b = checkBits(bits);
|
||||
if (brpCache.has(b))
|
||||
return brpCache.get(b);
|
||||
else {
|
||||
const res = bitReversalPermutation(this.roots(b));
|
||||
brpCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
inverse(bits) {
|
||||
const b = checkBits(bits);
|
||||
if (inverseCache.has(b))
|
||||
return inverseCache.get(b);
|
||||
else {
|
||||
const res = field.invertBatch(this.roots(b));
|
||||
inverseCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
omega: (bits) => omegas[checkBits(bits)],
|
||||
clear: () => {
|
||||
rootsCache.splice(0, rootsCache.length);
|
||||
brpCache.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
||||
*
|
||||
* - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
|
||||
* - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), Gentleman–Sande
|
||||
*
|
||||
* DIT takes brp input, returns natural output.
|
||||
* DIF takes natural input, returns brp output.
|
||||
*
|
||||
* The output is actually identical. Time / frequence distinction is not meaningful
|
||||
* for Polynomial multiplication in fields.
|
||||
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
||||
*
|
||||
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
||||
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
||||
*/
|
||||
const FFTCore = (opts, coreOpts) => {
|
||||
const { add, sub, mul } = opts; // inline to butteflies
|
||||
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
|
||||
const bits = log2(N);
|
||||
if (!isPowerOfTwo(N))
|
||||
throw new Error('FFT: Polynomial size should be power of two');
|
||||
const isDit = dit !== invertButterflies;
|
||||
isDit;
|
||||
return (values) => {
|
||||
if (values.length !== N)
|
||||
throw new Error('FFT: wrong Polynomial length');
|
||||
if (dit && brp)
|
||||
bitReversalInplace(values);
|
||||
for (let i = 0, g = 1; i < bits - skipStages; i++) {
|
||||
// For each stage s (sub-FFT length m = 2^s)
|
||||
const s = dit ? i + 1 + skipStages : bits - i;
|
||||
const m = 1 << s;
|
||||
const m2 = m >> 1;
|
||||
const stride = N >> s;
|
||||
// Loop over each subarray of length m
|
||||
for (let k = 0; k < N; k += m) {
|
||||
// Loop over each butterfly within the subarray
|
||||
for (let j = 0, grp = g++; j < m2; j++) {
|
||||
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
|
||||
const i0 = k + j;
|
||||
const i1 = k + j + m2;
|
||||
const omega = roots[rootPos];
|
||||
const b = values[i1];
|
||||
const a = values[i0];
|
||||
// Inlining gives us 10% perf in kyber vs functions
|
||||
if (isDit) {
|
||||
const t = mul(b, omega); // Standard DIT butterfly
|
||||
values[i0] = add(a, t);
|
||||
values[i1] = sub(a, t);
|
||||
}
|
||||
else if (invertButterflies) {
|
||||
values[i0] = add(b, a); // DIT loop + inverted butterflies (Kyber decode)
|
||||
values[i1] = mul(sub(b, a), omega);
|
||||
}
|
||||
else {
|
||||
values[i0] = add(a, b); // Standard DIF butterfly
|
||||
values[i1] = mul(sub(a, b), omega);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!dit && brp)
|
||||
bitReversalInplace(values);
|
||||
return values;
|
||||
};
|
||||
};
|
||||
exports.FFTCore = FFTCore;
|
||||
/**
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
* Naming mirrors other libraries.
|
||||
*/
|
||||
const FFT = (roots, opts) => {
|
||||
const getLoop = (N, roots, brpInput = false, brpOutput = false) => {
|
||||
if (brpInput && brpOutput) {
|
||||
// we cannot optimize this case, but lets support it anyway
|
||||
return (values) => (0, exports.FFTCore)(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
|
||||
}
|
||||
if (brpInput)
|
||||
return (0, exports.FFTCore)(opts, { N, roots, dit: true, brp: false });
|
||||
if (brpOutput)
|
||||
return (0, exports.FFTCore)(opts, { N, roots, dit: false, brp: false });
|
||||
return (0, exports.FFTCore)(opts, { N, roots, dit: true, brp: true }); // all natural
|
||||
};
|
||||
return {
|
||||
direct(values, brpInput = false, brpOutput = false) {
|
||||
const N = values.length;
|
||||
if (!isPowerOfTwo(N))
|
||||
throw new Error('FFT: Polynomial size should be power of two');
|
||||
const bits = log2(N);
|
||||
return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice());
|
||||
},
|
||||
inverse(values, brpInput = false, brpOutput = false) {
|
||||
const N = values.length;
|
||||
const bits = log2(N);
|
||||
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
|
||||
const ivm = opts.inv(BigInt(values.length)); // scale
|
||||
// we can get brp output if we use dif instead of dit!
|
||||
for (let i = 0; i < res.length; i++)
|
||||
res[i] = opts.mul(res[i], ivm);
|
||||
// Allows to re-use non-inverted roots, but is VERY fragile
|
||||
// return [res[0]].concat(res.slice(1).reverse());
|
||||
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
|
||||
return res;
|
||||
},
|
||||
};
|
||||
};
|
||||
exports.FFT = FFT;
|
||||
function poly(field, roots, create, fft, length) {
|
||||
const F = field;
|
||||
const _create = create ||
|
||||
((len, elm) => new Array(len).fill(elm ?? F.ZERO));
|
||||
const isPoly = (x) => Array.isArray(x) || ArrayBuffer.isView(x);
|
||||
const checkLength = (...lst) => {
|
||||
if (!lst.length)
|
||||
return 0;
|
||||
for (const i of lst)
|
||||
if (!isPoly(i))
|
||||
throw new Error('poly: not polynomial: ' + i);
|
||||
const L = lst[0].length;
|
||||
for (let i = 1; i < lst.length; i++)
|
||||
if (lst[i].length !== L)
|
||||
throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
|
||||
if (length !== undefined && L !== length)
|
||||
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
|
||||
return L;
|
||||
};
|
||||
function findOmegaIndex(x, n, brp = false) {
|
||||
const bits = log2(n);
|
||||
const omega = brp ? roots.brp(bits) : roots.roots(bits);
|
||||
for (let i = 0; i < n; i++)
|
||||
if (F.eql(x, omega[i]))
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
// TODO: mutating versions for mlkem/mldsa
|
||||
return {
|
||||
roots,
|
||||
create: _create,
|
||||
length,
|
||||
extend: (a, len) => {
|
||||
checkLength(a);
|
||||
const out = _create(len, F.ZERO);
|
||||
for (let i = 0; i < a.length; i++)
|
||||
out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
degree: (a) => {
|
||||
checkLength(a);
|
||||
for (let i = a.length - 1; i >= 0; i--)
|
||||
if (!F.is0(a[i]))
|
||||
return i;
|
||||
return -1;
|
||||
},
|
||||
add: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.add(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
sub: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.sub(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
dot: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.mul(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
mul: (a, b) => {
|
||||
if (isPoly(b)) {
|
||||
const len = checkLength(a, b);
|
||||
if (fft) {
|
||||
const A = fft.direct(a, false, true);
|
||||
const B = fft.direct(b, false, true);
|
||||
for (let i = 0; i < A.length; i++)
|
||||
A[i] = F.mul(A[i], B[i]);
|
||||
return fft.inverse(A, true, false);
|
||||
}
|
||||
else {
|
||||
// NOTE: this is quadratic and mostly for compat tests with FFT
|
||||
const res = _create(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
for (let j = 0; j < len; j++) {
|
||||
const k = (i + j) % len; // wrap mod length
|
||||
res[k] = F.add(res[k], F.mul(a[i], b[j]));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const out = _create(checkLength(a));
|
||||
for (let i = 0; i < out.length; i++)
|
||||
out[i] = F.mul(a[i], b);
|
||||
return out;
|
||||
}
|
||||
},
|
||||
convolve(a, b) {
|
||||
const len = nextPowerOfTwo(a.length + b.length - 1);
|
||||
return this.mul(this.extend(a, len), this.extend(b, len));
|
||||
},
|
||||
shift(p, factor) {
|
||||
const out = _create(checkLength(p));
|
||||
out[0] = p[0];
|
||||
for (let i = 1, power = F.ONE; i < p.length; i++) {
|
||||
power = F.mul(power, factor);
|
||||
out[i] = F.mul(p[i], power);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
clone: (a) => {
|
||||
checkLength(a);
|
||||
const out = _create(a.length);
|
||||
for (let i = 0; i < a.length; i++)
|
||||
out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
eval: (a, basis) => {
|
||||
checkLength(a);
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
acc = F.add(acc, F.mul(a[i], basis[i]));
|
||||
return acc;
|
||||
},
|
||||
monomial: {
|
||||
basis: (x, n) => {
|
||||
const out = _create(n);
|
||||
let pow = F.ONE;
|
||||
for (let i = 0; i < n; i++) {
|
||||
out[i] = pow;
|
||||
pow = F.mul(pow, x);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
eval: (a, x) => {
|
||||
checkLength(a);
|
||||
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
|
||||
let acc = F.ZERO;
|
||||
for (let i = a.length - 1; i >= 0; i--)
|
||||
acc = F.add(F.mul(acc, x), a[i]);
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
lagrange: {
|
||||
basis: (x, n, brp = false, weights) => {
|
||||
const bits = log2(n);
|
||||
const cache = weights || brp ? roots.brp(bits) : roots.roots(bits); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
|
||||
const out = _create(n);
|
||||
// Fast Kronecker-δ shortcut
|
||||
const idx = findOmegaIndex(x, n, brp);
|
||||
if (idx !== -1) {
|
||||
out[idx] = F.ONE;
|
||||
return out;
|
||||
}
|
||||
const tm = F.pow(x, BigInt(n));
|
||||
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n
|
||||
const denom = _create(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
denom[i] = F.sub(x, cache[i]);
|
||||
const inv = F.invertBatch(denom);
|
||||
for (let i = 0; i < n; i++)
|
||||
out[i] = F.mul(c, F.mul(cache[i], inv[i]));
|
||||
return out;
|
||||
},
|
||||
eval(a, x, brp = false) {
|
||||
checkLength(a);
|
||||
const idx = findOmegaIndex(x, a.length, brp);
|
||||
if (idx !== -1)
|
||||
return a[idx]; // fast path
|
||||
const L = this.basis(x, a.length, brp); // Lᵢ(x)
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
if (!F.is0(a[i]))
|
||||
acc = F.add(acc, F.mul(a[i], L[i]));
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
vanishing(roots) {
|
||||
checkLength(roots);
|
||||
const out = _create(roots.length + 1, F.ZERO);
|
||||
out[0] = F.ONE;
|
||||
for (const r of roots) {
|
||||
const neg = F.neg(r);
|
||||
for (let j = out.length - 1; j > 0; j--)
|
||||
out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
|
||||
out[0] = F.mul(out[0], neg);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=fft.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+84
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* hash-to-curve from RFC 9380.
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* https://www.rfc-editor.org/rfc/rfc9380
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import type { AffinePoint, Group, GroupConstructor } from './curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
import type { CHash } from './utils.ts';
|
||||
export type UnicodeOrBytes = string | Uint8Array;
|
||||
/**
|
||||
* * `DST` is a domain separation tag, defined in section 2.2.5
|
||||
* * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
|
||||
* * `m` is extension degree (1 for prime fields)
|
||||
* * `k` is the target security target in bits (e.g. 128), from section 5.1
|
||||
* * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
|
||||
* * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
|
||||
*/
|
||||
export type Opts = {
|
||||
DST: UnicodeOrBytes;
|
||||
p: bigint;
|
||||
m: number;
|
||||
k: number;
|
||||
expand: 'xmd' | 'xof';
|
||||
hash: CHash;
|
||||
};
|
||||
/**
|
||||
* Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
|
||||
* [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
|
||||
*/
|
||||
export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array;
|
||||
/**
|
||||
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
* 1. The collision resistance of H MUST be at least k bits.
|
||||
* 2. H MUST be an XOF that has been proved indifferentiable from
|
||||
* a random oracle under a reasonable cryptographic assumption.
|
||||
* [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
|
||||
*/
|
||||
export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array;
|
||||
/**
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
|
||||
* @param msg a byte string containing the message to hash
|
||||
* @param count the number of elements of F to output
|
||||
* @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
|
||||
* @returns [u_0, ..., u_(count - 1)], a list of field elements.
|
||||
*/
|
||||
export declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][];
|
||||
export type XY<T> = (x: T, y: T) => {
|
||||
x: T;
|
||||
y: T;
|
||||
};
|
||||
export type XYRatio<T> = [T[], T[], T[], T[]];
|
||||
export declare function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T>;
|
||||
/** Point interface, which curves must implement to work correctly with the module. */
|
||||
export interface H2CPoint<T> extends Group<H2CPoint<T>> {
|
||||
add(rhs: H2CPoint<T>): H2CPoint<T>;
|
||||
toAffine(iz?: bigint): AffinePoint<T>;
|
||||
clearCofactor(): H2CPoint<T>;
|
||||
assertValidity(): void;
|
||||
}
|
||||
export interface H2CPointConstructor<T> extends GroupConstructor<H2CPoint<T>> {
|
||||
fromAffine(ap: AffinePoint<T>): H2CPoint<T>;
|
||||
}
|
||||
export type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;
|
||||
export type htfBasicOpts = {
|
||||
DST: UnicodeOrBytes;
|
||||
};
|
||||
export type HTFMethod<T> = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint<T>;
|
||||
export type MapMethod<T> = (scalars: bigint[]) => H2CPoint<T>;
|
||||
export type Hasher<T> = {
|
||||
hashToCurve: HTFMethod<T>;
|
||||
encodeToCurve: HTFMethod<T>;
|
||||
mapToCurve: MapMethod<T>;
|
||||
defaults: Opts & {
|
||||
encodeDST?: UnicodeOrBytes;
|
||||
};
|
||||
};
|
||||
/** Creates hash-to-curve methods from EC Point and mapToCurve function. */
|
||||
export declare function createHasher<T>(Point: H2CPointConstructor<T>, mapToCurve: MapToCurve<T>, defaults: Opts & {
|
||||
encodeDST?: UnicodeOrBytes;
|
||||
}): Hasher<T>;
|
||||
//# sourceMappingURL=hash-to-curve.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"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"}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.expand_message_xmd = expand_message_xmd;
|
||||
exports.expand_message_xof = expand_message_xof;
|
||||
exports.hash_to_field = hash_to_field;
|
||||
exports.isogenyMap = isogenyMap;
|
||||
exports.createHasher = createHasher;
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
|
||||
const os2ip = utils_ts_1.bytesToNumberBE;
|
||||
// Integer to Octet Stream (numberToBytesBE)
|
||||
function i2osp(value, length) {
|
||||
anum(value);
|
||||
anum(length);
|
||||
if (value < 0 || value >= 1 << (8 * length))
|
||||
throw new Error('invalid I2OSP input: ' + value);
|
||||
const res = Array.from({ length }).fill(0);
|
||||
for (let i = length - 1; i >= 0; i--) {
|
||||
res[i] = value & 0xff;
|
||||
value >>>= 8;
|
||||
}
|
||||
return new Uint8Array(res);
|
||||
}
|
||||
function strxor(a, b) {
|
||||
const arr = new Uint8Array(a.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
arr[i] = a[i] ^ b[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
function anum(item) {
|
||||
if (!Number.isSafeInteger(item))
|
||||
throw new Error('number expected');
|
||||
}
|
||||
/**
|
||||
* Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
|
||||
* [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
|
||||
*/
|
||||
function expand_message_xmd(msg, DST, lenInBytes, H) {
|
||||
(0, utils_ts_1.abytes)(msg);
|
||||
(0, utils_ts_1.abytes)(DST);
|
||||
anum(lenInBytes);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
if (DST.length > 255)
|
||||
DST = H((0, utils_ts_1.concatBytes)((0, utils_ts_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));
|
||||
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
|
||||
const ell = Math.ceil(lenInBytes / b_in_bytes);
|
||||
if (lenInBytes > 65535 || ell > 255)
|
||||
throw new Error('expand_message_xmd: invalid lenInBytes');
|
||||
const DST_prime = (0, utils_ts_1.concatBytes)(DST, i2osp(DST.length, 1));
|
||||
const Z_pad = i2osp(0, r_in_bytes);
|
||||
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
|
||||
const b = new Array(ell);
|
||||
const b_0 = H((0, utils_ts_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
|
||||
b[0] = H((0, utils_ts_1.concatBytes)(b_0, i2osp(1, 1), DST_prime));
|
||||
for (let i = 1; i <= ell; i++) {
|
||||
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
|
||||
b[i] = H((0, utils_ts_1.concatBytes)(...args));
|
||||
}
|
||||
const pseudo_random_bytes = (0, utils_ts_1.concatBytes)(...b);
|
||||
return pseudo_random_bytes.slice(0, lenInBytes);
|
||||
}
|
||||
/**
|
||||
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
* 1. The collision resistance of H MUST be at least k bits.
|
||||
* 2. H MUST be an XOF that has been proved indifferentiable from
|
||||
* a random oracle under a reasonable cryptographic assumption.
|
||||
* [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
|
||||
*/
|
||||
function expand_message_xof(msg, DST, lenInBytes, k, H) {
|
||||
(0, utils_ts_1.abytes)(msg);
|
||||
(0, utils_ts_1.abytes)(DST);
|
||||
anum(lenInBytes);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
// DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
|
||||
if (DST.length > 255) {
|
||||
const dkLen = Math.ceil((2 * k) / 8);
|
||||
DST = H.create({ dkLen }).update((0, utils_ts_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
|
||||
}
|
||||
if (lenInBytes > 65535 || DST.length > 255)
|
||||
throw new Error('expand_message_xof: invalid lenInBytes');
|
||||
return (H.create({ dkLen: lenInBytes })
|
||||
.update(msg)
|
||||
.update(i2osp(lenInBytes, 2))
|
||||
// 2. DST_prime = DST || I2OSP(len(DST), 1)
|
||||
.update(DST)
|
||||
.update(i2osp(DST.length, 1))
|
||||
.digest());
|
||||
}
|
||||
/**
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
|
||||
* @param msg a byte string containing the message to hash
|
||||
* @param count the number of elements of F to output
|
||||
* @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
|
||||
* @returns [u_0, ..., u_(count - 1)], a list of field elements.
|
||||
*/
|
||||
function hash_to_field(msg, count, options) {
|
||||
(0, utils_ts_1.validateObject)(options, {
|
||||
DST: 'stringOrUint8Array',
|
||||
p: 'bigint',
|
||||
m: 'isSafeInteger',
|
||||
k: 'isSafeInteger',
|
||||
hash: 'hash',
|
||||
});
|
||||
const { p, k, m, hash, expand, DST: _DST } = options;
|
||||
(0, utils_ts_1.abytes)(msg);
|
||||
anum(count);
|
||||
const DST = typeof _DST === 'string' ? (0, utils_ts_1.utf8ToBytes)(_DST) : _DST;
|
||||
const log2p = p.toString(2).length;
|
||||
const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
|
||||
const len_in_bytes = count * m * L;
|
||||
let prb; // pseudo_random_bytes
|
||||
if (expand === 'xmd') {
|
||||
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
|
||||
}
|
||||
else if (expand === 'xof') {
|
||||
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
|
||||
}
|
||||
else if (expand === '_internal_pass') {
|
||||
// for internal tests only
|
||||
prb = msg;
|
||||
}
|
||||
else {
|
||||
throw new Error('expand must be "xmd" or "xof"');
|
||||
}
|
||||
const u = new Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const e = new Array(m);
|
||||
for (let j = 0; j < m; j++) {
|
||||
const elm_offset = L * (j + i * m);
|
||||
const tv = prb.subarray(elm_offset, elm_offset + L);
|
||||
e[j] = (0, modular_ts_1.mod)(os2ip(tv), p);
|
||||
}
|
||||
u[i] = e;
|
||||
}
|
||||
return u;
|
||||
}
|
||||
function isogenyMap(field, map) {
|
||||
// Make same order as in spec
|
||||
const coeff = map.map((i) => Array.from(i).reverse());
|
||||
return (x, y) => {
|
||||
const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
|
||||
// 6.6.3
|
||||
// Exceptional cases of iso_map are inputs that cause the denominator of
|
||||
// either rational function to evaluate to zero; such cases MUST return
|
||||
// the identity point on E.
|
||||
const [xd_inv, yd_inv] = (0, modular_ts_1.FpInvertBatch)(field, [xd, yd], true);
|
||||
x = field.mul(xn, xd_inv); // xNum / xDen
|
||||
y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
|
||||
return { x, y };
|
||||
};
|
||||
}
|
||||
/** Creates hash-to-curve methods from EC Point and mapToCurve function. */
|
||||
function createHasher(Point, mapToCurve, defaults) {
|
||||
if (typeof mapToCurve !== 'function')
|
||||
throw new Error('mapToCurve() must be defined');
|
||||
function map(num) {
|
||||
return Point.fromAffine(mapToCurve(num));
|
||||
}
|
||||
function clear(initial) {
|
||||
const P = initial.clearCofactor();
|
||||
if (P.equals(Point.ZERO))
|
||||
return Point.ZERO; // zero will throw in assert
|
||||
P.assertValidity();
|
||||
return P;
|
||||
}
|
||||
return {
|
||||
defaults,
|
||||
// Encodes byte string to elliptic curve.
|
||||
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
|
||||
hashToCurve(msg, options) {
|
||||
const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options });
|
||||
const u0 = map(u[0]);
|
||||
const u1 = map(u[1]);
|
||||
return clear(u0.add(u1));
|
||||
},
|
||||
// Encodes byte string to elliptic curve.
|
||||
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
|
||||
encodeToCurve(msg, options) {
|
||||
const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options });
|
||||
return clear(map(u[0]));
|
||||
},
|
||||
// Same as encodeToCurve, but without hash
|
||||
mapToCurve(scalars) {
|
||||
if (!Array.isArray(scalars))
|
||||
throw new Error('expected array of bigints');
|
||||
for (const i of scalars)
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('expected array of bigints');
|
||||
return clear(map(scalars));
|
||||
},
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=hash-to-curve.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+153
@@ -0,0 +1,153 @@
|
||||
export declare function mod(a: bigint, b: bigint): bigint;
|
||||
/**
|
||||
* Efficiently raise num to power and do modular division.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* TODO: remove.
|
||||
* @example
|
||||
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
||||
*/
|
||||
export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint;
|
||||
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
|
||||
export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint;
|
||||
/**
|
||||
* Inverses number over modulo.
|
||||
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
|
||||
*/
|
||||
export declare function invert(number: bigint, modulo: bigint): bigint;
|
||||
/**
|
||||
* Tonelli-Shanks square root search algorithm.
|
||||
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
|
||||
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
||||
* @param P field order
|
||||
* @returns function that takes field Fp (created from P) and number n
|
||||
*/
|
||||
export declare function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T;
|
||||
/**
|
||||
* Square root for a finite field. Will try optimized versions first:
|
||||
*
|
||||
* 1. P ≡ 3 (mod 4)
|
||||
* 2. P ≡ 5 (mod 8)
|
||||
* 3. Tonelli-Shanks algorithm
|
||||
*
|
||||
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
||||
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
|
||||
*/
|
||||
export declare function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T;
|
||||
export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean;
|
||||
/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */
|
||||
export interface IField<T> {
|
||||
ORDER: bigint;
|
||||
isLE: boolean;
|
||||
BYTES: number;
|
||||
BITS: number;
|
||||
MASK: bigint;
|
||||
ZERO: T;
|
||||
ONE: T;
|
||||
create: (num: T) => T;
|
||||
isValid: (num: T) => boolean;
|
||||
is0: (num: T) => boolean;
|
||||
neg(num: T): T;
|
||||
inv(num: T): T;
|
||||
sqrt(num: T): T;
|
||||
sqr(num: T): T;
|
||||
eql(lhs: T, rhs: T): boolean;
|
||||
add(lhs: T, rhs: T): T;
|
||||
sub(lhs: T, rhs: T): T;
|
||||
mul(lhs: T, rhs: T | bigint): T;
|
||||
pow(lhs: T, power: bigint): T;
|
||||
div(lhs: T, rhs: T | bigint): T;
|
||||
addN(lhs: T, rhs: T): T;
|
||||
subN(lhs: T, rhs: T): T;
|
||||
mulN(lhs: T, rhs: T | bigint): T;
|
||||
sqrN(num: T): T;
|
||||
isOdd?(num: T): boolean;
|
||||
invertBatch: (lst: T[]) => T[];
|
||||
toBytes(num: T): Uint8Array;
|
||||
fromBytes(bytes: Uint8Array): T;
|
||||
cmov(a: T, b: T, c: boolean): T;
|
||||
}
|
||||
export declare function validateField<T>(field: IField<T>): IField<T>;
|
||||
/**
|
||||
* Same as `pow` but for Fp: non-constant-time.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
*/
|
||||
export declare function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T;
|
||||
/**
|
||||
* Efficiently invert an array of Field elements.
|
||||
* Exception-free. Will return `undefined` for 0 elements.
|
||||
* @param passZero map 0 to 0 (instead of undefined)
|
||||
*/
|
||||
export declare function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero?: boolean): T[];
|
||||
export declare function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T;
|
||||
/**
|
||||
* Legendre symbol.
|
||||
* Legendre constant is used to calculate Legendre symbol (a | p)
|
||||
* which denotes the value of a^((p-1)/2) (mod p).
|
||||
*
|
||||
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
||||
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
||||
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
||||
*/
|
||||
export declare function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1;
|
||||
export declare function FpIsSquare<T>(Fp: IField<T>, n: T): boolean;
|
||||
export declare function nLength(n: bigint, nBitLength?: number): {
|
||||
nBitLength: number;
|
||||
nByteLength: number;
|
||||
};
|
||||
type FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;
|
||||
/**
|
||||
* Initializes a finite field over prime.
|
||||
* Major performance optimizations:
|
||||
* * a) denormalized operations like mulN instead of mul
|
||||
* * b) same object shape: never add or remove keys
|
||||
* * c) Object.freeze
|
||||
* Fragile: always run a benchmark on a change.
|
||||
* Security note: operations don't check 'isValid' for all elements for performance reasons,
|
||||
* it is caller responsibility to check this.
|
||||
* This is low-level code, please make sure you know what you're doing.
|
||||
* @param ORDER prime positive bigint
|
||||
* @param bitLen how many bits the field consumes
|
||||
* @param isLE (def: false) if encoding / decoding should be in little-endian
|
||||
* @param redef optional faster redefinitions of sqrt and other methods
|
||||
*/
|
||||
export declare function Field(ORDER: bigint, bitLen?: number, isLE?: boolean, redef?: Partial<IField<bigint>>): Readonly<FpField>;
|
||||
export declare function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T;
|
||||
export declare function FpSqrtEven<T>(Fp: IField<T>, elm: T): T;
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
|
||||
* Which makes it slightly more biased, less secure.
|
||||
* @deprecated use `mapKeyToField` instead
|
||||
*/
|
||||
export declare function hashToPrivateScalar(hash: string | Uint8Array, groupOrder: bigint, isLE?: boolean): bigint;
|
||||
/**
|
||||
* Returns total number of bytes consumed by the field element.
|
||||
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of field
|
||||
*/
|
||||
export declare function getFieldBytesLength(fieldOrder: bigint): number;
|
||||
/**
|
||||
* Returns minimal amount of bytes that can be safely reduced
|
||||
* by field order.
|
||||
* Should be 2^-128 for 128-bit curve such as P256.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of target hash
|
||||
*/
|
||||
export declare function getMinHashLength(fieldOrder: bigint): number;
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
||||
* and convert them into private scalar, with the modulo bias being negligible.
|
||||
* Needs at least 48 bytes of input for 32-byte private key.
|
||||
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
|
||||
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
|
||||
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
|
||||
* @param hash hash output from SHA3 or a similar function
|
||||
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
|
||||
* @param isLE interpret hash bytes as LE num
|
||||
* @returns valid private scalar
|
||||
*/
|
||||
export declare function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE?: boolean): Uint8Array;
|
||||
export {};
|
||||
//# sourceMappingURL=modular.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"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"}
|
||||
+481
@@ -0,0 +1,481 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isNegativeLE = void 0;
|
||||
exports.mod = mod;
|
||||
exports.pow = pow;
|
||||
exports.pow2 = pow2;
|
||||
exports.invert = invert;
|
||||
exports.tonelliShanks = tonelliShanks;
|
||||
exports.FpSqrt = FpSqrt;
|
||||
exports.validateField = validateField;
|
||||
exports.FpPow = FpPow;
|
||||
exports.FpInvertBatch = FpInvertBatch;
|
||||
exports.FpDiv = FpDiv;
|
||||
exports.FpLegendre = FpLegendre;
|
||||
exports.FpIsSquare = FpIsSquare;
|
||||
exports.nLength = nLength;
|
||||
exports.Field = Field;
|
||||
exports.FpSqrtOdd = FpSqrtOdd;
|
||||
exports.FpSqrtEven = FpSqrtEven;
|
||||
exports.hashToPrivateScalar = hashToPrivateScalar;
|
||||
exports.getFieldBytesLength = getFieldBytesLength;
|
||||
exports.getMinHashLength = getMinHashLength;
|
||||
exports.mapHashToField = mapHashToField;
|
||||
/**
|
||||
* Utils for modular division and finite fields.
|
||||
* A finite field over 11 is integer number operations `mod 11`.
|
||||
* There is no division: it is replaced by modular multiplicative inverse.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const utils_1 = require("@noble/hashes/utils");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
|
||||
// prettier-ignore
|
||||
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
|
||||
// Calculates a modulo b
|
||||
function mod(a, b) {
|
||||
const result = a % b;
|
||||
return result >= _0n ? result : b + result;
|
||||
}
|
||||
/**
|
||||
* Efficiently raise num to power and do modular division.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* TODO: remove.
|
||||
* @example
|
||||
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
||||
*/
|
||||
function pow(num, power, modulo) {
|
||||
return FpPow(Field(modulo), num, power);
|
||||
}
|
||||
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
|
||||
function pow2(x, power, modulo) {
|
||||
let res = x;
|
||||
while (power-- > _0n) {
|
||||
res *= res;
|
||||
res %= modulo;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Inverses number over modulo.
|
||||
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
|
||||
*/
|
||||
function invert(number, modulo) {
|
||||
if (number === _0n)
|
||||
throw new Error('invert: expected non-zero number');
|
||||
if (modulo <= _0n)
|
||||
throw new Error('invert: expected positive modulus, got ' + modulo);
|
||||
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
||||
let a = mod(number, modulo);
|
||||
let b = modulo;
|
||||
// prettier-ignore
|
||||
let x = _0n, y = _1n, u = _1n, v = _0n;
|
||||
while (a !== _0n) {
|
||||
// JIT applies optimization if those two lines follow each other
|
||||
const q = b / a;
|
||||
const r = b % a;
|
||||
const m = x - u * q;
|
||||
const n = y - v * q;
|
||||
// prettier-ignore
|
||||
b = a, a = r, x = u, y = v, u = m, v = n;
|
||||
}
|
||||
const gcd = b;
|
||||
if (gcd !== _1n)
|
||||
throw new Error('invert: does not exist');
|
||||
return mod(x, modulo);
|
||||
}
|
||||
// Not all roots are possible! Example which will throw:
|
||||
// const NUM =
|
||||
// n = 72057594037927816n;
|
||||
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
||||
function sqrt3mod4(Fp, n) {
|
||||
const p1div4 = (Fp.ORDER + _1n) / _4n;
|
||||
const root = Fp.pow(n, p1div4);
|
||||
// Throw if root^2 != n
|
||||
if (!Fp.eql(Fp.sqr(root), n))
|
||||
throw new Error('Cannot find square root');
|
||||
return root;
|
||||
}
|
||||
function sqrt5mod8(Fp, n) {
|
||||
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
||||
const n2 = Fp.mul(n, _2n);
|
||||
const v = Fp.pow(n2, p5div8);
|
||||
const nv = Fp.mul(n, v);
|
||||
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
||||
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
||||
if (!Fp.eql(Fp.sqr(root), n))
|
||||
throw new Error('Cannot find square root');
|
||||
return root;
|
||||
}
|
||||
// TODO: Commented-out for now. Provide test vectors.
|
||||
// Tonelli is too slow for extension fields Fp2.
|
||||
// That means we can't use sqrt (c1, c2...) even for initialization constants.
|
||||
// if (P % _16n === _9n) return sqrt9mod16;
|
||||
// // prettier-ignore
|
||||
// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {
|
||||
// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;
|
||||
// const c1 = Fp.sqrt(Fp.neg(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
||||
// const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
||||
// const c3 = Fp.sqrt(Fp.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
||||
// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
||||
// let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4
|
||||
// let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
|
||||
// const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
|
||||
// let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
|
||||
// const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
||||
// const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
||||
// tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
||||
// tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
||||
// const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
||||
// return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
|
||||
// }
|
||||
/**
|
||||
* Tonelli-Shanks square root search algorithm.
|
||||
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
|
||||
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
||||
* @param P field order
|
||||
* @returns function that takes field Fp (created from P) and number n
|
||||
*/
|
||||
function tonelliShanks(P) {
|
||||
// Initialization (precomputation).
|
||||
if (P < BigInt(3))
|
||||
throw new Error('sqrt is not defined for small field');
|
||||
// Factor P - 1 = Q * 2^S, where Q is odd
|
||||
let Q = P - _1n;
|
||||
let S = 0;
|
||||
while (Q % _2n === _0n) {
|
||||
Q /= _2n;
|
||||
S++;
|
||||
}
|
||||
// Find the first quadratic non-residue Z >= 2
|
||||
let Z = _2n;
|
||||
const _Fp = Field(P);
|
||||
while (FpLegendre(_Fp, Z) === 1) {
|
||||
// Basic primality test for P. After x iterations, chance of
|
||||
// not finding quadratic non-residue is 2^x, so 2^1000.
|
||||
if (Z++ > 1000)
|
||||
throw new Error('Cannot find square root: probably non-prime P');
|
||||
}
|
||||
// Fast-path; usually done before Z, but we do "primality test".
|
||||
if (S === 1)
|
||||
return sqrt3mod4;
|
||||
// Slow-path
|
||||
// TODO: test on Fp2 and others
|
||||
let cc = _Fp.pow(Z, Q); // c = z^Q
|
||||
const Q1div2 = (Q + _1n) / _2n;
|
||||
return function tonelliSlow(Fp, n) {
|
||||
if (Fp.is0(n))
|
||||
return n;
|
||||
// Check if n is a quadratic residue using Legendre symbol
|
||||
if (FpLegendre(Fp, n) !== 1)
|
||||
throw new Error('Cannot find square root');
|
||||
// Initialize variables for the main loop
|
||||
let M = S;
|
||||
let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
||||
let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
||||
let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
||||
// Main loop
|
||||
// while t != 1
|
||||
while (!Fp.eql(t, Fp.ONE)) {
|
||||
if (Fp.is0(t))
|
||||
return Fp.ZERO; // if t=0 return R=0
|
||||
let i = 1;
|
||||
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
||||
let t_tmp = Fp.sqr(t); // t^(2^1)
|
||||
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
||||
i++;
|
||||
t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
|
||||
if (i === M)
|
||||
throw new Error('Cannot find square root');
|
||||
}
|
||||
// Calculate the exponent for b: 2^(M - i - 1)
|
||||
const exponent = _1n << BigInt(M - i - 1); // bigint is important
|
||||
const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
|
||||
// Update variables
|
||||
M = i;
|
||||
c = Fp.sqr(b); // c = b^2
|
||||
t = Fp.mul(t, c); // t = (t * b^2)
|
||||
R = Fp.mul(R, b); // R = R*b
|
||||
}
|
||||
return R;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Square root for a finite field. Will try optimized versions first:
|
||||
*
|
||||
* 1. P ≡ 3 (mod 4)
|
||||
* 2. P ≡ 5 (mod 8)
|
||||
* 3. Tonelli-Shanks algorithm
|
||||
*
|
||||
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
||||
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
|
||||
*/
|
||||
function FpSqrt(P) {
|
||||
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
||||
if (P % _4n === _3n)
|
||||
return sqrt3mod4;
|
||||
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
||||
if (P % _8n === _5n)
|
||||
return sqrt5mod8;
|
||||
// P ≡ 9 (mod 16) not implemented, see above
|
||||
// Tonelli-Shanks algorithm
|
||||
return tonelliShanks(P);
|
||||
}
|
||||
// Little-endian check for first LE bit (last BE bit);
|
||||
const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
|
||||
exports.isNegativeLE = isNegativeLE;
|
||||
// prettier-ignore
|
||||
const FIELD_FIELDS = [
|
||||
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
||||
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
||||
'addN', 'subN', 'mulN', 'sqrN'
|
||||
];
|
||||
function validateField(field) {
|
||||
const initial = {
|
||||
ORDER: 'bigint',
|
||||
MASK: 'bigint',
|
||||
BYTES: 'isSafeInteger',
|
||||
BITS: 'isSafeInteger',
|
||||
};
|
||||
const opts = FIELD_FIELDS.reduce((map, val) => {
|
||||
map[val] = 'function';
|
||||
return map;
|
||||
}, initial);
|
||||
return (0, utils_ts_1.validateObject)(field, opts);
|
||||
}
|
||||
// Generic field functions
|
||||
/**
|
||||
* Same as `pow` but for Fp: non-constant-time.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
*/
|
||||
function FpPow(Fp, num, power) {
|
||||
if (power < _0n)
|
||||
throw new Error('invalid exponent, negatives unsupported');
|
||||
if (power === _0n)
|
||||
return Fp.ONE;
|
||||
if (power === _1n)
|
||||
return num;
|
||||
let p = Fp.ONE;
|
||||
let d = num;
|
||||
while (power > _0n) {
|
||||
if (power & _1n)
|
||||
p = Fp.mul(p, d);
|
||||
d = Fp.sqr(d);
|
||||
power >>= _1n;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* Efficiently invert an array of Field elements.
|
||||
* Exception-free. Will return `undefined` for 0 elements.
|
||||
* @param passZero map 0 to 0 (instead of undefined)
|
||||
*/
|
||||
function FpInvertBatch(Fp, nums, passZero = false) {
|
||||
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
|
||||
// Walk from first to last, multiply them by each other MOD p
|
||||
const multipliedAcc = nums.reduce((acc, num, i) => {
|
||||
if (Fp.is0(num))
|
||||
return acc;
|
||||
inverted[i] = acc;
|
||||
return Fp.mul(acc, num);
|
||||
}, Fp.ONE);
|
||||
// Invert last element
|
||||
const invertedAcc = Fp.inv(multipliedAcc);
|
||||
// Walk from last to first, multiply them by inverted each other MOD p
|
||||
nums.reduceRight((acc, num, i) => {
|
||||
if (Fp.is0(num))
|
||||
return acc;
|
||||
inverted[i] = Fp.mul(acc, inverted[i]);
|
||||
return Fp.mul(acc, num);
|
||||
}, invertedAcc);
|
||||
return inverted;
|
||||
}
|
||||
// TODO: remove
|
||||
function FpDiv(Fp, lhs, rhs) {
|
||||
return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
|
||||
}
|
||||
/**
|
||||
* Legendre symbol.
|
||||
* Legendre constant is used to calculate Legendre symbol (a | p)
|
||||
* which denotes the value of a^((p-1)/2) (mod p).
|
||||
*
|
||||
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
||||
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
||||
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
||||
*/
|
||||
function FpLegendre(Fp, n) {
|
||||
// We can use 3rd argument as optional cache of this value
|
||||
// but seems unneeded for now. The operation is very fast.
|
||||
const p1mod2 = (Fp.ORDER - _1n) / _2n;
|
||||
const powered = Fp.pow(n, p1mod2);
|
||||
const yes = Fp.eql(powered, Fp.ONE);
|
||||
const zero = Fp.eql(powered, Fp.ZERO);
|
||||
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
||||
if (!yes && !zero && !no)
|
||||
throw new Error('invalid Legendre symbol result');
|
||||
return yes ? 1 : zero ? 0 : -1;
|
||||
}
|
||||
// This function returns True whenever the value x is a square in the field F.
|
||||
function FpIsSquare(Fp, n) {
|
||||
const l = FpLegendre(Fp, n);
|
||||
return l === 1;
|
||||
}
|
||||
// CURVE.n lengths
|
||||
function nLength(n, nBitLength) {
|
||||
// Bit size, byte size of CURVE.n
|
||||
if (nBitLength !== undefined)
|
||||
(0, utils_1.anumber)(nBitLength);
|
||||
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
|
||||
const nByteLength = Math.ceil(_nBitLength / 8);
|
||||
return { nBitLength: _nBitLength, nByteLength };
|
||||
}
|
||||
/**
|
||||
* Initializes a finite field over prime.
|
||||
* Major performance optimizations:
|
||||
* * a) denormalized operations like mulN instead of mul
|
||||
* * b) same object shape: never add or remove keys
|
||||
* * c) Object.freeze
|
||||
* Fragile: always run a benchmark on a change.
|
||||
* Security note: operations don't check 'isValid' for all elements for performance reasons,
|
||||
* it is caller responsibility to check this.
|
||||
* This is low-level code, please make sure you know what you're doing.
|
||||
* @param ORDER prime positive bigint
|
||||
* @param bitLen how many bits the field consumes
|
||||
* @param isLE (def: false) if encoding / decoding should be in little-endian
|
||||
* @param redef optional faster redefinitions of sqrt and other methods
|
||||
*/
|
||||
function Field(ORDER, bitLen, isLE = false, redef = {}) {
|
||||
if (ORDER <= _0n)
|
||||
throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
|
||||
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
|
||||
if (BYTES > 2048)
|
||||
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
||||
let sqrtP; // cached sqrtP
|
||||
const f = Object.freeze({
|
||||
ORDER,
|
||||
isLE,
|
||||
BITS,
|
||||
BYTES,
|
||||
MASK: (0, utils_ts_1.bitMask)(BITS),
|
||||
ZERO: _0n,
|
||||
ONE: _1n,
|
||||
create: (num) => mod(num, ORDER),
|
||||
isValid: (num) => {
|
||||
if (typeof num !== 'bigint')
|
||||
throw new Error('invalid field element: expected bigint, got ' + typeof num);
|
||||
return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
|
||||
},
|
||||
is0: (num) => num === _0n,
|
||||
isOdd: (num) => (num & _1n) === _1n,
|
||||
neg: (num) => mod(-num, ORDER),
|
||||
eql: (lhs, rhs) => lhs === rhs,
|
||||
sqr: (num) => mod(num * num, ORDER),
|
||||
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
||||
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
||||
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
||||
pow: (num, power) => FpPow(f, num, power),
|
||||
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
||||
// Same as above, but doesn't normalize
|
||||
sqrN: (num) => num * num,
|
||||
addN: (lhs, rhs) => lhs + rhs,
|
||||
subN: (lhs, rhs) => lhs - rhs,
|
||||
mulN: (lhs, rhs) => lhs * rhs,
|
||||
inv: (num) => invert(num, ORDER),
|
||||
sqrt: redef.sqrt ||
|
||||
((n) => {
|
||||
if (!sqrtP)
|
||||
sqrtP = FpSqrt(ORDER);
|
||||
return sqrtP(f, n);
|
||||
}),
|
||||
toBytes: (num) => (isLE ? (0, utils_ts_1.numberToBytesLE)(num, BYTES) : (0, utils_ts_1.numberToBytesBE)(num, BYTES)),
|
||||
fromBytes: (bytes) => {
|
||||
if (bytes.length !== BYTES)
|
||||
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
||||
return isLE ? (0, utils_ts_1.bytesToNumberLE)(bytes) : (0, utils_ts_1.bytesToNumberBE)(bytes);
|
||||
},
|
||||
// TODO: we don't need it here, move out to separate fn
|
||||
invertBatch: (lst) => FpInvertBatch(f, lst),
|
||||
// We can't move this out because Fp6, Fp12 implement it
|
||||
// and it's unclear what to return in there.
|
||||
cmov: (a, b, c) => (c ? b : a),
|
||||
});
|
||||
return Object.freeze(f);
|
||||
}
|
||||
function FpSqrtOdd(Fp, elm) {
|
||||
if (!Fp.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = Fp.sqrt(elm);
|
||||
return Fp.isOdd(root) ? root : Fp.neg(root);
|
||||
}
|
||||
function FpSqrtEven(Fp, elm) {
|
||||
if (!Fp.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = Fp.sqrt(elm);
|
||||
return Fp.isOdd(root) ? Fp.neg(root) : root;
|
||||
}
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
|
||||
* Which makes it slightly more biased, less secure.
|
||||
* @deprecated use `mapKeyToField` instead
|
||||
*/
|
||||
function hashToPrivateScalar(hash, groupOrder, isLE = false) {
|
||||
hash = (0, utils_ts_1.ensureBytes)('privateHash', hash);
|
||||
const hashLen = hash.length;
|
||||
const minLen = nLength(groupOrder).nByteLength + 8;
|
||||
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
|
||||
throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
|
||||
const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(hash) : (0, utils_ts_1.bytesToNumberBE)(hash);
|
||||
return mod(num, groupOrder - _1n) + _1n;
|
||||
}
|
||||
/**
|
||||
* Returns total number of bytes consumed by the field element.
|
||||
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of field
|
||||
*/
|
||||
function getFieldBytesLength(fieldOrder) {
|
||||
if (typeof fieldOrder !== 'bigint')
|
||||
throw new Error('field order must be bigint');
|
||||
const bitLength = fieldOrder.toString(2).length;
|
||||
return Math.ceil(bitLength / 8);
|
||||
}
|
||||
/**
|
||||
* Returns minimal amount of bytes that can be safely reduced
|
||||
* by field order.
|
||||
* Should be 2^-128 for 128-bit curve such as P256.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of target hash
|
||||
*/
|
||||
function getMinHashLength(fieldOrder) {
|
||||
const length = getFieldBytesLength(fieldOrder);
|
||||
return length + Math.ceil(length / 2);
|
||||
}
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
||||
* and convert them into private scalar, with the modulo bias being negligible.
|
||||
* Needs at least 48 bytes of input for 32-byte private key.
|
||||
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
|
||||
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
|
||||
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
|
||||
* @param hash hash output from SHA3 or a similar function
|
||||
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
|
||||
* @param isLE interpret hash bytes as LE num
|
||||
* @returns valid private scalar
|
||||
*/
|
||||
function mapHashToField(key, fieldOrder, isLE = false) {
|
||||
const len = key.length;
|
||||
const fieldLen = getFieldBytesLength(fieldOrder);
|
||||
const minLen = getMinHashLength(fieldOrder);
|
||||
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
|
||||
if (len < 16 || len < minLen || len > 1024)
|
||||
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
||||
const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(key) : (0, utils_ts_1.bytesToNumberBE)(key);
|
||||
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
||||
const reduced = mod(num, fieldOrder - _1n) + _1n;
|
||||
return isLE ? (0, utils_ts_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_ts_1.numberToBytesBE)(reduced, fieldLen);
|
||||
}
|
||||
//# sourceMappingURL=modular.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+21
@@ -0,0 +1,21 @@
|
||||
type Hex = string | Uint8Array;
|
||||
export type CurveType = {
|
||||
P: bigint;
|
||||
type: 'x25519' | 'x448';
|
||||
adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;
|
||||
powPminus2: (x: bigint) => bigint;
|
||||
randomBytes: (bytesLength?: number) => Uint8Array;
|
||||
};
|
||||
export type CurveFn = {
|
||||
scalarMult: (scalar: Hex, u: Hex) => Uint8Array;
|
||||
scalarMultBase: (scalar: Hex) => Uint8Array;
|
||||
getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;
|
||||
getPublicKey: (privateKey: Hex) => Uint8Array;
|
||||
utils: {
|
||||
randomPrivateKey: () => Uint8Array;
|
||||
};
|
||||
GuBytes: Uint8Array;
|
||||
};
|
||||
export declare function montgomery(curveDef: CurveType): CurveFn;
|
||||
export {};
|
||||
//# sourceMappingURL=montgomery.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAmBA,KAAK,GAAG,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/B,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC;IACxB,iBAAiB,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,UAAU,CAAC;IACrD,UAAU,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAClC,WAAW,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;CACnD,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,UAAU,CAAC;IAChD,cAAc,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,UAAU,CAAC;IAC5C,eAAe,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IACnE,YAAY,EAAE,CAAC,UAAU,EAAE,GAAG,KAAK,UAAU,CAAC;IAC9C,KAAK,EAAE;QAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;KAAE,CAAC;IAC9C,OAAO,EAAE,UAAU,CAAC;CACrB,CAAC;AAUF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,SAAS,GAAG,OAAO,CAsHvD"}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.montgomery = montgomery;
|
||||
/**
|
||||
* Montgomery curve methods. It's not really whole montgomery curve,
|
||||
* just bunch of very specific methods for X25519 / X448 from
|
||||
* [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
const _2n = BigInt(2);
|
||||
function validateOpts(curve) {
|
||||
(0, utils_ts_1.validateObject)(curve, {
|
||||
adjustScalarBytes: 'function',
|
||||
powPminus2: 'function',
|
||||
});
|
||||
return Object.freeze({ ...curve });
|
||||
}
|
||||
function montgomery(curveDef) {
|
||||
const CURVE = validateOpts(curveDef);
|
||||
const { P, type, adjustScalarBytes, powPminus2 } = CURVE;
|
||||
const is25519 = type === 'x25519';
|
||||
if (!is25519 && type !== 'x448')
|
||||
throw new Error('invalid type');
|
||||
const montgomeryBits = is25519 ? 255 : 448;
|
||||
const fieldLen = is25519 ? 32 : 56;
|
||||
const Gu = is25519 ? BigInt(9) : BigInt(5);
|
||||
// RFC 7748 #5:
|
||||
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and
|
||||
// (156326 - 2) / 4 = 39081 for curve448/X448
|
||||
// const a = is25519 ? 156326n : 486662n;
|
||||
const a24 = is25519 ? BigInt(121665) : BigInt(39081);
|
||||
// RFC: x25519 "the resulting integer is of the form 2^254 plus
|
||||
// eight times a value between 0 and 2^251 - 1 (inclusive)"
|
||||
// x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)"
|
||||
const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);
|
||||
const maxAdded = is25519
|
||||
? BigInt(8) * _2n ** BigInt(251) - _1n
|
||||
: BigInt(4) * _2n ** BigInt(445) - _1n;
|
||||
const maxScalar = minScalar + maxAdded + _1n; // (inclusive)
|
||||
const modP = (n) => (0, modular_ts_1.mod)(n, P);
|
||||
const GuBytes = encodeU(Gu);
|
||||
function encodeU(u) {
|
||||
return (0, utils_ts_1.numberToBytesLE)(modP(u), fieldLen);
|
||||
}
|
||||
function decodeU(u) {
|
||||
const _u = (0, utils_ts_1.ensureBytes)('u coordinate', u, fieldLen);
|
||||
// RFC: When receiving such an array, implementations of X25519
|
||||
// (but not X448) MUST mask the most significant bit in the final byte.
|
||||
if (is25519)
|
||||
_u[31] &= 127; // 0b0111_1111
|
||||
// RFC: Implementations MUST accept non-canonical values and process them as
|
||||
// if they had been reduced modulo the field prime. The non-canonical
|
||||
// values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224
|
||||
// - 1 through 2^448 - 1 for X448.
|
||||
return modP((0, utils_ts_1.bytesToNumberLE)(_u));
|
||||
}
|
||||
function decodeScalar(scalar) {
|
||||
return (0, utils_ts_1.bytesToNumberLE)(adjustScalarBytes((0, utils_ts_1.ensureBytes)('scalar', scalar, fieldLen)));
|
||||
}
|
||||
function scalarMult(scalar, u) {
|
||||
const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
|
||||
// Some public keys are useless, of low-order. Curve author doesn't think
|
||||
// it needs to be validated, but we do it nonetheless.
|
||||
// https://cr.yp.to/ecdh.html#validate
|
||||
if (pu === _0n)
|
||||
throw new Error('invalid private or public key received');
|
||||
return encodeU(pu);
|
||||
}
|
||||
// Computes public key from private. By doing scalar multiplication of base point.
|
||||
function scalarMultBase(scalar) {
|
||||
return scalarMult(scalar, GuBytes);
|
||||
}
|
||||
// cswap from RFC7748 "example code"
|
||||
function cswap(swap, x_2, x_3) {
|
||||
// dummy = mask(swap) AND (x_2 XOR x_3)
|
||||
// Where mask(swap) is the all-1 or all-0 word of the same length as x_2
|
||||
// and x_3, computed, e.g., as mask(swap) = 0 - swap.
|
||||
const dummy = modP(swap * (x_2 - x_3));
|
||||
x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy
|
||||
x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy
|
||||
return { x_2, x_3 };
|
||||
}
|
||||
/**
|
||||
* Montgomery x-only multiplication ladder.
|
||||
* @param pointU u coordinate (x) on Montgomery Curve 25519
|
||||
* @param scalar by which the point would be multiplied
|
||||
* @returns new Point on Montgomery curve
|
||||
*/
|
||||
function montgomeryLadder(u, scalar) {
|
||||
(0, utils_ts_1.aInRange)('u', u, _0n, P);
|
||||
(0, utils_ts_1.aInRange)('scalar', scalar, minScalar, maxScalar);
|
||||
const k = scalar;
|
||||
const x_1 = u;
|
||||
let x_2 = _1n;
|
||||
let z_2 = _0n;
|
||||
let x_3 = u;
|
||||
let z_3 = _1n;
|
||||
let swap = _0n;
|
||||
for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
|
||||
const k_t = (k >> t) & _1n;
|
||||
swap ^= k_t;
|
||||
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
||||
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
||||
swap = k_t;
|
||||
const A = x_2 + z_2;
|
||||
const AA = modP(A * A);
|
||||
const B = x_2 - z_2;
|
||||
const BB = modP(B * B);
|
||||
const E = AA - BB;
|
||||
const C = x_3 + z_3;
|
||||
const D = x_3 - z_3;
|
||||
const DA = modP(D * A);
|
||||
const CB = modP(C * B);
|
||||
const dacb = DA + CB;
|
||||
const da_cb = DA - CB;
|
||||
x_3 = modP(dacb * dacb);
|
||||
z_3 = modP(x_1 * modP(da_cb * da_cb));
|
||||
x_2 = modP(AA * BB);
|
||||
z_2 = modP(E * (AA + modP(a24 * E)));
|
||||
}
|
||||
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
||||
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
||||
const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent
|
||||
return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))
|
||||
}
|
||||
return {
|
||||
scalarMult,
|
||||
scalarMultBase,
|
||||
getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),
|
||||
getPublicKey: (privateKey) => scalarMultBase(privateKey),
|
||||
utils: { randomPrivateKey: () => CURVE.randomBytes(fieldLen) },
|
||||
GuBytes: GuBytes.slice(),
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=montgomery.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+76
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
|
||||
*
|
||||
* There are many poseidon variants with different constants.
|
||||
* We don't provide them: you should construct them manually.
|
||||
* Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type IField } from './modular.ts';
|
||||
export type PoseidonBasicOpts = {
|
||||
Fp: IField<bigint>;
|
||||
t: number;
|
||||
roundsFull: number;
|
||||
roundsPartial: number;
|
||||
isSboxInverse?: boolean;
|
||||
};
|
||||
export type PoseidonGrainOpts = PoseidonBasicOpts & {
|
||||
sboxPower?: number;
|
||||
};
|
||||
type PoseidonConstants = {
|
||||
mds: bigint[][];
|
||||
roundConstants: bigint[][];
|
||||
};
|
||||
export declare function grainGenConstants(opts: PoseidonGrainOpts, skipMDS?: number): PoseidonConstants;
|
||||
export type PoseidonOpts = PoseidonBasicOpts & PoseidonConstants & {
|
||||
sboxPower?: number;
|
||||
reversePartialPowIdx?: boolean;
|
||||
};
|
||||
export declare function validateOpts(opts: PoseidonOpts): Readonly<{
|
||||
rounds: number;
|
||||
sboxFn: (n: bigint) => bigint;
|
||||
roundConstants: bigint[][];
|
||||
mds: bigint[][];
|
||||
Fp: IField<bigint>;
|
||||
t: number;
|
||||
roundsFull: number;
|
||||
roundsPartial: number;
|
||||
sboxPower?: number;
|
||||
reversePartialPowIdx?: boolean;
|
||||
}>;
|
||||
export declare function splitConstants(rc: bigint[], t: number): bigint[][];
|
||||
/** Poseidon NTT-friendly hash. */
|
||||
export declare function poseidon(opts: PoseidonOpts): {
|
||||
(values: bigint[]): bigint[];
|
||||
roundConstants: bigint[][];
|
||||
};
|
||||
export declare class PoseidonSponge {
|
||||
private Fp;
|
||||
readonly rate: number;
|
||||
readonly capacity: number;
|
||||
readonly hash: ReturnType<typeof poseidon>;
|
||||
private state;
|
||||
private pos;
|
||||
private isAbsorbing;
|
||||
constructor(Fp: IField<bigint>, rate: number, capacity: number, hash: ReturnType<typeof poseidon>);
|
||||
private process;
|
||||
absorb(input: bigint[]): void;
|
||||
squeeze(count: number): bigint[];
|
||||
clean(): void;
|
||||
clone(): PoseidonSponge;
|
||||
}
|
||||
export type PoseidonSpongeOpts = Omit<PoseidonOpts, 't'> & {
|
||||
rate: number;
|
||||
capacity: number;
|
||||
};
|
||||
/**
|
||||
* The method is not defined in spec, but nevertheless used often.
|
||||
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
|
||||
* We cross-test against:
|
||||
* - https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms
|
||||
* - https://github.com/arkworks-rs/crypto-primitives/tree/main
|
||||
*/
|
||||
export declare function poseidonSponge(opts: PoseidonSpongeOpts): () => PoseidonSponge;
|
||||
export {};
|
||||
//# sourceMappingURL=poseidon.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"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"}
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PoseidonSponge = void 0;
|
||||
exports.grainGenConstants = grainGenConstants;
|
||||
exports.validateOpts = validateOpts;
|
||||
exports.splitConstants = splitConstants;
|
||||
exports.poseidon = poseidon;
|
||||
exports.poseidonSponge = poseidonSponge;
|
||||
/**
|
||||
* Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
|
||||
*
|
||||
* There are many poseidon variants with different constants.
|
||||
* We don't provide them: you should construct them manually.
|
||||
* Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf
|
||||
function grainLFSR(state) {
|
||||
let pos = 0;
|
||||
if (state.length !== 80)
|
||||
throw new Error('grainLFRS: wrong state length, should be 80 bits');
|
||||
const getBit = () => {
|
||||
const r = (offset) => state[(pos + offset) % 80];
|
||||
const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0);
|
||||
state[pos] = bit;
|
||||
pos = ++pos % 80;
|
||||
return !!bit;
|
||||
};
|
||||
for (let i = 0; i < 160; i++)
|
||||
getBit();
|
||||
return () => {
|
||||
// https://en.wikipedia.org/wiki/Shrinking_generator
|
||||
while (true) {
|
||||
const b1 = getBit();
|
||||
const b2 = getBit();
|
||||
if (!b1)
|
||||
continue;
|
||||
return b2;
|
||||
}
|
||||
};
|
||||
}
|
||||
function validateBasicOpts(opts) {
|
||||
const { Fp, roundsFull } = opts;
|
||||
(0, modular_ts_1.validateField)(Fp);
|
||||
for (const i of ['t', 'roundsFull', 'roundsPartial']) {
|
||||
if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
|
||||
throw new Error('invalid number ' + i);
|
||||
}
|
||||
if (opts.isSboxInverse !== undefined && typeof opts.isSboxInverse !== 'boolean')
|
||||
throw new Error(`Poseidon: invalid param isSboxInverse=${opts.isSboxInverse}`);
|
||||
if (roundsFull & 1)
|
||||
throw new Error('roundsFull is not even' + roundsFull);
|
||||
}
|
||||
function poseidonGrain(opts) {
|
||||
validateBasicOpts(opts);
|
||||
const { Fp } = opts;
|
||||
const state = Array(80).fill(1);
|
||||
let pos = 0;
|
||||
const writeBits = (value, bitCount) => {
|
||||
for (let i = bitCount - 1; i >= 0; i--)
|
||||
state[pos++] = Number((0, utils_ts_1.bitGet)(value, i));
|
||||
};
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
writeBits(_1n, 2); // prime field
|
||||
writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5
|
||||
writeBits(BigInt(Fp.BITS), 12); // b6..b17
|
||||
writeBits(BigInt(opts.t), 12); // b18..b29
|
||||
writeBits(BigInt(opts.roundsFull), 10); // b30..b39
|
||||
writeBits(BigInt(opts.roundsPartial), 10); // b40..b49
|
||||
const getBit = grainLFSR(state);
|
||||
return (count, reject) => {
|
||||
const res = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
while (true) {
|
||||
let num = _0n;
|
||||
for (let i = 0; i < Fp.BITS; i++) {
|
||||
num <<= _1n;
|
||||
if (getBit())
|
||||
num |= _1n;
|
||||
}
|
||||
if (reject && num >= Fp.ORDER)
|
||||
continue; // rejection sampling
|
||||
res.push(Fp.create(num));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
// NOTE: this is not standard but used often for constant generation for poseidon
|
||||
// (grain LFRS-like structure)
|
||||
function grainGenConstants(opts, skipMDS = 0) {
|
||||
const { Fp, t, roundsFull, roundsPartial } = opts;
|
||||
const rounds = roundsFull + roundsPartial;
|
||||
const sample = poseidonGrain(opts);
|
||||
const roundConstants = [];
|
||||
for (let r = 0; r < rounds; r++)
|
||||
roundConstants.push(sample(t, true));
|
||||
if (skipMDS > 0)
|
||||
for (let i = 0; i < skipMDS; i++)
|
||||
sample(2 * t, false);
|
||||
const xs = sample(t, false);
|
||||
const ys = sample(t, false);
|
||||
// Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j])
|
||||
const mds = [];
|
||||
for (let i = 0; i < t; i++) {
|
||||
const row = [];
|
||||
for (let j = 0; j < t; j++) {
|
||||
const xy = Fp.add(xs[i], ys[j]);
|
||||
if (Fp.is0(xy))
|
||||
throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`);
|
||||
row.push(xy);
|
||||
}
|
||||
mds.push((0, modular_ts_1.FpInvertBatch)(Fp, row));
|
||||
}
|
||||
return { roundConstants, mds };
|
||||
}
|
||||
function validateOpts(opts) {
|
||||
validateBasicOpts(opts);
|
||||
const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
|
||||
const { roundsFull, roundsPartial, sboxPower, t } = opts;
|
||||
// MDS is TxT matrix
|
||||
if (!Array.isArray(mds) || mds.length !== t)
|
||||
throw new Error('Poseidon: invalid MDS matrix');
|
||||
const _mds = mds.map((mdsRow) => {
|
||||
if (!Array.isArray(mdsRow) || mdsRow.length !== t)
|
||||
throw new Error('invalid MDS matrix row: ' + mdsRow);
|
||||
return mdsRow.map((i) => {
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('invalid MDS matrix bigint: ' + i);
|
||||
return Fp.create(i);
|
||||
});
|
||||
});
|
||||
if (rev !== undefined && typeof rev !== 'boolean')
|
||||
throw new Error('invalid param reversePartialPowIdx=' + rev);
|
||||
if (roundsFull & 1)
|
||||
throw new Error('roundsFull is not even' + roundsFull);
|
||||
const rounds = roundsFull + roundsPartial;
|
||||
if (!Array.isArray(rc) || rc.length !== rounds)
|
||||
throw new Error('Poseidon: invalid round constants');
|
||||
const roundConstants = rc.map((rc) => {
|
||||
if (!Array.isArray(rc) || rc.length !== t)
|
||||
throw new Error('invalid round constants');
|
||||
return rc.map((i) => {
|
||||
if (typeof i !== 'bigint' || !Fp.isValid(i))
|
||||
throw new Error('invalid round constant');
|
||||
return Fp.create(i);
|
||||
});
|
||||
});
|
||||
if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower))
|
||||
throw new Error('invalid sboxPower');
|
||||
const _sboxPower = BigInt(sboxPower);
|
||||
let sboxFn = (n) => (0, modular_ts_1.FpPow)(Fp, n, _sboxPower);
|
||||
// Unwrapped sbox power for common cases (195->142μs)
|
||||
if (sboxPower === 3)
|
||||
sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
|
||||
else if (sboxPower === 5)
|
||||
sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
|
||||
return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds });
|
||||
}
|
||||
function splitConstants(rc, t) {
|
||||
if (typeof t !== 'number')
|
||||
throw new Error('poseidonSplitConstants: invalid t');
|
||||
if (!Array.isArray(rc) || rc.length % t)
|
||||
throw new Error('poseidonSplitConstants: invalid rc');
|
||||
const res = [];
|
||||
let tmp = [];
|
||||
for (let i = 0; i < rc.length; i++) {
|
||||
tmp.push(rc[i]);
|
||||
if (tmp.length === t) {
|
||||
res.push(tmp);
|
||||
tmp = [];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/** Poseidon NTT-friendly hash. */
|
||||
function poseidon(opts) {
|
||||
const _opts = validateOpts(opts);
|
||||
const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts;
|
||||
const halfRoundsFull = _opts.roundsFull / 2;
|
||||
const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
|
||||
const poseidonRound = (values, isFull, idx) => {
|
||||
values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
|
||||
if (isFull)
|
||||
values = values.map((i) => sboxFn(i));
|
||||
else
|
||||
values[partialIdx] = sboxFn(values[partialIdx]);
|
||||
// Matrix multiplication
|
||||
values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
|
||||
return values;
|
||||
};
|
||||
const poseidonHash = function poseidonHash(values) {
|
||||
if (!Array.isArray(values) || values.length !== t)
|
||||
throw new Error('invalid values, expected array of bigints with length ' + t);
|
||||
values = values.map((i) => {
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('invalid bigint=' + i);
|
||||
return Fp.create(i);
|
||||
});
|
||||
let lastRound = 0;
|
||||
// Apply r_f/2 full rounds.
|
||||
for (let i = 0; i < halfRoundsFull; i++)
|
||||
values = poseidonRound(values, true, lastRound++);
|
||||
// Apply r_p partial rounds.
|
||||
for (let i = 0; i < roundsPartial; i++)
|
||||
values = poseidonRound(values, false, lastRound++);
|
||||
// Apply r_f/2 full rounds.
|
||||
for (let i = 0; i < halfRoundsFull; i++)
|
||||
values = poseidonRound(values, true, lastRound++);
|
||||
if (lastRound !== totalRounds)
|
||||
throw new Error('invalid number of rounds');
|
||||
return values;
|
||||
};
|
||||
// For verification in tests
|
||||
poseidonHash.roundConstants = roundConstants;
|
||||
return poseidonHash;
|
||||
}
|
||||
class PoseidonSponge {
|
||||
constructor(Fp, rate, capacity, hash) {
|
||||
this.pos = 0;
|
||||
this.isAbsorbing = true;
|
||||
this.Fp = Fp;
|
||||
this.hash = hash;
|
||||
this.rate = rate;
|
||||
this.capacity = capacity;
|
||||
this.state = new Array(rate + capacity);
|
||||
this.clean();
|
||||
}
|
||||
process() {
|
||||
this.state = this.hash(this.state);
|
||||
}
|
||||
absorb(input) {
|
||||
for (const i of input)
|
||||
if (typeof i !== 'bigint' || !this.Fp.isValid(i))
|
||||
throw new Error('invalid input: ' + i);
|
||||
for (let i = 0; i < input.length;) {
|
||||
if (!this.isAbsorbing || this.pos === this.rate) {
|
||||
this.process();
|
||||
this.pos = 0;
|
||||
this.isAbsorbing = true;
|
||||
}
|
||||
const chunk = Math.min(this.rate - this.pos, input.length - i);
|
||||
for (let j = 0; j < chunk; j++) {
|
||||
const idx = this.capacity + this.pos++;
|
||||
this.state[idx] = this.Fp.add(this.state[idx], input[i++]);
|
||||
}
|
||||
}
|
||||
}
|
||||
squeeze(count) {
|
||||
const res = [];
|
||||
while (res.length < count) {
|
||||
if (this.isAbsorbing || this.pos === this.rate) {
|
||||
this.process();
|
||||
this.pos = 0;
|
||||
this.isAbsorbing = false;
|
||||
}
|
||||
const chunk = Math.min(this.rate - this.pos, count - res.length);
|
||||
for (let i = 0; i < chunk; i++)
|
||||
res.push(this.state[this.capacity + this.pos++]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
clean() {
|
||||
this.state.fill(this.Fp.ZERO);
|
||||
this.isAbsorbing = true;
|
||||
this.pos = 0;
|
||||
}
|
||||
clone() {
|
||||
const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash);
|
||||
c.pos = this.pos;
|
||||
c.state = [...this.state];
|
||||
return c;
|
||||
}
|
||||
}
|
||||
exports.PoseidonSponge = PoseidonSponge;
|
||||
/**
|
||||
* The method is not defined in spec, but nevertheless used often.
|
||||
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
|
||||
* We cross-test against:
|
||||
* - https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms
|
||||
* - https://github.com/arkworks-rs/crypto-primitives/tree/main
|
||||
*/
|
||||
function poseidonSponge(opts) {
|
||||
for (const i of ['rate', 'capacity']) {
|
||||
if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
|
||||
throw new Error('invalid number ' + i);
|
||||
}
|
||||
const { rate, capacity } = opts;
|
||||
const t = opts.rate + opts.capacity;
|
||||
// Re-use hash instance between multiple instances
|
||||
const hash = poseidon({ ...opts, t });
|
||||
const { Fp } = opts;
|
||||
return () => new PoseidonSponge(Fp, rate, capacity, hash);
|
||||
}
|
||||
//# sourceMappingURL=poseidon.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user