From 1f68727f3178e5c4178d10229f7b4f3ebd406759 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Mon, 30 Nov 2015 17:58:58 +0000 Subject: [PATCH] Cash: add an onlyParties parameter to the spend crafting method. This allows you to restrict the wallet to only cash issued by particular parties. --- src/contracts/Cash.kt | 17 ++++++++++++++--- tests/contracts/CashTests.kt | 7 +++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/contracts/Cash.kt b/src/contracts/Cash.kt index 50a39bea48..9d198baacf 100644 --- a/src/contracts/Cash.kt +++ b/src/contracts/Cash.kt @@ -154,9 +154,14 @@ class Cash : Contract { /** * Generate a transaction that consumes one or more of the given input states to move money to the given pubkey. * Note that the wallet list is not updated: it's up to you to do that. + * + * @param onlyFromParties if non-null, the wallet will be filtered to only include cash states issued by the set + * of given parties. This can be useful if the party you're trying to pay has expectations + * about which type of cash claims they are willing to accept. */ @Throws(InsufficientBalanceException::class) - fun craftSpend(tx: PartialTransaction, amount: Amount, to: PublicKey, wallet: List>) { + fun craftSpend(tx: PartialTransaction, amount: Amount, to: PublicKey, + wallet: List>, onlyFromParties: Set? = null) { // Discussion // // This code is analogous to the Wallet.send() set of methods in bitcoinj, and has the same general outline. @@ -178,11 +183,17 @@ class Cash : Contract { // Finally, we add the states to the provided partial transaction. val currency = amount.currency - val coinsOfCurrency = wallet.filter { it.state.amount.currency == currency } + val acceptableCoins = run { + val ofCurrency = wallet.filter { it.state.amount.currency == currency } + if (onlyFromParties != null) + ofCurrency.filter { it.state.deposit.party in onlyFromParties } + else + ofCurrency + } val gathered = arrayListOf>() var gatheredAmount = Amount(0, currency) - for (c in coinsOfCurrency) { + for (c in acceptableCoins) { if (gatheredAmount >= amount) break gathered.add(c) gatheredAmount += c.state.amount diff --git a/tests/contracts/CashTests.kt b/tests/contracts/CashTests.kt index 465a6c276a..8d9b3259a3 100644 --- a/tests/contracts/CashTests.kt +++ b/tests/contracts/CashTests.kt @@ -316,6 +316,13 @@ class CashTests { assertEquals(OUR_PUBKEY_1, wtx.commands[0].pubkeys[0]) } + @Test + fun craftSimpleSpendWithParties() { + val tx = PartialTransaction() + Cash().craftSpend(tx, 80.DOLLARS, ALICE, WALLET, setOf(MINI_CORP)) + assertEquals(WALLET[2].ref, tx.inputStates()[0]) + } + @Test fun craftSimpleSpendWithChange() { val wtx = makeSpend(10.DOLLARS, THEIR_PUBKEY_1)