Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CashuWallet.checkProofsStates() #199

Merged
merged 11 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions migration-2.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export type OutputAmounts = {
};
```

#### `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`
Expand Down
41 changes: 26 additions & 15 deletions src/CashuWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ import {
type SerializedBlindedMessage,
type SwapPayload,
type Token,
CheckStateEnum,
SerializedBlindedSignature,
GetInfoResponse,
OutputAmounts,
CheckStateEntry,
ProofState,
BlindingData
} from './model/types/index.js';
import { bytesToNumber, getDecodedToken, splitAmount, sumProofs, getKeepAmounts } from './utils.js';
Expand Down Expand Up @@ -841,24 +840,36 @@ class CashuWallet {
};
return { payload, blindingData };
}

/**
* returns proofs that are already spent (use for keeping wallet state clean)
* 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
*/
async checkProofsSpent<T extends { secret: string }>(proofs: Array<T>): Promise<Array<T>> {
async checkProofsStates(proofs: Array<Proof>): Promise<Array<ProofState>> {
const enc = new TextEncoder();
const Ys = proofs.map((p: T) => hashToCurve(enc.encode(p.secret)).toHex(true));
const payload = {
// array of Ys of proofs to check
Ys: Ys
};
const { states } = await this.mint.check(payload);

return proofs.filter((_: T, i: number) => {
const state = states.find((state: CheckStateEntry) => state.Y === Ys[i]);
return state && state.state === CheckStateEnum.SPENT;
});
const Ys = proofs.map((p: Proof) => hashToCurve(enc.encode(p.secret)).toHex(true));
// TODO: Replace this with a value from the info endpoint of the mint eventually
const BATCH_SIZE = 100;
const states: Array<ProofState> = [];
for (let i = 0; i < Ys.length; i += BATCH_SIZE) {
const YsSlice = Ys.slice(i, i + BATCH_SIZE);
const { states: batchStates } = await this.mint.check({
Ys: YsSlice
});
const stateMap: { [y: string]: ProofState } = {};
batchStates.forEach((s) => {
stateMap[s.Y] = s;
});
for (let j = 0; j < YsSlice.length; j++) {
const state = stateMap[YsSlice[j]];
if (!state) {
throw new Error('Could not find state for proof with Y: ' + YsSlice[j]);
}
states.push(state);
}
}
return states;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/model/types/mint/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export type ApiError = {
/**
* Entries of CheckStateResponse with state of the proof
*/
export type CheckStateEntry = {
export type ProofState = {
Y: string;
state: CheckStateEnum;
witness: string | null;
Expand All @@ -43,7 +43,7 @@ export type CheckStateResponse = {
/**
*
*/
states: Array<CheckStateEntry>;
states: Array<ProofState>;
} & ApiError;

/**
Expand Down
42 changes: 27 additions & 15 deletions test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import dns from 'node:dns';
import { deriveKeysetId, getEncodedToken, sumProofs } from '../src/utils.js';
import { secp256k1 } from '@noble/curves/secp256k1';
import { bytesToHex } from '@noble/curves/abstract/utils';
import { MeltQuoteState } from '../src/model/types/index.js';
import { CheckStateEnum, MeltQuoteState } from '../src/model/types/index.js';
dns.setDefaultResultOrder('ipv4first');

const externalInvoice =
Expand Down Expand Up @@ -100,14 +100,20 @@ describe('mint api', () => {
expect(response.change.reduce((a, b) => a + b.amount, 0)).toBe(fee);

// check states of spent and kept proofs after payment
const sentProofsSpent = await wallet.checkProofsSpent(sendResponse.send);
expect(sentProofsSpent).toBeDefined();
// expect that all proofs are spent, i.e. sendProofsSpent == sendResponse.send
expect(sentProofsSpent).toEqual(sendResponse.send);
const sentProofsStates = await wallet.checkProofsStates(sendResponse.send);
expect(sentProofsStates).toBeDefined();
// expect that all proofs are spent, i.e. all are CheckStateEnum.SPENT
sentProofsStates.forEach((state) => {
expect(state.state).toBe(CheckStateEnum.SPENT);
expect(state.witness).toBeNull();
});
// expect none of the sendResponse.keep to be spent
const keepSpent = await wallet.checkProofsSpent(sendResponse.keep);
expect(keepSpent).toBeDefined();
expect(keepSpent).toEqual([]);
const keepProofsStates = await wallet.checkProofsStates(sendResponse.keep);
expect(keepProofsStates).toBeDefined();
keepProofsStates.forEach((state) => {
expect(state.state).toBe(CheckStateEnum.UNSPENT);
expect(state.witness).toBeNull();
});
});
test('pay external invoice', async () => {
const mint = new CashuMint(mintUrl);
Expand All @@ -131,14 +137,20 @@ describe('mint api', () => {
expect(response.change.reduce((a, b) => a + b.amount, 0)).toBeLessThan(fee);

// check states of spent and kept proofs after payment
const sentProofsSpent = await wallet.checkProofsSpent(sendResponse.send);
expect(sentProofsSpent).toBeDefined();
// expect that all proofs are spent, i.e. sendProofsSpent == sendResponse.send
expect(sentProofsSpent).toEqual(sendResponse.send);
const sentProofsStates = await wallet.checkProofsStates(sendResponse.send);
expect(sentProofsStates).toBeDefined();
// expect that all proofs are spent, i.e. all are CheckStateEnum.SPENT
sentProofsStates.forEach((state) => {
expect(state.state).toBe(CheckStateEnum.SPENT);
expect(state.witness).toBeNull();
});
// expect none of the sendResponse.keep to be spent
const keepSpent = await wallet.checkProofsSpent(sendResponse.keep);
expect(keepSpent).toBeDefined();
expect(keepSpent).toEqual([]);
const keepProofsStates = await wallet.checkProofsStates(sendResponse.keep);
expect(keepProofsStates).toBeDefined();
keepProofsStates.forEach((state) => {
expect(state.state).toBe(CheckStateEnum.UNSPENT);
expect(state.witness).toBeNull();
});
});
test('test send tokens exact without previous split', async () => {
const mint = new CashuMint(mintUrl);
Expand Down
24 changes: 17 additions & 7 deletions test/wallet.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import nock from 'nock';
import { CashuMint } from '../src/CashuMint.js';
import { CashuWallet } from '../src/CashuWallet.js';
import { MeltQuoteResponse } from '../src/model/types/index.js';
import { CheckStateEnum, MeltQuoteResponse } from '../src/model/types/index.js';
import { getDecodedToken } from '../src/utils.js';

const dummyKeysResp = {
Expand Down Expand Up @@ -203,7 +203,7 @@ describe('receive', () => {
});
});

describe('checkProofsSpent', () => {
describe('checkProofsStates', () => {
const proofs = [
{
id: '009a1f293253e41e',
Expand All @@ -212,15 +212,25 @@ describe('checkProofsSpent', () => {
C: '034268c0bd30b945adf578aca2dc0d1e26ef089869aaf9a08ba3a6da40fda1d8be'
}
];
test('test checkProofsSpent - get proofs that are NOT spendable', async () => {
test('test checkProofsStates - get proofs that are NOT spendable', async () => {
nock(mintUrl)
.post('/v1/checkstate')
.reply(200, { states: [{ Y: 'asd', state: 'UNSPENT', witness: 'witness-asd' }] });
.reply(200, {
states: [
{
Y: '02d5dd71f59d917da3f73defe997928e9459e9d67d8bdb771e4989c2b5f50b2fff',
state: 'UNSPENT',
witness: 'witness-asd'
}
]
});
const wallet = new CashuWallet(mint, { unit });

const result = await wallet.checkProofsSpent(proofs);

expect(result).toStrictEqual([]);
const result = await wallet.checkProofsStates(proofs);
result.forEach((r) => {
expect(r.state).toEqual(CheckStateEnum.UNSPENT);
expect(r.witness).toEqual('witness-asd');
});
});
});

Expand Down
Loading