taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 2611fd2c934d8d3f33b2f5887a51ed9fd465fb92
parent b5dc3726cd0f5f5d880abfe7e1bb8814a95c5e12
Author: Özgür Kesim <oec@codeblau.de>
Date:   Sat, 21 Nov 2026 14:34:59 +0100

wallet-core: recover refreshed coins from REVEAL history entries

Support the coin history entry type "REVEAL" (CoinRevealTransaction):
appended by the exchange on the first successful /reveal-melt, it carries
rc, the blinded signatures of the fresh coins of the batch at
noreveal_index and, for Clause-Schnorr, the R-values.

- taler-util: CoinRevealTransaction and its codec; MELT entries parse the
  v46 fields noreveal_index and transfer_pubs.  The blinded denomination
  signature codecs, the R-pair codec and DenomKeyType move from
  types-taler-exchange.ts to types-taler-common.ts, where the history
  codecs use them, so that the two modules do not import each other at
  runtime.
- History validation: a REVEAL entry changes no balance and must follow a
  MELT entry with the same rc, once, with one signature (and R-value slot)
  per fresh coin.
- Recovery: with a REVEAL entry, the fresh coins are derived from
  ECDH(old coin private key, transfer_pubs[i]) and unblinded from the
  entry's signatures, without melt or reveal requests.  This also works
  when another holder of the old coin melted with batch seeds this wallet
  cannot derive.  Without a REVEAL entry, the existing replay path is
  unchanged.  Recovered coins record the revealed batch for batch recoup
  (the melt's rc and the batch's envelope hashes) on either path.
- Tests: codec, validation, the ECDH derivation against libtalerutil test
  vectors (RSA and CS), and recovery with real blinded signatures.

Issue: https://bugs.gnunet.org/view?id=12236

Diffstat:
Mpackages/taler-util/src/taler-crypto.ts | 8++++----
Mpackages/taler-util/src/types-donau.ts | 2+-
Mpackages/taler-util/src/types-taler-common.test.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-util/src/types-taler-common.ts | 118++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-util/src/types-taler-exchange.ts | 59+++--------------------------------------------------------
Mpackages/taler-util/src/types-taler-merchant.ts | 3+--
Mpackages/taler-util/src/types-taler-wallet.ts | 2+-
Mpackages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mpackages/taler-wallet-core/src/crypto/cryptoImplementation.ts | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mpackages/taler-wallet-core/src/crypto/cryptoTypes.ts | 28++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/exchange-signatures.test.ts | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/exchange-signatures.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/refresh.test.ts | 28++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/refresh.ts | 4++++
Mpackages/taler-wallet-core/src/testing-check-coins.ts | 19+++++++++++++------
Mpackages/taler-wallet-core/src/testing-recover-coins.test.ts | 323++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/testing-recover-coins.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
17 files changed, 1215 insertions(+), 140 deletions(-)

diff --git a/packages/taler-util/src/taler-crypto.ts b/packages/taler-util/src/taler-crypto.ts @@ -34,12 +34,12 @@ import { Logger } from "./logging.js"; import { randomBytes } from "./prng.js"; import { TalerSignaturePurpose } from "./taler_signatures.js"; import { TalerProtocolDuration, TalerProtocolTimestamp } from "./time.js"; -import { CoinPublicKeyString, HashCodeString } from "./types-taler-common.js"; import { - CoinEnvelope, + CoinPublicKeyString, + HashCodeString, DenomKeyType, - DenominationPubKey, -} from "./types-taler-exchange.js"; +} from "./types-taler-common.js"; +import { CoinEnvelope, DenominationPubKey } from "./types-taler-exchange.js"; import { TokenEnvelope, TokenIssuePublicKey } from "./types-taler-merchant.js"; import { PayWalletData } from "./types-taler-wallet.js"; import { diff --git a/packages/taler-util/src/types-donau.ts b/packages/taler-util/src/types-donau.ts @@ -46,8 +46,8 @@ import { RsaPublicKeyString, RsaSignature, AmountString, + DenomKeyType, } from "./types-taler-common.js"; -import { DenomKeyType } from "./types-taler-exchange.js"; import { assertUnreachable } from "./errors.js"; import { decodeCrock, encodeCrock, hash } from "./taler-crypto.js"; diff --git a/packages/taler-util/src/types-taler-common.test.ts b/packages/taler-util/src/types-taler-common.test.ts @@ -269,3 +269,77 @@ for (const type of ["RECOUP-WITHDRAW", "RECOUP-REFRESH"] as const) { ); }); } + +test("v46 melt history carries the revealed batch's transfer keys", () => { + const decoded = common.codecForCoinHistoryResponse().decode({ + balance: "KUDOS:0", + h_denom_pub: "denom-hash", + history: [ + { + type: "MELT", + history_offset: 0, + amount: "KUDOS:1", + melt_fee: "KUDOS:0.01", + rc: "refresh-commitment", + h_denom_pub: "denom-hash", + refresh_seed: "seed", + denoms_h: ["d1", "d2"], + noreveal_index: 2, + transfer_pubs: ["t1", "t2"], + coin_sig: "coin-signature", + }, + ], + }); + const melt = decoded.history[0]; + assert.strictEqual(melt.type, "MELT"); + assert.strictEqual(melt.noreveal_index, 2); + assert.deepStrictEqual(melt.transfer_pubs, ["t1", "t2"]); +}); + +test("reveal history entry carries the blinded signatures", () => { + const reveal = { + type: "REVEAL", + history_offset: 1, + rc: "refresh-commitment", + ev_sigs: [ + { cipher: "RSA", blinded_rsa_signature: "rsa-sig" }, + { cipher: "CS", b: 1, s: "cs-s" }, + ], + cs_r_values: [null, ["r0", "r1"]], + }; + const response = { + balance: "KUDOS:0", + h_denom_pub: "denom-hash", + history: [reveal], + }; + const decoded = common.codecForCoinHistoryResponse().decode(response); + const item = decoded.history[0]; + assert.strictEqual(item.type, "REVEAL"); + assert.strictEqual(item.rc, "refresh-commitment"); + assert.deepStrictEqual(item.ev_sigs, reveal.ev_sigs); + assert.deepStrictEqual(item.cs_r_values, [null, ["r0", "r1"]]); + // The R-values are optional. + const withoutR: Partial<typeof reveal> = { ...reveal }; + delete withoutR.cs_r_values; + const decodedWithoutR = common.codecForCoinHistoryResponse().decode({ + ...response, + history: [withoutR], + }); + assert.strictEqual(decodedWithoutR.history[0].type, "REVEAL"); + assert.strictEqual( + (decodedWithoutR.history[0] as common.CoinRevealTransaction).cs_r_values, + undefined, + ); + for (const bad of [ + { ...reveal, rc: undefined }, + { ...reveal, ev_sigs: [{ cipher: "RSA" }] }, + { ...reveal, ev_sigs: [{ cipher: "UNKNOWN", sig: "x" }] }, + { ...reveal, cs_r_values: [["r0"]] }, + ]) { + assert.throws(() => + common + .codecForCoinHistoryResponse() + .decode({ ...response, history: [bad] }), + ); + } +}); diff --git a/packages/taler-util/src/types-taler-common.ts b/packages/taler-util/src/types-taler-common.ts @@ -34,17 +34,23 @@ import { DecodingError, buildCodecForObject, buildCodecForUnion, + codecForConstString, + renderContext, codecForBoolean, codecForList, codecForMap, codecForNumber, codecForCanonicalBaseUrlString, - codecForConstString, codecForHttpUrlString, codecForString, codecOptional, } from "./codec.js"; import { EddsaPrivP } from "./taler-crypto.js"; +import type { + BlindedDenominationSignature, + CSBlindedDenominationSignature, + RsaBlindedDenominationSignature, +} from "./types-taler-exchange.js"; import { TalerProtocolDuration, TalerProtocolTimestamp, @@ -304,10 +310,37 @@ export interface CoinMeltTransaction extends CoinHistoryItemCommon { blinding_seed?: string; /** Ordered output denominations, including duplicates. Absent on older exchanges. */ denoms_h?: string[]; + /** Added in exchange protocol v46. */ + noreveal_index?: Integer; + /** + * Transfer public keys of the batch at noreveal_index, one per fresh coin. + * Added in exchange protocol v46; absent for melts without transfer keys. + */ + transfer_pubs?: EddsaPublicKeyString[]; h_age_commitment?: HashCodeString; coin_sig: EddsaSignatureString; } +/** + * Appended by the first successful reveal of the melt with the same rc. + * Does not change the coin's balance. Added in exchange protocol v46. + */ +export interface CoinRevealTransaction extends CoinHistoryItemCommon { + type: "REVEAL"; + /** Equals the rc of the corresponding MELT entry. */ + rc: HashCodeString; + /** + * Blinded signatures over the fresh coins of the batch at noreveal_index, + * in the order of the MELT entry's denoms_h. + */ + ev_sigs: BlindedDenominationSignature[]; + /** + * Per fresh coin, the R-values the exchange used for a Clause-Schnorr + * denomination, null for other ciphers. + */ + cs_r_values?: ([CsRPublic, CsRPublic] | null)[]; +} + export interface CoinRefundTransaction extends CoinHistoryItemCommon { type: "REFUND"; amount: AmountString; @@ -382,6 +415,7 @@ export interface CoinReserveOpenDepositTransaction extends CoinHistoryItemCommon export type CoinSpendHistoryItem = | CoinDepositTransaction | CoinMeltTransaction + | CoinRevealTransaction | CoinRefundTransaction | CoinRecoupWithdrawTransaction | CoinRecoupRefreshTransaction @@ -390,6 +424,66 @@ export type CoinSpendHistoryItem = | CoinPurseRefundTransaction | CoinReserveOpenDepositTransaction; +export enum DenomKeyType { + Rsa = "RSA", + ClauseSchnorr = "CS", +} + +export namespace DenomKeyType { + export function toIntTag(t: DenomKeyType): number { + switch (t) { + case DenomKeyType.Rsa: + return 1; + case DenomKeyType.ClauseSchnorr: + return 2; + } + } +} + +export const codecForRsaBlindedDenominationSignature = + (): Codec<RsaBlindedDenominationSignature> => + buildCodecForObject<RsaBlindedDenominationSignature>() + .property("cipher", codecForConstString(DenomKeyType.Rsa)) + .property("blinded_rsa_signature", codecForString()) + .build("RsaBlindedDenominationSignature"); + +export const codecForCsBlindedDenominationSignature = + (): Codec<CSBlindedDenominationSignature> => + buildCodecForObject<CSBlindedDenominationSignature>() + .property("cipher", codecForConstString(DenomKeyType.ClauseSchnorr)) + .property("b", codecForNumber()) + .property("s", codecForString()) + .build("CSBlindedDenominationSignature"); + +export const codecForBlindedDenominationSignature = + (): Codec<BlindedDenominationSignature> => + buildCodecForUnion<BlindedDenominationSignature>() + .discriminateOn("cipher") + .alternative(DenomKeyType.Rsa, codecForRsaBlindedDenominationSignature()) + .alternative( + DenomKeyType.ClauseSchnorr, + codecForCsBlindedDenominationSignature(), + ) + .build("BlindedDenominationSignature"); + +export const codecForCsRPair = (): Codec<[string, string]> => ({ + decode(x, c) { + const values = codecForList(codecForString()).decode(x, c); + if (values.length !== 2) { + throw new DecodingError( + `expected Clause-Schnorr R-pair at ${renderContext(c)}`, + ); + } + return [values[0], values[1]]; + }, +}); + +const codecForCsRPairOrNull = (): Codec<[string, string] | null> => ({ + decode(x, c) { + return x === null ? null : codecForCsRPair().decode(x, c); + }, +}); + const rawCoinSpendHistoryItemCodec = (): Codec<CoinSpendHistoryItem> => buildCodecForUnion<CoinSpendHistoryItem>() .discriminateOn("type") @@ -426,11 +520,33 @@ const rawCoinSpendHistoryItemCodec = (): Codec<CoinSpendHistoryItem> => .property("refresh_seed", codecOptional(codecForString())) .property("blinding_seed", codecOptional(codecForString())) .property("denoms_h", codecOptional(codecForList(codecForString()))) + .property("noreveal_index", codecOptional(codecForNumber())) + .property( + "transfer_pubs", + codecOptional(codecForList(codecForString())), + ) .property("h_age_commitment", codecOptional(codecForString())) .property("coin_sig", codecForString()) .build("CoinMeltTransaction"), ) .alternative( + "REVEAL", + buildCodecForObject<CoinRevealTransaction>() + .allowExtra() + .property("history_offset", codecForNumber()) + .property("type", codecForConstString("REVEAL")) + .property("rc", codecForString()) + .property( + "ev_sigs", + codecForList(codecForBlindedDenominationSignature()), + ) + .property( + "cs_r_values", + codecOptional(codecForList(codecForCsRPairOrNull())), + ) + .build("CoinRevealTransaction"), + ) + .alternative( "REFUND", buildCodecForObject<CoinRefundTransaction>() .allowExtra() diff --git a/packages/taler-util/src/types-taler-exchange.ts b/packages/taler-util/src/types-taler-exchange.ts @@ -19,7 +19,6 @@ import { codecForAmountString } from "./amounts.js"; import { Codec, - DecodingError, buildCodecForObject, buildCodecForUnion, codecForAny, @@ -33,7 +32,6 @@ import { codecForStringURL, codecOptional, codecOptionalDefault, - renderContext, } from "./codec.js"; import { strcmp } from "./helpers.js"; import { @@ -78,6 +76,9 @@ import { codecForInternationalizedString, codecForURLString, codecForURN, + DenomKeyType, + codecForBlindedDenominationSignature, + codecForCsRPair, } from "./types-taler-common.js"; export type DenominationPubKey = RsaDenominationPubKey | CsDenominationPubKey; @@ -951,18 +952,6 @@ export interface BlindingPrepareResponse { r_pubs: [string, string][]; } -const codecForCsRPair = (): Codec<[string, string]> => ({ - decode(x, c) { - const values = codecForList(codecForString()).decode(x, c); - if (values.length !== 2) { - throw new DecodingError( - `expected Clause-Schnorr R-pair at ${renderContext(c)}`, - ); - } - return [values[0], values[1]]; - }, -}); - export const codecForBlindingPrepareResponse = (): Codec<BlindingPrepareResponse> => buildCodecForObject<BlindingPrepareResponse>() @@ -1189,48 +1178,6 @@ export interface ExchangeWithdrawResponse { ev_sigs: BlindedDenominationSignature[]; } -export enum DenomKeyType { - Rsa = "RSA", - ClauseSchnorr = "CS", -} - -export namespace DenomKeyType { - export function toIntTag(t: DenomKeyType): number { - switch (t) { - case DenomKeyType.Rsa: - return 1; - case DenomKeyType.ClauseSchnorr: - return 2; - } - } -} - -export const codecForRsaBlindedDenominationSignature = - (): Codec<RsaBlindedDenominationSignature> => - buildCodecForObject<RsaBlindedDenominationSignature>() - .property("cipher", codecForConstString(DenomKeyType.Rsa)) - .property("blinded_rsa_signature", codecForString()) - .build("RsaBlindedDenominationSignature"); - -export const codecForCsBlindedDenominationSignature = - (): Codec<CSBlindedDenominationSignature> => - buildCodecForObject<CSBlindedDenominationSignature>() - .property("cipher", codecForConstString(DenomKeyType.ClauseSchnorr)) - .property("b", codecForNumber()) - .property("s", codecForString()) - .build("CSBlindedDenominationSignature"); - -export const codecForBlindedDenominationSignature = - (): Codec<BlindedDenominationSignature> => - buildCodecForUnion<BlindedDenominationSignature>() - .discriminateOn("cipher") - .alternative(DenomKeyType.Rsa, codecForRsaBlindedDenominationSignature()) - .alternative( - DenomKeyType.ClauseSchnorr, - codecForCsBlindedDenominationSignature(), - ) - .build("BlindedDenominationSignature"); - export const codecForExchangeLegacyWithdrawBatchResponse = (): Codec<ExchangeLegacyWithdrawBatchResponse> => buildCodecForObject<ExchangeLegacyWithdrawBatchResponse>() diff --git a/packages/taler-util/src/types-taler-merchant.ts b/packages/taler-util/src/types-taler-merchant.ts @@ -42,10 +42,9 @@ import { import { assertUnreachable } from "./errors.js"; import { PaytoString, codecForPaytoString } from "./payto.js"; import { codecForTalerUriString } from "./taleruri.js"; -import { AccessToken } from "./types-taler-common.js"; +import { AccessToken, DenomKeyType } from "./types-taler-common.js"; import { AccountLimit, - DenomKeyType, UnblindedDenominationSignature, codecForAccountLimit, } from "./types-taler-exchange.js"; diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -80,11 +80,11 @@ import { RelativeTime, Timestamp, codecForEddsaPrivateKey, + DenomKeyType, } from "./types-taler-common.js"; import { AccountRestriction, CoinEnvelope, - DenomKeyType, DenominationPubKey, ExchangeAuditor, ExchangeWithdrawValue, diff --git a/packages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts b/packages/taler-wallet-core/src/crypto/cryptoImplementation.test.ts @@ -14,6 +14,7 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ import { + AgeRestriction, AmountString, Amounts, buildSigPS, @@ -855,13 +856,15 @@ test("order unclaim signs the contract hash with the wallet nonce", async () => ); }); +const refreshTestRsaDenomPub = { + cipher: DenomKeyType.Rsa as const, + rsa_public_key: + "040000XT67C8KBD6B75TTQ3SK8FWXMNQW4372T3BDDGPAMB9RFCA03638W8T3F71WFEFK9NP32VKYVNFXPYRWQ1N1HDKV5J0DFEKHBPJCYSWCBJDRNWD7G8BN8PT97FA9AMV75MYEK4X54D1HGJ207JSVJBGFCATSPNTEYNHEQF1F220W00TBZR1HNPDQFD56FG0DJQ9KGHM8EC33H6AY9YN9CNX5R3Z4TZ4Q23W47SBHB13H6W74FQJG1F50X38VRSC4SR8RWBAFB7S4K8D2H4NMRFSQT892A3T0BTBW7HM5C0H2CK6FRKG31F7W9WP1S29013K5CXYE55CT8TH6N8J9B780R42Y5S3ZB6J6E9H76XBPSGH4TGYSR2VZRB98J417KCQMZKX1BB67E7W5KVE37TC9SJ904002", + age_mask: 0, +}; + test("refresh commitment covers the transfer public keys only since v45", async () => { - const denomPub = { - cipher: DenomKeyType.Rsa as const, - rsa_public_key: - "040000XT67C8KBD6B75TTQ3SK8FWXMNQW4372T3BDDGPAMB9RFCA03638W8T3F71WFEFK9NP32VKYVNFXPYRWQ1N1HDKV5J0DFEKHBPJCYSWCBJDRNWD7G8BN8PT97FA9AMV75MYEK4X54D1HGJ207JSVJBGFCATSPNTEYNHEQF1F220W00TBZR1HNPDQFD56FG0DJQ9KGHM8EC33H6AY9YN9CNX5R3Z4TZ4Q23W47SBHB13H6W74FQJG1F50X38VRSC4SR8RWBAFB7S4K8D2H4NMRFSQT892A3T0BTBW7HM5C0H2CK6FRKG31F7W9WP1S29013K5CXYE55CT8TH6N8J9B780R42Y5S3ZB6J6E9H76XBPSGH4TGYSR2VZRB98J417KCQMZKX1BB67E7W5KVE37TC9SJ904002", - age_mask: 0, - }; + const denomPub = refreshTestRsaDenomPub; const meltCoin = createEddsaKeyPair(); const req = { kappa: 3, @@ -925,3 +928,137 @@ test("refresh commitment covers the transfer public keys only since v45", async assert.notEqual(current.hash, legacy.hash); assert.notEqual(current.confirmSig, legacy.confirmSig); }); + +// Clause-Schnorr public key and R-values of the taler-exchange-tvg vector +// "cs_blind_signing". +const csTvgDenomPub = { + cipher: DenomKeyType.ClauseSchnorr as const, + cs_public_key: "1903SZ7QE1K8T4BHTJ32KDJ153SBXT22DGNQDY5NKJE535J72H2G", + age_mask: 0, +}; +const csTvgRValues = { + cipher: DenomKeyType.ClauseSchnorr as const, + r_pub_0: "J5XFBKFP9T6BM02H6ZV6Y568PQ2K398MD339036F25XTSP1A7T3G", + r_pub_1: "GA2CZKJ6CWFS81ZN1T5R4GQFHF7XJV6HWHDR1JA9VATKKXQN89J0", +}; + +test("the old coin's private key derives the fresh coins from a batch's transfer keys", async () => { + // Values computed by libtalerutil: TALER_link_recover_transfer_secret, + // TALER_transfer_secret_to_planchet_secret for coins 0 and 1, + // TALER_planchet_setup_coin_priv and TALER_planchet_blinding_secret_create, + // with the keys of the taler-exchange-tvg vector "eddsa_ecdh". + const oldCoinPriv = "1KG54M8T3X8BSFSZXCR3SQBSR7Y9P53NX61M864S7TEVMJ2XVPF0"; + const transferPub = "FXFN5GPAFTKVPWJDPVXQ87167S8T82T5ZV8CDYC0NH2AE14X0M30"; + const expected = { + [DenomKeyType.Rsa]: [ + { + coinPriv: "XCE63MP6JF98PHF0MAXYVVJCRD6XQBH4ZA9HBYVBMDHR90HD7QG0", + blindingKey: "NAAP72WH9MAMJSZP74NGB8H2JSWXXTG8JENR679QYP1W95H2BFY0", + }, + { + coinPriv: "69AR56TR3ADAT63TMTSKFCAP3G0FWSME4C1R2M6GVRF38XEFW3KG", + blindingKey: "AB3V1RRNBCC3K6VYYDEKTA73B23YP5SS6HZH8VHW4DMZDQ42R0K0", + }, + ], + [DenomKeyType.ClauseSchnorr]: [ + { + coinPriv: "695WEJ1MCJ626CJYKVD0QHB3J4H7TVGHH3GQWHE1270EWAE8M930", + blindingKey: "WMB5CNZXT8E4F7BQKNB7EC1KB75VXP7XZVTW78XBN9P21PH16620", + }, + { + coinPriv: "280XC72WQ7316JJQ27VJ2FKT0D6N99HR54TDD5P8GB9M8CYFQHE0", + blindingKey: "K5140VYB0ZV1R0R5Y8Z7N0FTZKBXZ9K9GCR6ETQ8PV45PEBTSCFG", + }, + ], + }; + for (const denomPub of [refreshTestRsaDenomPub, csTvgDenomPub]) { + const cs = denomPub.cipher === DenomKeyType.ClauseSchnorr; + const { planchets } = await nativeCryptoR.deriveRevealedRefreshPlanchets( + nativeCryptoR, + { + meltCoinPriv: oldCoinPriv, + meltCoinMaxAge: 0, + transferPubs: [transferPub, transferPub], + newCoinDenomPubs: [denomPub, denomPub], + blindingSeed: cs ? encodeCrock(new Uint8Array(32).fill(5)) : undefined, + exchangeWithdrawValues: cs ? [csTvgRValues, csTvgRValues] : undefined, + }, + ); + assert.deepStrictEqual( + planchets.map((p) => ({ + coinPriv: p.coinPriv, + blindingKey: p.blindingKey, + })), + expected[denomPub.cipher], + ); + } +}); + +test("each refresh batch is recoverable from its transfer public keys alone", async () => { + const meltCoin = createEddsaKeyPair(); + const ageCommitmentProof = await AgeRestriction.restrictionCommit( + 1 | (1 << 8) | (1 << 10) | (1 << 12) | (1 << 14) | (1 << 16), + 14, + ); + const blindingSeed = encodeCrock(getRandomBytes(32)); + const newCoinDenoms = [ + { + count: 2, + denomPub: refreshTestRsaDenomPub, + denomPubHash: encodeCrock(hashDenomPub(refreshTestRsaDenomPub)), + feeWithdraw: "KUDOS:0.01" as AmountString, + value: "KUDOS:1" as AmountString, + }, + { + count: 1, + denomPub: csTvgDenomPub, + denomPubHash: encodeCrock(hashDenomPub(csTvgDenomPub)), + feeWithdraw: "KUDOS:0.01" as AmountString, + value: "KUDOS:2" as AmountString, + }, + ]; + const exchangeWithdrawValues = [undefined, undefined, csTvgRValues]; + for (const meltCoinAgeCommitmentProof of [undefined, ageCommitmentProof]) { + const session = await nativeCryptoR.deriveRefreshSessionV3(nativeCryptoR, { + includeTransferPubsInCommitment: true, + kappa: 3, + sessionPublicSeed: encodeCrock(getRandomBytes(64)), + meltCoinPub: encodeCrock(meltCoin.eddsaPub), + meltCoinPriv: encodeCrock(meltCoin.eddsaPriv), + meltCoinDenomPubHash: encodeCrock(new Uint8Array(64).fill(3)), + meltCoinMaxAge: meltCoinAgeCommitmentProof ? 14 : 0, + meltCoinAgeCommitmentProof, + feeRefresh: Amounts.parseOrThrow("KUDOS:0.01"), + newCoinDenoms, + blindingSeed, + exchangeWithdrawValues, + }); + for (let i = 0; i < 3; i++) { + const revealed = await nativeCryptoR.deriveRevealedRefreshPlanchets( + nativeCryptoR, + { + meltCoinPriv: encodeCrock(meltCoin.eddsaPriv), + meltCoinMaxAge: meltCoinAgeCommitmentProof ? 14 : 0, + meltCoinAgeCommitmentProof, + transferPubs: session.transferPubs[i], + newCoinDenomPubs: [ + refreshTestRsaDenomPub, + refreshTestRsaDenomPub, + csTvgDenomPub, + ], + blindingSeed, + exchangeWithdrawValues, + }, + ); + assert.deepStrictEqual(revealed.planchets, session.planchets[i]); + } + } + await assert.rejects( + nativeCryptoR.deriveRevealedRefreshPlanchets(nativeCryptoR, { + meltCoinPriv: encodeCrock(meltCoin.eddsaPriv), + meltCoinMaxAge: 0, + transferPubs: [], + newCoinDenomPubs: [refreshTestRsaDenomPub], + }), + ); +}); diff --git a/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts b/packages/taler-wallet-core/src/crypto/cryptoImplementation.ts @@ -82,6 +82,7 @@ import { kdf, kdfKw, keyExchangeEcdhEddsa, + keyExchangeEddsaEcdh, Logger, MakeSyncSignatureRequest, MerchantContractOutputType, @@ -123,6 +124,8 @@ import { DeriveRefreshSessionRequest, DeriveRefreshSessionRequestV2, DeriveRefreshSessionRequestV3, + DerivedRevealedRefreshPlanchets, + DeriveRevealedRefreshPlanchetsRequest, EncryptContractForDepositRequest, EncryptContractForDepositResponse, EncryptContractRequest, @@ -215,6 +218,83 @@ async function createRefreshCoinEnvelope( } /** + * Derive fresh coin number coinIndex of a refresh batch from its transfer + * secret (see TALER_transfer_secret_to_planchet_secret in the C impl). + * + * The melting wallet obtains the transfer secret as ECDH(transfer_priv, + * old_coin_pub), the owner of the old coin as ECDH(old_coin_priv, + * transfer_pub) (TALER_link_recover_transfer_secret); both yield the same + * coin. + */ +async function deriveRefreshPlanchetFromTransferSecret( + tci: TalerCryptoInterfaceR, + args: { + transferSecret: Uint8Array; + coinIndex: number; + denomPub: DenominationPubKey; + blindingSeed: string | undefined; + exchangeWithdrawValues: ExchangeWithdrawValue | undefined; + meltCoinMaxAge: number; + meltCoinAgeCommitmentProof: AgeCommitmentProof | undefined; + }, +): Promise<{ planchet: RefreshPlanchetInfo; coinEvHash: Uint8Array }> { + const { coinIndex } = args; + const planchetSecret = kdfKw({ + ikm: args.transferSecret, + outputLength: 32, + salt: bufferForUint32(coinIndex), + info: stringToBytes("taler-coin-derivation"), + }); + const fresh: FreshCoinEncoded = await tci.setupRefreshPlanchetV2(tci, { + coinNumber: coinIndex, + refreshPlanchetSecret: encodeCrock(planchetSecret), + exchangeWithdrawValues: args.exchangeWithdrawValues, + }); + let newAc: AgeCommitmentProof | undefined = undefined; + let newAch: HashCodeString | undefined = undefined; + if (args.meltCoinAgeCommitmentProof) { + const ageCommitmentSalt = kdfKw({ + ikm: planchetSecret, + outputLength: 64, + salt: stringToBytes("age commitment"), + }); + newAc = await AgeRestriction.commitmentDerive( + args.meltCoinAgeCommitmentProof, + ageCommitmentSalt, + ); + newAch = AgeRestriction.hashCommitment(newAc.commitment); + } + const coinPubHash = hashCoinPub(fresh.coinPub, newAch); + const envelope = await createRefreshCoinEnvelope( + tci, + args.denomPub, + fresh, + coinPubHash, + coinIndex, + args.blindingSeed, + args.exchangeWithdrawValues, + ); + const { coinEv } = envelope; + const coinEvHash = hashCoinEv( + coinEv, + encodeCrock(hashDenomPub(args.denomPub)), + ); + return { + coinEvHash, + planchet: { + blindingKey: envelope.blindingKey, + exchangeWithdrawValues: envelope.exchangeWithdrawValues, + coinEv, + coinPriv: fresh.coinPriv, + coinPub: fresh.coinPub, + coinEvHash: encodeCrock(coinEvHash), + maxAge: args.meltCoinMaxAge, + ageCommitmentProof: newAc, + }, + }; +} + +/** * Interface for (asynchronous) cryptographic operations that * Taler uses. */ @@ -348,6 +428,10 @@ export interface TalerCryptoInterface { req: DeriveRefreshSessionRequestV3, ): Promise<DerivedRefreshSessionV3>; + deriveRevealedRefreshPlanchets( + req: DeriveRevealedRefreshPlanchetsRequest, + ): Promise<DerivedRevealedRefreshPlanchets>; + hashString(req: HashStringRequest): Promise<HashStringResult>; signCoinLink(req: SignCoinLinkRequest): Promise<EddsaSigningResult>; @@ -754,6 +838,11 @@ export const nullCrypto: TalerCryptoInterface = { ): Promise<DerivedRefreshSessionV3> { throw new Error("Function not implemented."); }, + deriveRevealedRefreshPlanchets: function ( + req: DeriveRevealedRefreshPlanchetsRequest, + ): Promise<DerivedRevealedRefreshPlanchets> { + throw new Error("Function not implemented."); + }, rsaVerifyDirect: function ( req: RsaVerificationRequest, ): Promise<ValidationResult> { @@ -1798,6 +1887,11 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { valid = verify(preimage, item.coin_sig, req.coinPub); break; } + case "REVEAL": + // Not signed; bound to its MELT entry by rc, see + // requireConsistentCoinRevealEntries. + valid = true; + break; case "REFUND": { if (!feeMatches(item.refund_fee, req.feeRefund)) { return { valid: false }; @@ -2677,60 +2771,16 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { ecdhePriv: transferPriv, eddsaPub: meltCoinPub, }); - // See TALER_transfer_secret_to_planchet_secret in the C impl. - const myPlanchetSecret = kdfKw({ - ikm: decodeCrock(transferSecretRes.h), - outputLength: 32, - salt: bufferForUint32(coinIndex), - info: stringToBytes("taler-coin-derivation"), - }); - const fresh: FreshCoinEncoded = await tci.setupRefreshPlanchetV2( - tci, - { - coinNumber: coinIndex, - refreshPlanchetSecret: encodeCrock(myPlanchetSecret), + const { planchet, coinEvHash } = + await deriveRefreshPlanchetFromTransferSecret(tci, { + transferSecret: decodeCrock(transferSecretRes.h), + coinIndex, + denomPub: denomSel.denomPub, + blindingSeed: req.blindingSeed, exchangeWithdrawValues: req.exchangeWithdrawValues?.[coinIndex], - }, - ); - let newAc: AgeCommitmentProof | undefined = undefined; - let newAch: HashCodeString | undefined = undefined; - if (req.meltCoinAgeCommitmentProof) { - const ageCommitmentSalt = kdfKw({ - ikm: myPlanchetSecret, - outputLength: 64, - salt: stringToBytes("age commitment"), + meltCoinMaxAge: req.meltCoinMaxAge, + meltCoinAgeCommitmentProof: req.meltCoinAgeCommitmentProof, }); - newAc = await AgeRestriction.commitmentDerive( - req.meltCoinAgeCommitmentProof, - ageCommitmentSalt, - ); - newAch = AgeRestriction.hashCommitment(newAc.commitment); - } - const coinPubHash = hashCoinPub(fresh.coinPub, newAch); - const envelope = await createRefreshCoinEnvelope( - tci, - denomSel.denomPub, - fresh, - coinPubHash, - coinIndex, - req.blindingSeed, - req.exchangeWithdrawValues?.[coinIndex], - ); - const { coinEv } = envelope; - const coinEvHash = hashCoinEv( - coinEv, - encodeCrock(hashDenomPub(denomSel.denomPub)), - ); - const planchet: RefreshPlanchetInfo = { - blindingKey: envelope.blindingKey, - exchangeWithdrawValues: envelope.exchangeWithdrawValues, - coinEv, - coinPriv: fresh.coinPriv, - coinPub: fresh.coinPub, - coinEvHash: encodeCrock(coinEvHash), - maxAge: req.meltCoinMaxAge, - ageCommitmentProof: newAc, - }; planchets.push(planchet); planchetsHc.update(coinEvHash); } @@ -2798,6 +2848,41 @@ export const nativeCryptoR: TalerCryptoInterfaceR = { }; }, + /** + * Derive the fresh coins of the revealed batch of a melt from the old + * coin's private key and the batch's transfer public keys, the way the + * former /link endpoint let the owner of the old coin do it: coin i comes + * from ECDH(old_coin_priv, transfer_pubs[i]), see + * TALER_link_recover_transfer_secret in the C impl. + */ + async deriveRevealedRefreshPlanchets( + tci: TalerCryptoInterfaceR, + req: DeriveRevealedRefreshPlanchetsRequest, + ): Promise<DerivedRevealedRefreshPlanchets> { + if (req.transferPubs.length !== req.newCoinDenomPubs.length) { + throw Error("need one transfer public key per fresh coin"); + } + const meltCoinPriv = decodeCrock(req.meltCoinPriv); + const planchets: RefreshPlanchetInfo[] = []; + for (let coinIndex = 0; coinIndex < req.transferPubs.length; coinIndex++) { + const transferSecret = keyExchangeEddsaEcdh( + meltCoinPriv, + decodeCrock(req.transferPubs[coinIndex]), + ); + const { planchet } = await deriveRefreshPlanchetFromTransferSecret(tci, { + transferSecret, + coinIndex, + denomPub: req.newCoinDenomPubs[coinIndex], + blindingSeed: req.blindingSeed, + exchangeWithdrawValues: req.exchangeWithdrawValues?.[coinIndex], + meltCoinMaxAge: req.meltCoinMaxAge, + meltCoinAgeCommitmentProof: req.meltCoinAgeCommitmentProof, + }); + planchets.push(planchet); + } + return { planchets }; + }, + async deriveRefreshSession( tci: TalerCryptoInterfaceR, req: DeriveRefreshSessionRequest, diff --git a/packages/taler-wallet-core/src/crypto/cryptoTypes.ts b/packages/taler-wallet-core/src/crypto/cryptoTypes.ts @@ -120,6 +120,34 @@ export interface DeriveRefreshSessionRequestV3 { exchangeWithdrawValues?: (ExchangeWithdrawValue | undefined)[]; } +/** + * Request to derive the fresh coins of the revealed batch of a melt from the + * old coin's private key and the transfer public keys of that batch. + * + * Unlike {@link DeriveRefreshSessionRequestV3}, this does not need the batch + * seed, so it also recovers the coins of a melt whose batch seeds were not + * derived from the refresh seed by this wallet. + */ +export interface DeriveRevealedRefreshPlanchetsRequest { + meltCoinPriv: string; + meltCoinMaxAge: number; + meltCoinAgeCommitmentProof?: AgeCommitmentProof; + /** + * Transfer public keys of the revealed batch, one per fresh coin. + */ + transferPubs: EddsaPublicKeyString[]; + /** + * Denominations of the fresh coins, in the order of the melt. + */ + newCoinDenomPubs: DenominationPubKey[]; + blindingSeed?: string; + exchangeWithdrawValues?: (ExchangeWithdrawValue | undefined)[]; +} + +export interface DerivedRevealedRefreshPlanchets { + planchets: RefreshPlanchetInfo[]; +} + export interface DerivedRefreshSession { /** * Public key that's being melted in this session. diff --git a/packages/taler-wallet-core/src/exchange-signatures.test.ts b/packages/taler-wallet-core/src/exchange-signatures.test.ts @@ -29,6 +29,7 @@ import { requireValidDirectExchangeRefundConfirmation, requireValidExchangePurseCreateConfirmation, requireValidExchangePurseDepositConfirmation, + requireValidExchangeCoinHistory, requireValidExchangePurseStatus, } from "./exchange-signatures.js"; @@ -101,6 +102,9 @@ function verificationContext(args: { async isValidRefundConfirmation() { return { valid: args.cryptoValid }; }, + async isValidCoinHistory() { + return { valid: args.cryptoValid }; + }, }, async runWalletDbTx(fn: (tx: any) => Promise<unknown>) { return await fn({ @@ -263,3 +267,83 @@ test("purse-create confirmation uses the request contract fields", async () => { assert.strictEqual(seen[0].purseValueAfterFees, "TESTKUDOS:5"); assert.strictEqual(seen[0].purseExpiration.t_s, 2_000_000_000); }); + +test("a REVEAL history entry must belong to a preceding melt and fit its outputs", async () => { + const melt = { + type: "MELT", + history_offset: 0, + amount: "TESTKUDOS:3", + melt_fee: "TESTKUDOS:0.1", + rc: "rc", + h_denom_pub: "denom", + refresh_seed: "seed", + denoms_h: ["d1", "d2"], + noreveal_index: 1, + transfer_pubs: ["t1", "t2"], + coin_sig: "coin-signature", + }; + const reveal = { + type: "REVEAL", + history_offset: 1, + rc: "rc", + ev_sigs: [ + { cipher: "RSA", blinded_rsa_signature: "s1" }, + { cipher: "CS", b: 0, s: "s2" }, + ], + cs_r_values: [null, ["r0", "r1"]], + }; + const check = (history: unknown[]) => + requireValidExchangeCoinHistory( + verificationContext({ cryptoValid: true, knownPub: "key" }), + { + exchangeBaseUrl: "https://exchange.example/", + coinPub: "coin", + denomination: { + denomPubHash: "denom", + feeDeposit: "TESTKUDOS:0", + feeRefresh: "TESTKUDOS:0.1", + feeRefund: "TESTKUDOS:0", + } as any, + response: { + h_denom_pub: "denom", + balance: "TESTKUDOS:7", + history, + } as any, + }, + ); + await assert.doesNotReject(check([melt, reveal])); + const withoutR: Partial<typeof reveal> = { ...reveal }; + delete withoutR.cs_r_values; + await assert.doesNotReject(check([melt, withoutR])); + const rejected: [string, unknown[]][] = [ + ["without a preceding MELT", [reveal]], + ["without a preceding MELT", [melt, { ...reveal, rc: "other" }]], + [ + "without a preceding MELT", + [ + { ...melt, history_offset: 2 }, + { ...reveal, history_offset: 1 }, + ], + ], + ["more than one REVEAL", [melt, reveal, { ...reveal, history_offset: 2 }]], + [ + "one signature per fresh coin", + [melt, { ...reveal, ev_sigs: reveal.ev_sigs.slice(1) }], + ], + [ + "one signature per fresh coin", + [melt, { ...reveal, cs_r_values: [null] }], + ], + [ + "one signature per fresh coin", + [{ ...melt, denoms_h: undefined }, withoutR], + ], + [ + "R-values for the wrong coins", + [melt, { ...reveal, cs_r_values: [["r0", "r1"], null] }], + ], + ]; + for (const [message, history] of rejected) { + await assert.rejects(check(history), new RegExp(message), message); + } +}); diff --git a/packages/taler-wallet-core/src/exchange-signatures.ts b/packages/taler-wallet-core/src/exchange-signatures.ts @@ -28,7 +28,10 @@ import { Amounts, BatchDepositSuccess, CoinHistoryResponse, + CoinMeltTransaction, + CoinSpendHistoryItem, DenominationInfo, + DenomKeyType, Duration, EddsaPublicKeyString, ExchangePurseStatus, @@ -172,6 +175,60 @@ export async function requireValidExchangePurseMergeConfirmation( } } +/** + * Check the REVEAL entries of a coin history against its MELT entries. + * + * A REVEAL entry carries no signature of its own: it is bound to the melt + * by rc, and its blinded signatures are checked when the fresh coins are + * unblinded. Here, require one MELT entry before it with the same rc and + * one signature (and, if given, one R-value pair or null) per fresh coin + * of that melt. Replays of a reveal append nothing, so a melt has at most + * one REVEAL entry. + */ +export function requireConsistentCoinRevealEntries( + history: CoinSpendHistoryItem[], +): void { + const revealed = new Set<string>(); + for (const item of history) { + if (item.type !== "REVEAL") continue; + const melt = history.find( + (m): m is CoinMeltTransaction => m.type === "MELT" && m.rc === item.rc, + ); + if (!melt || melt.history_offset >= item.history_offset) { + throw invalidExchangeSignature( + "coin history has a REVEAL entry without a preceding MELT entry", + ); + } + if (revealed.has(item.rc)) { + throw invalidExchangeSignature( + "coin history has more than one REVEAL entry for a melt", + ); + } + revealed.add(item.rc); + const n = melt.denoms_h?.length; + if ( + n === undefined || + item.ev_sigs.length !== n || + (item.cs_r_values !== undefined && item.cs_r_values.length !== n) + ) { + throw invalidExchangeSignature( + "coin history REVEAL entry does not have one signature per fresh coin", + ); + } + if ( + item.cs_r_values?.some( + (r, i) => + (r !== null) !== + (item.ev_sigs[i].cipher === DenomKeyType.ClauseSchnorr), + ) + ) { + throw invalidExchangeSignature( + "coin history REVEAL entry has R-values for the wrong coins", + ); + } + } +} + /** Verify every authorization and exchange confirmation in a coin history. */ export async function requireValidExchangeCoinHistory( wex: WalletExecutionContext, @@ -195,6 +252,7 @@ export async function requireValidExchangeCoinHistory( "exchange returned a coin history with invalid signatures or fees", ); } + requireConsistentCoinRevealEntries(args.response.history); const known = await Promise.all( args.response.history.flatMap((item) => { diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -329,6 +329,34 @@ test("coin history balance is recomputed from typed operations", () => { ); }); +test("a REVEAL history entry does not change the coin balance", () => { + const history = { + h_denom_pub: "denom", + balance: "TESTKUDOS:7", + history: [ + { + type: "MELT", + history_offset: 0, + amount: "TESTKUDOS:3", + melt_fee: "TESTKUDOS:0.1", + rc: "rc", + h_denom_pub: "denom", + denoms_h: ["d1"], + }, + { + type: "REVEAL", + history_offset: 1, + rc: "rc", + ev_sigs: [{ cipher: "RSA", blinded_rsa_signature: "sig" }], + }, + ], + } as never; + assert.strictEqual( + validateAndRecomputeCoinHistoryBalance("denom", "TESTKUDOS:10", history), + "TESTKUDOS:7", + ); +}); + test("coin history rejects unbound or non-conserving aggregates", () => { const response = { h_denom_pub: "denom", diff --git a/packages/taler-wallet-core/src/refresh.ts b/packages/taler-wallet-core/src/refresh.ts @@ -1823,6 +1823,10 @@ export function validateAndRecomputeCoinHistoryBalance( case "MELT": amount = item.amount; break; + case "REVEAL": + // Carries the signatures over the fresh coins of a melt, whose MELT + // entry already accounts for the value. + continue; case "RESERVE-OPEN-DEPOSIT": amount = item.coin_contribution; break; diff --git a/packages/taler-wallet-core/src/testing-check-coins.ts b/packages/taler-wallet-core/src/testing-check-coins.ts @@ -20,6 +20,7 @@ import { canonicalizeBaseUrl, canonicalJson, CoinHistoryResponse, + CoinRevealTransaction, CoinStatus, DenominationInfo, HttpStatusCode, @@ -242,12 +243,18 @@ export async function testingCheckCoins( "Exchange balance differs from the unspent coin's denomination value", expected: { balance: denom.value }, actual: { balance: response.balance }, - exchangeOperations: response.history.map((item) => [ - item.type, - item.type === "RESERVE-OPEN-DEPOSIT" - ? item.coin_contribution - : item.amount, - ]), + // A REVEAL entry moves no value; its MELT entry is listed. + exchangeOperations: response.history + .filter( + (item): item is Exclude<typeof item, CoinRevealTransaction> => + item.type !== "REVEAL", + ) + .map((item) => [ + item.type, + item.type === "RESERVE-OPEN-DEPOSIT" + ? item.coin_contribution + : item.amount, + ]), }); } } diff --git a/packages/taler-wallet-core/src/testing-recover-coins.test.ts b/packages/taler-wallet-core/src/testing-recover-coins.test.ts @@ -15,16 +15,27 @@ */ import assert from "node:assert/strict"; +import { generateKeyPairSync } from "node:crypto"; import { test } from "node:test"; import { AmountString, Amounts, + BlindedDenominationSignature, CancellationToken, + CoinEnvelope, CoinHistoryResponse, CoinMeltTransaction, + CoinRevealTransaction, + CoinSpendHistoryItem, CoinStatus, + decodeCrock, + DenominationPubKey, DenomKeyType, + deriveCsNonce, + eddsaGetPublic, encodeCrock, + ExchangeWithdrawValue, + getRandomBytes, hash, stringToBytes, NotificationType, @@ -51,6 +62,7 @@ import { import { WalletDbHandle } from "./db/handle.js"; import { runnerFactories } from "./db/testing/runners.js"; import { handleCancelProgressToken } from "./progress.js"; +import { nativeCryptoR } from "./crypto/cryptoImplementation.js"; const url = "https://exchange.test/"; const a = (value: string): AmountString => `TESTKUDOS:${value}` as AmountString; @@ -90,9 +102,10 @@ function denom(value: string): WalletDenomination { }; } function coin(label: string, value: string): WalletCoin { + const coinPriv = k("private" + label); return { - coinPub: k(label), - coinPriv: k("private" + label), + coinPub: encodeCrock(eddsaGetPublic(decodeCrock(coinPriv))), + coinPriv, denomPubHash: h(value), exchangeBaseUrl: url, exchangeMasterPub: master, @@ -175,6 +188,7 @@ async function fixture(db: WalletDbHandle) { let badSignature = false; let noRevealIndex = 1; let onRequest: ((path: string) => Promise<void>) | undefined; + let blindingPrepare: ((body: any) => unknown) | undefined; function melt(old: WalletCoin, outputs: WalletCoin[], version = 32) { const seed = h("seed" + old.coinPub); const amount = Amounts.stringify( @@ -240,6 +254,14 @@ async function fixture(db: WalletDbHandle) { blinded_rsa_signature: sig, })), }; + } else if (path === "blinding-prepare") { + response = blindingPrepare?.(body); + if (!response) { + status = 404; + response = { + code: TalerErrorCode.EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN, + }; + } } else throw Error("Unexpected endpoint " + path); return { requestUrl: u, @@ -341,6 +363,188 @@ async function fixture(db: WalletDbHandle) { onRequest: (f: (p: string) => Promise<void>) => { onRequest = f; }, + blindingPrepare: (f?: (body: any) => unknown) => { + blindingPrepare = f; + }, + }; +} + +function bigIntFromBytes(b: Uint8Array, littleEndian = false): bigint { + const bytes = littleEndian ? [...b].reverse() : [...b]; + return bytes.reduce((acc, x) => (acc << 8n) | BigInt(x), 0n); +} + +function bigIntToBytes(n: bigint, length: number, littleEndian = false) { + const out = new Uint8Array(length); + for (let i = length - 1; i >= 0; i--, n >>= 8n) out[i] = Number(n & 0xffn); + return littleEndian ? out.reverse() : out; +} + +function modPow(base: bigint, exp: bigint, mod: bigint): bigint { + let result = 1n; + base %= mod; + for (; exp > 0n; exp >>= 1n, base = (base * base) % mod) + if (exp & 1n) result = (result * base) % mod; + return result; +} + +const b64 = (s: string) => new Uint8Array(Buffer.from(s, "base64url")); + +/** An exchange's denomination keys, to sign the fresh coins of a melt. */ +const signer = (() => { + let rsa: { n: bigint; d: bigint; pub: string } | undefined; + // Clause-Schnorr keys of the taler-exchange-tvg vector "cs_blind_signing". + const csPriv = bigIntFromBytes( + decodeCrock("K43QAMEPE9KJJTX6AJZD6N4SN1N3ARVAXZ2MRNPT85FHD4QD2C60"), + true, + ); + const rPrivs = [ + "B01FJCRCST8JM10K17SJXY7S7HH7T65JMFQ03H6PNYY9Z167Q1T0", + "N3GW5X6VYSB8PY83CYNHJ3PN6TCA5N5BCS4WT2WEEQH7MTK915P0", + ].map((r) => bigIntFromBytes(decodeCrock(r), true)); + const rPubs: [string, string] = [ + "J5XFBKFP9T6BM02H6ZV6Y568PQ2K398MD339036F25XTSP1A7T3G", + "GA2CZKJ6CWFS81ZN1T5R4GQFHF7XJV6HWHDR1JA9VATKKXQN89J0", + ]; + const L = 2n ** 252n + 27742317777372353535851937790883648493n; + const rsaKey = () => { + if (!rsa) { + const jwk = generateKeyPairSync("rsa", { + modulusLength: 2048, + }).privateKey.export({ format: "jwk" }); + const [n, e] = [b64(jwk.n!), b64(jwk.e!)]; + const pub = new Uint8Array(4 + n.length + e.length); + pub.set([n.length >> 8, n.length & 0xff, e.length >> 8, e.length & 0xff]); + pub.set(n, 4); + pub.set(e, 4 + n.length); + rsa = { + n: bigIntFromBytes(n), + d: bigIntFromBytes(b64(jwk.d!)), + pub: encodeCrock(pub), + }; + } + return rsa; + }; + return { + rPubs, + rsaDenomPub: (): DenominationPubKey => ({ + cipher: DenomKeyType.Rsa, + rsa_public_key: rsaKey().pub, + age_mask: 0, + }), + csDenomPub: (): DenominationPubKey => ({ + cipher: DenomKeyType.ClauseSchnorr, + cs_public_key: "1903SZ7QE1K8T4BHTJ32KDJ153SBXT22DGNQDY5NKJE535J72H2G", + age_mask: 0, + }), + sign(coinEv: CoinEnvelope): BlindedDenominationSignature { + if (coinEv.cipher === DenomKeyType.Rsa) { + const { n, d } = rsaKey(); + const m = bigIntFromBytes(decodeCrock(coinEv.rsa_blinded_planchet)); + return { + cipher: DenomKeyType.Rsa, + blinded_rsa_signature: encodeCrock( + bigIntToBytes(modPow(m, d, n), 256), + ), + }; + } + const b = 1; + const c = bigIntFromBytes(decodeCrock(coinEv.cs_blinded_c1), true); + return { + cipher: DenomKeyType.ClauseSchnorr, + b, + s: encodeCrock(bigIntToBytes((rPrivs[b] + c * csPriv) % L, 32, true)), + }; + }, + }; +})(); + +/** + * A melt of the root coin by another holder of its private key, with batch + * seeds that do not follow from the refresh seed in its history entry. + */ +async function foreignMelt(f: Awaited<ReturnType<typeof fixture>>) { + const outputs = [ + { ...denom("2"), denomPubHash: h("rsa"), denomPub: signer.rsaDenomPub() }, + { ...denom("1"), denomPubHash: h("cs"), denomPub: signer.csDenomPub() }, + ]; + await f.db.runReadWriteTx(async (tx) => { + for (const d of outputs) await tx.upsertDenomination(d); + }); + const order = [outputs[0], outputs[1], outputs[0]]; + const csValues: ExchangeWithdrawValue = { + cipher: DenomKeyType.ClauseSchnorr, + r_pub_0: signer.rPubs[0], + r_pub_1: signer.rPubs[1], + }; + const blindingSeed = encodeCrock(getRandomBytes(32)); + const session = await nativeCryptoR.deriveRefreshSessionV3(nativeCryptoR, { + includeTransferPubsInCommitment: true, + kappa: 3, + sessionPublicSeed: h("seed of the other holder"), + meltCoinPub: f.root.coinPub, + meltCoinPriv: f.root.coinPriv, + meltCoinDenomPubHash: f.root.denomPubHash, + meltCoinMaxAge: 0, + feeRefresh: Amounts.parseOrThrow(a("1")), + newCoinDenoms: order.map((d) => ({ + count: 1, + value: d.value, + feeWithdraw: d.fees.feeWithdraw, + denomPub: d.denomPub, + denomPubHash: d.denomPubHash, + })), + blindingSeed, + exchangeWithdrawValues: [undefined, csValues, undefined], + }); + const noreveal = 2; + const melt: CoinMeltTransaction = { + type: "MELT", + history_offset: 1, + amount: Amounts.stringify(session.meltValueWithFee), + melt_fee: a("1"), + rc: session.hash, + h_denom_pub: f.root.denomPubHash, + refresh_seed: h("refresh seed in the melt request"), + blinding_seed: blindingSeed, + denoms_h: order.map((d) => d.denomPubHash), + noreveal_index: noreveal, + transfer_pubs: session.transferPubs[noreveal], + coin_sig: sig, + }; + const reveal: CoinRevealTransaction = { + type: "REVEAL", + history_offset: 2, + rc: session.hash, + ev_sigs: session.planchets[noreveal].map((p) => signer.sign(p.coinEv)), + cs_r_values: [null, signer.rPubs, null], + }; + const history = (...items: CoinSpendHistoryItem[]) => + f.histories.set(f.root.coinPub, { + h_denom_pub: f.root.denomPubHash, + balance: a("0"), + history: items, + }); + // Real cryptography for the derivation of the fresh coins and their + // signatures; the coin history signatures stay mocked. + Object.assign(f.wex.cryptoApi, { + deriveRefreshSessionV3: (r: any) => + nativeCryptoR.deriveRefreshSessionV3(nativeCryptoR, r), + deriveRefreshSessionV2: (r: any) => + nativeCryptoR.deriveRefreshSessionV2(nativeCryptoR, r), + deriveRevealedRefreshPlanchets: (r: any) => + nativeCryptoR.deriveRevealedRefreshPlanchets(nativeCryptoR, r), + unblindDenominationSignature: (r: any) => + nativeCryptoR.unblindDenominationSignature(nativeCryptoR, r), + verifyDenominationSignature: (r: any) => + nativeCryptoR.verifyDenominationSignature(nativeCryptoR, r), + }); + return { + melt, + reveal, + history, + blindingSeed, + planchets: session.planchets[noreveal], }; } @@ -594,6 +798,121 @@ for (const makeDb of runnerFactories) { await f.close(); } }); + + test(`${makeDb.name}: a REVEAL entry recovers a melt with seeds of another holder`, async () => { + const f = await fixture(await makeDb()); + try { + const m = await foreignMelt(f); + f.blindingPrepare((body) => ({ + cipher: DenomKeyType.ClauseSchnorr, + r_pubs: body.nks.map(() => signer.rPubs), + })); + m.history(m.melt); + const before = await f.run(); + assert.equal(before.issues.length, 1, JSON.stringify(before)); + assert.equal(before.issues[0].reason, "commitment-mismatch"); + assert.match(before.issues[0].description, /cannot derive.*REVEAL/); + assert(!f.requests.some((r) => r.path === "melt")); + + m.history(m.melt, m.reveal); + const requests = f.requests.length; + const result = await f.run(); + assert.equal(result.complete, true, JSON.stringify(result)); + assert.equal(result.recoveredAmount, a("5")); + assert.equal(result.numRecovered, 3); + // Only coin histories, no melt, reveal or blinding-prepare request. + assert.deepEqual( + f.requests.slice(requests).filter((r) => !r.path.startsWith("coins/")), + [], + ); + const coins = await f.db.runReadWriteTx((tx) => + tx.getCoinsByPubs(m.planchets.map((p) => p.coinPub)), + ); + assert.equal(coins.length, 3); + for (const c of coins) assert.equal(c.status, CoinStatus.Fresh); + const csCoin = coins.find((c) => c.coinPub === m.planchets[1].coinPub)!; + assert.equal(csCoin.denomSig.cipher, DenomKeyType.ClauseSchnorr); + assert.equal( + csCoin.coinSource.type === CoinSourceType.Refresh && + csCoin.coinSource.nonce, + encodeCrock(deriveCsNonce(decodeCrock(m.blindingSeed), "melt", 1)), + ); + const group = ( + await f.db.runReadWriteTx((tx) => tx.listAllRefreshGroups()) + )[0]; + const session = await f.db.runReadWriteTx((tx) => + tx.getRefreshSession(group.refreshGroupId, 0), + ); + assert.equal(session!.norevealIndex, 2); + } finally { + await f.close(); + } + }); + + test(`${makeDb.name}: a REVEAL entry without R-values asks the exchange for them`, async () => { + const f = await fixture(await makeDb()); + try { + const m = await foreignMelt(f); + delete m.reveal.cs_r_values; + m.history(m.melt, m.reveal); + const unavailable = await f.run(); + assert.equal(unavailable.issues[0].reason, "missing-recovery-data"); + assert.match(unavailable.issues[0].description, /R-values/); + const prepared: any[] = []; + f.blindingPrepare((body) => { + prepared.push(body); + return { + cipher: DenomKeyType.ClauseSchnorr, + r_pubs: body.nks.map(() => signer.rPubs), + }; + }); + const result = await f.run(); + assert.equal(result.complete, true, JSON.stringify(result)); + assert.equal(result.recoveredAmount, a("5")); + assert.deepEqual(prepared, [ + { + cipher: DenomKeyType.ClauseSchnorr, + operation: "melt", + seed: m.blindingSeed, + nks: [{ coin_offset: 1, denom_pub_hash: h("cs") }], + }, + ]); + } finally { + await f.close(); + } + }); + + test(`${makeDb.name}: a REVEAL entry must fit the melt and carry valid signatures`, async () => { + const f = await fixture(await makeDb()); + try { + const m = await foreignMelt(f); + const [s0, s1, s2] = m.reveal.ev_sigs; + for (const reveal of [ + { ...m.reveal, ev_sigs: [s2, s1, s0] }, + { ...m.reveal, ev_sigs: [s1, s0, s2] }, + ]) { + m.history(m.melt, reveal); + const result = await f.run(); + assert.equal(result.issues[0].reason, "invalid-history"); + } + m.history( + { ...m.melt, transfer_pubs: m.melt.transfer_pubs!.slice(1) }, + m.reveal, + ); + assert.equal((await f.run()).issues[0].reason, "invalid-history"); + assert( + !f.requests.some((r) => + ["melt", "reveal-melt", "blinding-prepare"].includes(r.path), + ), + ); + assert.equal( + (await f.db.runReadWriteTx((tx) => tx.listAllRefreshGroups())).length, + 0, + ); + } finally { + await f.close(); + } + }); } test("recovery request codec defaults selection in the handler and rejects bad fields", () => { diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts @@ -19,20 +19,26 @@ import { AgeRestriction, AmountString, Amounts, + BlindedDenominationSignature, + BlindingInputParameter, canonicalizeBaseUrl, canonicalJson, CoinHistoryResponse, CoinMeltTransaction, CoinRecoveryIssue, CoinRecoveryPhase, + CoinRevealTransaction, CoinStatus, + DenominationPubKey, DenomKeyType, encodeCrock, + ExchangeWithdrawValue, getRandomBytes, hash, hashCoinPub, HttpStatusCode, NotificationType, + RefreshPlanchetInfo, RefreshReason, stringToBytes, succeedOrThrow, @@ -55,6 +61,7 @@ import { WalletRefreshSession, } from "./db/records.js"; import { WalletDbTransaction } from "./db/transaction.js"; +import { RefreshNewDenomInfo } from "./crypto/cryptoTypes.js"; import { requireValidExchangeCoinHistory } from "./exchange-signatures.js"; import { runWithMaybeProgressContext } from "./progress.js"; import { @@ -160,19 +167,101 @@ async function changeAvailability( }); } -/** Reconstruct one historical refresh, without disclosing unmatched candidates. */ +/** + * Obtain the R-values of the Clause-Schnorr fresh coins of a revealed melt. + * + * The REVEAL entry should carry them. Otherwise ask the exchange again for + * the R-values of the melt's blinding seed, which only works while the + * denominations' private keys are available. + */ +async function revealedExchangeWithdrawValues( + wex: WalletExecutionContext, + oldCoin: WalletCoin, + newDenoms: { denomPub: DenominationPubKey; denomPubHash: string }[], + blindingSeed: string | undefined, + revealEntry: CoinRevealTransaction, +): Promise<(ExchangeWithdrawValue | undefined)[] | undefined> { + const nks: BlindingInputParameter[] = []; + const values: (ExchangeWithdrawValue | undefined)[] = newDenoms.map( + () => undefined, + ); + newDenoms.forEach((d, i) => { + if (d.denomPub.cipher !== DenomKeyType.ClauseSchnorr) return; + const r = revealEntry.cs_r_values?.[i]; + if (r) { + values[i] = { + cipher: DenomKeyType.ClauseSchnorr, + r_pub_0: r[0], + r_pub_1: r[1], + }; + } else { + nks.push({ coin_offset: i, denom_pub_hash: d.denomPubHash }); + } + }); + if (!values.some((v) => v) && !nks.length) return undefined; + if (nks.length) { + let rPubs: [string, string][] | undefined; + try { + const prep = await walletExchangeClient( + oldCoin.exchangeBaseUrl, + wex, + ).postBlindingPrepare({ + body: { + cipher: DenomKeyType.ClauseSchnorr, + operation: "melt", + seed: blindingSeed!, + nks, + }, + }); + if (prep.case === "ok") rPubs = prep.body.r_pubs; + } catch { + // Reported below. + } + checkCancelled(wex); + if (!rPubs || rPubs.length !== nks.length) { + throw new RecoveryError( + "missing-recovery-data", + "Exchange history lacks the Clause-Schnorr R-values of the revealed coins, and the exchange no longer provides them", + ); + } + for (let j = 0; j < nks.length; j++) { + values[nks[j].coin_offset] = { + cipher: DenomKeyType.ClauseSchnorr, + r_pub_0: rPubs[j][0], + r_pub_1: rPubs[j][1], + }; + } + } + return values; +} + +/** + * Reconstruct one historical refresh, without disclosing unmatched candidates. + * + * With a REVEAL entry for the melt, the fresh coins follow from the old + * coin's private key, the transfer public keys of the revealed batch and the + * blinded signatures of the entry, however the batch seeds were derived, and + * no melt or reveal request is needed. Otherwise, re-derive the melt from + * the refresh seed and replay melt and reveal, which only works for a melt + * whose batch seeds this wallet derives from the refresh seed. + */ export async function recoverCoinMelt( wex: WalletExecutionContext, oldCoin: WalletCoin, oldDenom: WalletDenomination, melt: CoinMeltTransaction, phase: (p: CoinRecoveryPhase) => void, + revealEntry?: CoinRevealTransaction, ): Promise<{ coins: WalletCoin[]; group: WalletRefreshGroup; session: WalletRefreshSession; }> { - if (!melt.refresh_seed || !melt.denoms_h?.length) { + // A melt without transfer public keys (refresh protocol v27) derives its + // coins from signatures by the old coin, not from transfer keys. Its REVEAL + // entry does not help, but the melt can still be replayed. + const transferPubs = revealEntry ? melt.transfer_pubs : undefined; + if (!melt.denoms_h?.length || (!transferPubs && !melt.refresh_seed)) { throw new RecoveryError( "missing-recovery-data", "Exchange history lacks the refresh seed or ordered output denominations", @@ -238,6 +327,80 @@ export async function recoverCoinMelt( })), }; phase("derive"); + let planchets: RefreshPlanchetInfo[]; + let evSigs: BlindedDenominationSignature[]; + if (revealEntry && transferPubs) { + if ( + transferPubs.length !== newDenoms.length || + revealEntry.ev_sigs.length !== newDenoms.length || + revealEntry.ev_sigs.some( + (sig, i) => sig.cipher !== newDenoms[i].denomPub.cipher, + ) + ) { + throw new RecoveryError( + "invalid-history", + "Revealed melt does not have one transfer key and signature per fresh coin", + ); + } + checkCancelled(wex); + const exchangeWithdrawValues = await revealedExchangeWithdrawValues( + wex, + oldCoin, + newDenoms, + melt.blinding_seed, + revealEntry, + ); + planchets = ( + await wex.cryptoApi.deriveRevealedRefreshPlanchets({ + meltCoinPriv: oldCoin.coinPriv, + meltCoinMaxAge: oldCoin.maxAge, + meltCoinAgeCommitmentProof: oldCoin.ageCommitmentProof, + transferPubs, + newCoinDenomPubs: newDenoms.map((d) => d.denomPub), + blindingSeed: melt.blinding_seed, + exchangeWithdrawValues, + }) + ).planchets; + evSigs = revealEntry.ev_sigs; + // The coins do not follow from the refresh seed, so the session cannot + // be re-derived; the refresh group is finished and never re-derives it. + session.norevealIndex = melt.noreveal_index; + } else { + ({ planchets, evSigs } = await replayCoinMelt( + wex, + oldCoin, + oldDenom, + melt, + newDenoms, + session, + phase, + )); + } + return buildRecoveredRefresh( + wex, + oldCoin, + oldDenom, + melt, + newDenoms, + session, + planchets, + evSigs, + ); +} + +/** Re-derive a melt from its refresh seed and replay melt and reveal. */ +async function replayCoinMelt( + wex: WalletExecutionContext, + oldCoin: WalletCoin, + oldDenom: WalletDenomination, + melt: CoinMeltTransaction, + newDenoms: RefreshNewDenomInfo[], + session: WalletRefreshSession, + phase: (p: CoinRecoveryPhase) => void, +): Promise<{ + planchets: RefreshPlanchetInfo[]; + evSigs: BlindedDenominationSignature[]; +}> { let derived: Awaited<ReturnType<typeof deriveRefreshSession>> | undefined; for (const version of [45, 32, 27]) { checkCancelled(wex); @@ -260,7 +423,7 @@ export async function recoverCoinMelt( if (!derived) { throw new RecoveryError( "commitment-mismatch", - "Recovery data does not reproduce the signed refresh commitment", + "The melt was made with batch seeds this wallet cannot derive from the refresh seed; its fresh coins become recoverable once the exchange reports the reveal of the melt (REVEAL entry in the coin history)", ); } phase("melt"); @@ -275,14 +438,14 @@ export async function recoverCoinMelt( old_age_commitment_h: oldCoin.ageCommitmentProof ? AgeRestriction.hashCommitment(oldCoin.ageCommitmentProof.commitment) : undefined, - refresh_seed: melt.refresh_seed, + refresh_seed: melt.refresh_seed!, blinding_seed: derived.blindingSeed, confirm_sig: derived.confirmSig, coin_evs: derived.planchets.map((batch) => batch.map((c) => c.coinEv)), ...(derived.protocolVersion !== 27 ? { transfer_pubs: derived.transferPubs } : {}), - denoms_h: melt.denoms_h, + denoms_h: melt.denoms_h!, value_with_fee: Amounts.stringify(derived.meltValueWithFee), }, }), @@ -347,12 +510,31 @@ export async function recoverCoinMelt( "Wrong number of refreshed coin signatures", ); } + return { planchets: derived.planchets[index], evSigs: reveal.ev_sigs }; +} + +/** Unblind and check the fresh coins and build the finished refresh. */ +async function buildRecoveredRefresh( + wex: WalletExecutionContext, + oldCoin: WalletCoin, + oldDenom: WalletDenomination, + melt: CoinMeltTransaction, + newDenoms: RefreshNewDenomInfo[], + session: WalletRefreshSession, + planchets: RefreshPlanchetInfo[], + evSigs: BlindedDenominationSignature[], +): Promise<{ + coins: WalletCoin[]; + group: WalletRefreshGroup; + session: WalletRefreshSession; +}> { + const { refreshGroupId, amountRefreshOutput } = session; const transactionId = new RefreshTransactionContext(wex, refreshGroupId) .transactionId; const coins: WalletCoin[] = []; for (let i = 0; i < newDenoms.length; i++) { checkCancelled(wex); - const pc = derived.planchets[index][i]; + const pc = planchets[i]; const d = newDenoms[i]; const denomSig = await wex.cryptoApi.unblindDenominationSignature({ planchet: { @@ -360,7 +542,7 @@ export async function recoverCoinMelt( denomPub: d.denomPub, exchangeWithdrawValues: pc.exchangeWithdrawValues, }, - evSig: reveal.ev_sigs[i], + evSig: evSigs[i], }); const coinPubHash = encodeCrock( hashCoinPub( @@ -392,10 +574,12 @@ export async function recoverCoinMelt( status: CoinStatus.Dormant, coinSource: { type: CoinSourceType.Refresh, + // The revealed batch, from a replay or from the REVEAL entry; the + // melt's rc is its commitment. recoupBatch: { - commitment: derived.hash, + commitment: melt.rc, coinIndex: i, - envelopeHashes: derived.planchets[index].map((p) => p.coinEvHash), + envelopeHashes: planchets.map((p) => p.coinEvHash), }, refreshGroupId, oldCoinPub: oldCoin.coinPub, @@ -657,6 +841,10 @@ async function runCoinRecovery( let failed = false; for (const melt of history.history) { if (melt.type !== "MELT") continue; + const revealEntry = history.history.find( + (r): r is CoinRevealTransaction => + r.type === "REVEAL" && r.rc === melt.rc, + ); try { const recovered = await recoverCoinMelt( wex, @@ -664,6 +852,7 @@ async function runCoinRecovery( denom, melt, phase, + revealEntry, ); checkCancelled(wex); await wex.runWalletDbTx(async (tx) => {