From da63ad57a481a39d419a98f7c9ce94fef0acf8c3 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Mon, 8 Aug 2016 15:54:08 +0200 Subject: [PATCH 1/3] Minor: run intellij "code cleanup" on all but javascript files. --- .../com/r3corda/contracts/clause/Net.kt | 8 ++-- .../r3corda/core/crypto/X509UtilitiesTest.kt | 2 +- .../contracts/universal/Arrangement.kt | 2 +- .../com/r3corda/contracts/universal/Util.kt | 4 +- .../contracts/BillOfLadingAgreementTests.kt | 48 +++++++++---------- .../com/r3corda/contracts/InvoiceTests.kt | 8 ++-- .../kotlin/com/r3corda/contracts/LOCTests.kt | 44 ++++++++--------- 7 files changed, 58 insertions(+), 58 deletions(-) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt b/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt index dee60e570c..506adfee13 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt @@ -67,10 +67,10 @@ open class NetClause

: SingleClause { * Verify a netting command. This handles both close-out and payment netting. */ @VisibleForTesting - public fun verifyNetCommand(inputs: List>, - outputs: List>, - command: AuthenticatedObject, - netState: NetState

) { + fun verifyNetCommand(inputs: List>, + outputs: List>, + command: AuthenticatedObject, + netState: NetState

) { val template = netState.template // Create two maps of balances from obligors to beneficiaries, one for input states, the other for output states. val inputBalances = extractAmountsDue(template, inputs) diff --git a/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt b/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt index ff4168c6ce..71b845af4f 100644 --- a/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt @@ -196,7 +196,7 @@ class X509UtilitiesTest { val context = SSLContext.getInstance("TLS") val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) keyManagerFactory.init(keyStore, "serverstorepass".toCharArray()) - val keyManagers = keyManagerFactory.getKeyManagers() + val keyManagers = keyManagerFactory.keyManagers val trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) trustMgrFactory.init(trustStore) val trustManagers = trustMgrFactory.trustManagers diff --git a/experimental/src/main/kotlin/com/r3corda/contracts/universal/Arrangement.kt b/experimental/src/main/kotlin/com/r3corda/contracts/universal/Arrangement.kt index e7ac7a0fa2..53056fe19b 100644 --- a/experimental/src/main/kotlin/com/r3corda/contracts/universal/Arrangement.kt +++ b/experimental/src/main/kotlin/com/r3corda/contracts/universal/Arrangement.kt @@ -19,7 +19,7 @@ interface Arrangement // A base arrangement with no rights and no obligations. Contract cancellation/termination is a transition to ``Zero``. class Zero() : Arrangement { override fun hashCode(): Int { - return 0; + return 0 } override fun equals(other: Any?): Boolean { return other is Zero diff --git a/experimental/src/main/kotlin/com/r3corda/contracts/universal/Util.kt b/experimental/src/main/kotlin/com/r3corda/contracts/universal/Util.kt index ef8ad8ed38..2f1ace5b9e 100644 --- a/experimental/src/main/kotlin/com/r3corda/contracts/universal/Util.kt +++ b/experimental/src/main/kotlin/com/r3corda/contracts/universal/Util.kt @@ -34,7 +34,7 @@ fun liableParties(contract: Arrangement) : Set { throw IllegalArgumentException() } - return visit(contract); + return visit(contract) } /** returns list of involved parties for a given contract */ @@ -53,7 +53,7 @@ fun involvedParties(arrangement: Arrangement) : Set { } } - return visit(arrangement); + return visit(arrangement) } fun replaceParty(action: Action, from: Party, to: Party) : Action { diff --git a/experimental/src/test/kotlin/com/r3corda/contracts/BillOfLadingAgreementTests.kt b/experimental/src/test/kotlin/com/r3corda/contracts/BillOfLadingAgreementTests.kt index e22564b3e7..cf634be1d4 100644 --- a/experimental/src/test/kotlin/com/r3corda/contracts/BillOfLadingAgreementTests.kt +++ b/experimental/src/test/kotlin/com/r3corda/contracts/BillOfLadingAgreementTests.kt @@ -36,7 +36,7 @@ class BillOfLadingAgreementTests { quantity = 2500.0, unit = LocDataStructures.WeightUnit.KG ) - ); + ) val Bill = BillOfLadingAgreement.State( owner = MEGA_CORP_PUBKEY, beneficiary = BOB, @@ -149,14 +149,14 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) //There are multiple commands - this.`fails with`("List has more than one element."); + this `fails with` "List has more than one element." } transaction { input { Bill } output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } timestamp(Instant.now()) //There are no commands - this.`fails with`("Required ${BillOfLadingAgreement.Commands::class.qualifiedName} command"); + this `fails with` "Required ${BillOfLadingAgreement.Commands::class.qualifiedName} command" } } @@ -167,7 +167,7 @@ class BillOfLadingAgreementTests { output { Bill } command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() } timestamp(Instant.now()) - this.verifies(); + this.verifies() } transaction { @@ -175,14 +175,14 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() } timestamp(Instant.now()) - this.`fails with`("there is no input state"); + this `fails with` "there is no input state" } transaction { output { Bill } command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() } timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the carrier"); + this `fails with` "the transaction is signed by the carrier" } } @@ -194,7 +194,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) - this.verifies(); + this.verifies() } transaction { @@ -202,7 +202,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } //There is no timestamp - this.`fails with`("must be timestamped"); + this `fails with` "must be timestamped" } transaction { @@ -212,7 +212,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) //There are two inputs - this.`fails with`("List has more than one element."); + this `fails with` "List has more than one element." } transaction { @@ -220,7 +220,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) //There are no inputs - this.`fails with`("List is empty."); + this `fails with` "List is empty." } transaction { @@ -230,7 +230,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) //There are two outputs - this.`fails with`("List has more than one element."); + this `fails with` "List has more than one element." } transaction { @@ -238,7 +238,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) //There are no outputs - this.`fails with`("List is empty."); + this `fails with` "List is empty." } transaction { @@ -246,7 +246,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the beneficiary"); + this `fails with` "the transaction is signed by the beneficiary" } transaction { @@ -254,7 +254,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) } command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the state object owner"); + this `fails with` "the transaction is signed by the state object owner" } transaction { @@ -262,7 +262,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE, props = pros.copy(nameOfVessel = "Svet")) } command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } timestamp(Instant.now()) - this.`fails with`("the bill of lading agreement properties are unchanged"); + this `fails with` "the bill of lading agreement properties are unchanged" } } @@ -274,7 +274,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY) } command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) - this.verifies(); + this.verifies() } transaction { @@ -282,7 +282,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY) } command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } //There is no timestamp - this.`fails with`("must be timestamped"); + this `fails with` "must be timestamped" } transaction { @@ -292,7 +292,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) //There are two inputs - this.`fails with`("List has more than one element."); + this `fails with` "List has more than one element." } transaction { @@ -300,7 +300,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) //There are no inputs - this.`fails with`("List is empty."); + this `fails with` "List is empty." } transaction { @@ -310,7 +310,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) //There are two outputs - this.`fails with`("List has more than one element."); + this `fails with` "List has more than one element." } transaction { @@ -318,7 +318,7 @@ class BillOfLadingAgreementTests { command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) //There are no outputs - this.`fails with`("List is empty."); + this `fails with` "List is empty." } transaction { @@ -326,7 +326,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY) } command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the state object owner"); + this `fails with` "the transaction is signed by the state object owner" } transaction { @@ -334,7 +334,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY,beneficiary = CHARLIE) } command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) - this.`fails with`("the beneficiary is unchanged"); + this `fails with` "the beneficiary is unchanged" } @@ -343,7 +343,7 @@ class BillOfLadingAgreementTests { output { Bill.copy(owner = CHARLIE_PUBKEY, props = pros.copy(nameOfVessel = "Svet")) } command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() } timestamp(Instant.now()) - this.`fails with`("the bill of lading agreement properties are unchanged"); + this `fails with` "the bill of lading agreement properties are unchanged" } } diff --git a/experimental/src/test/kotlin/com/r3corda/contracts/InvoiceTests.kt b/experimental/src/test/kotlin/com/r3corda/contracts/InvoiceTests.kt index be2d427214..17e29a1d55 100644 --- a/experimental/src/test/kotlin/com/r3corda/contracts/InvoiceTests.kt +++ b/experimental/src/test/kotlin/com/r3corda/contracts/InvoiceTests.kt @@ -73,7 +73,7 @@ class InvoiceTests { this `fails with` "the transaction is signed by the invoice owner" } - var props = invoiceProperties.copy(seller = invoiceProperties.buyer); + var props = invoiceProperties.copy(seller = invoiceProperties.buyer) transaction { output { initialInvoiceState.copy(props = props) } command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() } @@ -88,7 +88,7 @@ class InvoiceTests { this `fails with` "the invoice must not be assigned" } - props = invoiceProperties.copy(invoiceID = ""); + props = invoiceProperties.copy(invoiceID = "") transaction { output { initialInvoiceState.copy(props = props) } command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() } @@ -98,7 +98,7 @@ class InvoiceTests { val withMessage = "the term must be a positive number" val r = try { - props = invoiceProperties.copy(term = 0); + props = invoiceProperties.copy(term = 0) false } catch (e: Exception) { val m = e.message @@ -179,7 +179,7 @@ class InvoiceTests { this `fails with` "the transaction must be signed by the owner" } - var props = invoiceProperties.copy(seller = invoiceProperties.buyer); + var props = invoiceProperties.copy(seller = invoiceProperties.buyer) transaction { input { initialInvoiceState } output { initialInvoiceState.copy(props = props) } diff --git a/experimental/src/test/kotlin/com/r3corda/contracts/LOCTests.kt b/experimental/src/test/kotlin/com/r3corda/contracts/LOCTests.kt index 4c0b8fca94..d70c0ac632 100644 --- a/experimental/src/test/kotlin/com/r3corda/contracts/LOCTests.kt +++ b/experimental/src/test/kotlin/com/r3corda/contracts/LOCTests.kt @@ -154,19 +154,19 @@ class LOCTests { output { LOCstate.copy(issued = false) } command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() } timestamp(Instant.now()) - this.`fails with`("the LOC must be Issued"); + this `fails with` "the LOC must be Issued" } transaction { output { LOCstate.copy(beneficiaryPaid = true, issued = true) } command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() } timestamp(Instant.now()) - this.`fails with`("Demand Presentation must not be preformed successfully"); + this `fails with` "Demand Presentation must not be preformed successfully" } transaction { output { LOCstate.copy(terminated = true, issued = true) } command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() } timestamp(Instant.now()) - this.`fails with`("LOC must not be terminated"); + this `fails with` "LOC must not be terminated" } transaction { output { LOCstate.copy(issued = true) } @@ -179,7 +179,7 @@ class LOCTests { // output { LOCstate.copy() } command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() } timestamp(Instant.now()) - this.`fails with`("the period of presentation must be a positive number"); + this `fails with` "the period of presentation must be a positive number" } } @@ -199,7 +199,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.verifies(); + this.verifies() } transaction { @@ -215,7 +215,7 @@ class LOCTests { command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()} command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the issuing bank"); + this `fails with` "the transaction is signed by the issuing bank" } transaction { @@ -231,7 +231,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the Beneficiary"); + this `fails with` "the transaction is signed by the Beneficiary" } transaction { @@ -247,7 +247,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the LOC properties do not remain the same"); + this `fails with` "the LOC properties do not remain the same" } transaction { @@ -263,7 +263,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the shipment is late"); + this `fails with` "the shipment is late" } transaction { @@ -279,7 +279,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the cash state has not been transferred"); + this `fails with` "the cash state has not been transferred" } transaction { @@ -295,7 +295,7 @@ class LOCTests { command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() } command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the bill of lading has not been transferred"); + this `fails with` "the bill of lading has not been transferred" } /* transaction { @@ -327,7 +327,7 @@ class LOCTests { command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()} command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the beneficiary has not been paid, status not changed"); + this `fails with` "the beneficiary has not been paid, status not changed" } transaction { @@ -343,7 +343,7 @@ class LOCTests { command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()} command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the LOC must be Issued"); + this `fails with` "the LOC must be Issued" } transaction { @@ -359,7 +359,7 @@ class LOCTests { command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()} command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("LOC must not be terminated"); + this `fails with` "LOC must not be terminated" } } @@ -375,7 +375,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.verifies(); + this.verifies() } transaction { input { LOCstate.copy(issued = true, beneficiaryPaid = true) } @@ -385,7 +385,7 @@ class LOCTests { command(ALICE_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the transaction is signed by the issuing bank"); + this `fails with` "the transaction is signed by the issuing bank" } /*transaction { @@ -407,7 +407,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the cash state has not been transferred"); + this `fails with` "the cash state has not been transferred" } transaction { @@ -418,7 +418,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("Empty collection can't be reduced"); + this `fails with` "Empty collection can't be reduced" } transaction { @@ -429,7 +429,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the beneficiary has not been paid, status not changed"); + this `fails with` "the beneficiary has not been paid, status not changed" } transaction { @@ -440,7 +440,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the LOC must be Issued"); + this `fails with` "the LOC must be Issued" } transaction { input { LOCstate.copy(issued = true, beneficiaryPaid = true) } @@ -450,7 +450,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("LOC should be terminated"); + this `fails with` "LOC should be terminated" } transaction { @@ -461,7 +461,7 @@ class LOCTests { command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() } command(CHARLIE_PUBKEY) {Cash.Commands.Move()} timestamp(Instant.now()) - this.`fails with`("the LOC properties do not remain the same"); + this `fails with` "the LOC properties do not remain the same" } } From 2bc77ae09574497cae12b9ab32e101e81a9d31db Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Mon, 8 Aug 2016 15:56:51 +0200 Subject: [PATCH 2/3] Minor: suppress bogus "cast never succeeds" compiler warning in whitelist manager unit test --- .../kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt b/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt index a32e55e4ff..e92826f566 100644 --- a/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt @@ -13,6 +13,8 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue +// We cast null to things in order to select overloads here but Kotlin doesn't know that it's OK. +@Suppress("CAST_NEVER_SUCCEEDS") class WhitelistTrustManagerTest { companion object { @BeforeClass From 87047c8996f0ae0a34277d89fe28b6555c616ec4 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Mon, 8 Aug 2016 16:19:28 +0200 Subject: [PATCH 3/3] Minor: fix various inspector warnings and delete some dead code. --- .../contracts/JavaCommercialPaper.java | 4 +- .../com/r3corda/contracts/CommercialPaper.kt | 2 +- .../contracts/CommercialPaperLegacy.kt | 2 +- .../kotlin/com/r3corda/contracts/IRSUtils.kt | 2 +- .../com/r3corda/contracts/asset/Cash.kt | 7 +-- .../contracts/asset/CommodityContract.kt | 9 ++-- .../r3corda/contracts/asset/FungibleAsset.kt | 1 - .../com/r3corda/contracts/asset/Obligation.kt | 15 +++--- .../r3corda/contracts/asset/OnLedgerAsset.kt | 5 +- .../clause/AbstractConserveAmount.kt | 6 +-- .../r3corda/contracts/clause/AbstractIssue.kt | 2 +- .../com/r3corda/contracts/clause/Net.kt | 1 + .../contracts/clause/NoZeroSizedOutputs.kt | 2 +- .../protocols/TwoPartyTradeProtocol.kt | 2 +- .../contracts/asset/CashTestsJava.java | 8 +-- .../kotlin/com/r3corda/contracts/IRSTests.kt | 4 +- .../contracts/asset/ObligationTests.kt | 26 +++++----- .../java/com/r3corda/core/crypto/Base58.java | 2 +- .../src/main/kotlin/com/r3corda/core/Utils.kt | 15 +++--- .../r3corda/core/contracts/ContractsDSL.kt | 10 ++-- .../r3corda/core/contracts/FinanceTypes.kt | 12 +++-- .../com/r3corda/core/contracts/Structures.kt | 2 +- .../core/contracts/TransactionVerification.kt | 5 -- .../contracts/clauses/GroupClauseVerifier.kt | 2 +- .../r3corda/core/crypto/CryptoUtilities.kt | 5 +- .../com/r3corda/core/messaging/Messaging.kt | 3 +- .../core/node/PhysicalLocationStructures.kt | 1 + .../core/protocols/ProtocolLogicRef.kt | 2 +- .../com/r3corda/core/serialization/Kryo.kt | 5 +- .../core/serialization/SerializationToken.kt | 4 +- .../com/r3corda/core/testing/CoreTestUtils.kt | 1 - .../core/testing/LedgerDSLInterpreter.kt | 6 --- .../com/r3corda/core/testing/TestDSL.kt | 6 +-- .../com/r3corda/core/utilities/NonEmptySet.kt | 8 +-- .../r3corda/core/utilities/ProgressTracker.kt | 1 + .../r3corda/core/utilities/RecordingMap.kt | 50 ------------------- .../AbstractStateReplacementProtocol.kt | 22 ++++---- .../com/r3corda/protocols/RatesFixProtocol.kt | 3 +- .../r3corda/protocols/TwoPartyDealProtocol.kt | 18 +++---- .../ProtocolLogicRefFromJavaTest.java | 15 +++--- .../com/r3corda/core/FinanceTypesTest.kt | 14 +++--- .../core/crypto/WhitelistTrustManagerTest.kt | 2 +- .../r3corda/core/crypto/X509UtilitiesTest.kt | 1 - .../core/protocols/ProtocolLogicRefTest.kt | 13 ++--- .../TransactionSerializationTests.kt | 3 -- .../core/utilities/ProgressTrackerTest.kt | 4 +- .../ResolveTransactionsProtocolTest.kt | 4 ++ .../main/kotlin/com/r3corda/node/api/Query.kt | 9 ---- .../com/r3corda/node/internal/AbstractNode.kt | 15 +++--- .../r3corda/node/internal/testing/MockNode.kt | 5 +- .../node/internal/testing/Simulation.kt | 10 ++-- .../node/services/api/AbstractNodeService.kt | 1 - .../node/services/api/CheckpointStorage.kt | 1 - .../clientapi/FixingSessionInitiation.kt | 1 - .../services/clientapi/NodeInterestRates.kt | 8 +-- .../network/InMemoryMessagingNetwork.kt | 20 ++++---- .../network/InMemoryNetworkMapCache.kt | 5 +- .../services/network/MockNetworkMapCache.kt | 6 +-- .../services/network/NetworkMapService.kt | 2 +- .../persistence/DataVendingService.kt | 2 +- .../persistence/NodeAttachmentService.kt | 4 +- .../persistence/PerFileCheckpointStorage.kt | 2 +- .../services/statemachine/FiberRequest.kt | 14 +++--- .../wallet/CashBalanceAsMetricsObserver.kt | 8 +-- .../node/utilities/ANSIProgressObserver.kt | 1 - .../com/r3corda/node/utilities/FiberBox.kt | 2 +- .../com/r3corda/node/utilities/JsonSupport.kt | 2 - .../node/services/MockServiceHubInternal.kt | 1 + .../node/services/NodeInterestRatesTest.kt | 3 +- .../node/services/NodeSchedulerServiceTest.kt | 4 +- .../PerFileCheckpointStorageTests.kt | 1 - .../statemachine/StateMachineManagerTests.kt | 1 - .../node/visualiser/GroupToGraphConversion.kt | 1 + .../r3corda/node/visualiser/StateViewer.java | 2 +- .../kotlin/com/r3corda/demos/RateFixDemo.kt | 2 +- .../com/r3corda/demos/irswebdemo/js/Deal.js | 8 +-- .../com/r3corda/demos/irswebdemo/js/app.js | 2 +- .../demos/irswebdemo/js/controllers/Home.js | 4 +- .../demos/irswebdemo/js/services/NodeApi.js | 12 ++--- .../js/utils/dayCountBasisLookup.js | 2 +- 80 files changed, 210 insertions(+), 288 deletions(-) delete mode 100644 core/src/main/kotlin/com/r3corda/core/utilities/RecordingMap.kt create mode 100644 core/src/test/kotlin/com/r3corda/protocols/ResolveTransactionsProtocolTest.kt diff --git a/contracts/src/main/java/com/r3corda/contracts/JavaCommercialPaper.java b/contracts/src/main/java/com/r3corda/contracts/JavaCommercialPaper.java index b589d0ffb6..3985966652 100644 --- a/contracts/src/main/java/com/r3corda/contracts/JavaCommercialPaper.java +++ b/contracts/src/main/java/com/r3corda/contracts/JavaCommercialPaper.java @@ -24,7 +24,7 @@ import static kotlin.collections.CollectionsKt.*; */ public class JavaCommercialPaper extends ClauseVerifier { //public static SecureHash JCP_PROGRAM_ID = SecureHash.sha256("java commercial paper (this should be a bytecode hash)"); - public static Contract JCP_PROGRAM_ID = new JavaCommercialPaper(); + private static final Contract JCP_PROGRAM_ID = new JavaCommercialPaper(); public static class State implements ContractState, ICommercialPaperState { private PartyAndReference issuance; @@ -326,7 +326,7 @@ public class JavaCommercialPaper extends ClauseVerifier { public Collection> extractCommands(@NotNull TransactionForContract tx) { return tx.getCommands() .stream() - .filter((AuthenticatedObject command) -> { return command.getValue() instanceof Commands; }) + .filter((AuthenticatedObject command) -> command.getValue() instanceof Commands) .collect(Collectors.toList()); } diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaper.kt b/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaper.kt index 91c1fb1f78..712bec598e 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaper.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaper.kt @@ -205,7 +205,7 @@ class CommercialPaper : ClauseVerifier() { @Throws(InsufficientBalanceException::class) fun generateRedeem(tx: TransactionBuilder, paper: StateAndRef, wallet: List>) { // Add the cash movement using the states in our wallet. - val amount = paper.state.data.faceValue.let { amount -> Amount(amount.quantity, amount.token.product) } + val amount = paper.state.data.faceValue.let { amount -> Amount(amount.quantity, amount.token.product) } Cash().generateSpend(tx, amount, paper.state.data.owner, wallet) tx.addInputState(paper) tx.addCommand(CommercialPaper.Commands.Redeem(paper.state.notary), paper.state.data.owner) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaperLegacy.kt b/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaperLegacy.kt index 081a406382..c87795b862 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaperLegacy.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/CommercialPaperLegacy.kt @@ -55,7 +55,7 @@ class CommercialPaperLegacy : Contract { override fun verify(tx: TransactionForContract) { // Group by everything except owner: any modification to the CP at all is considered changing it fundamentally. - val groups = tx.groupStates() { it: State -> it.withoutOwner() } + val groups = tx.groupStates(State::withoutOwner) // There are two possible things that can be done with this CP. The first is trading it. The second is redeeming // it for cash on or after the maturity date. diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/IRSUtils.kt b/contracts/src/main/kotlin/com/r3corda/contracts/IRSUtils.kt index a590cc7077..55aec6d42d 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/IRSUtils.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/IRSUtils.kt @@ -79,7 +79,7 @@ class ReferenceRate(val oracle: String, val tenor: Tenor, val name: String) : Fl } // TODO: For further discussion. -operator fun Amount.times(other: RatioUnit): Amount = Amount((BigDecimal(this.quantity).multiply(other.value)).longValueExact(), this.token) +operator fun Amount.times(other: RatioUnit): Amount = Amount((BigDecimal(this.quantity).multiply(other.value)).longValueExact(), this.token) //operator fun Amount.times(other: FixedRate): Amount = Amount((BigDecimal(this.pennies).multiply(other.value)).longValueExact(), this.currency) //fun Amount.times(other: InterestRateSwap.RatioUnit): Amount = Amount((BigDecimal(this.pennies).multiply(other.value)).longValueExact(), this.currency) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/asset/Cash.kt b/contracts/src/main/kotlin/com/r3corda/contracts/asset/Cash.kt index 5758cc47db..fe954a669f 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/asset/Cash.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/asset/Cash.kt @@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount import com.r3corda.contracts.clause.AbstractIssue import com.r3corda.contracts.clause.NoZeroSizedOutputs import com.r3corda.core.contracts.* -import com.r3corda.core.contracts.clauses.* +import com.r3corda.core.contracts.clauses.GroupClauseVerifier +import com.r3corda.core.contracts.clauses.MatchBehaviour import com.r3corda.core.crypto.* import com.r3corda.core.node.services.Wallet import com.r3corda.core.utilities.Emoji @@ -81,7 +82,7 @@ class Cash : OnLedgerAsset() { override val owner: PublicKey ) : FungibleAsset { constructor(deposit: PartyAndReference, amount: Amount, owner: PublicKey) - : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) + : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) override val deposit = amount.token.issuer override val exitKeys = setOf(deposit.party.owningKey) @@ -165,7 +166,7 @@ fun Iterable.sumCashOrNull(): Amount>? = filterI /** Sums the cash states in the list, returning zero of the given currency+issuer if there are none. */ fun Iterable.sumCashOrZero(currency: Issued): Amount> { - return filterIsInstance().map { it.amount }.sumOrZero>(currency) + return filterIsInstance().map { it.amount }.sumOrZero(currency) } /** diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/asset/CommodityContract.kt b/contracts/src/main/kotlin/com/r3corda/contracts/asset/CommodityContract.kt index 632eb20b9f..d929a1723c 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/asset/CommodityContract.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/asset/CommodityContract.kt @@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount import com.r3corda.contracts.clause.AbstractIssue import com.r3corda.contracts.clause.NoZeroSizedOutputs import com.r3corda.core.contracts.* -import com.r3corda.core.contracts.clauses.* +import com.r3corda.core.contracts.clauses.GroupClauseVerifier +import com.r3corda.core.contracts.clauses.MatchBehaviour import com.r3corda.core.crypto.Party import com.r3corda.core.crypto.SecureHash import com.r3corda.core.crypto.newSecureRandom @@ -107,7 +108,7 @@ class CommodityContract : OnLedgerAsset() { override val owner: PublicKey ) : FungibleAsset { constructor(deposit: PartyAndReference, amount: Amount, owner: PublicKey) - : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) + : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) override val deposit = amount.token.issuer override val contract = COMMODITY_PROGRAM_ID @@ -182,7 +183,7 @@ class CommodityContract : OnLedgerAsset() { fun Iterable.sumCommodities() = filterIsInstance().map { it.amount }.sumOrThrow() /** Sums the cash states in the list, returning null if there are none. */ -fun Iterable.sumCommoditiesOrNull() = filterIsInstance().map { it.amount }.sumOrNull() +@Suppress("unused") fun Iterable.sumCommoditiesOrNull() = filterIsInstance().map { it.amount }.sumOrNull() /** Sums the cash states in the list, returning zero of the given currency if there are none. */ -fun Iterable.sumCommoditiesOrZero(currency: Issued) = filterIsInstance().map { it.amount }.sumOrZero>(currency) +fun Iterable.sumCommoditiesOrZero(currency: Issued) = filterIsInstance().map { it.amount }.sumOrZero(currency) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/asset/FungibleAsset.kt b/contracts/src/main/kotlin/com/r3corda/contracts/asset/FungibleAsset.kt index 5636ab50e1..a098923bb6 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/asset/FungibleAsset.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/asset/FungibleAsset.kt @@ -2,7 +2,6 @@ package com.r3corda.contracts.asset import com.r3corda.core.contracts.* import java.security.PublicKey -import java.util.* class InsufficientBalanceException(val amountMissing: Amount<*>) : Exception() { override fun toString() = "Insufficient balance, missing $amountMissing" diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/asset/Obligation.kt b/contracts/src/main/kotlin/com/r3corda/contracts/asset/Obligation.kt index 28a8d6d312..472b2fa10d 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/asset/Obligation.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/asset/Obligation.kt @@ -181,7 +181,7 @@ class Obligation

: ClauseVerifier() { // Settle commands exclude all other commands, so we don't need to check for contracts moving at the same // time. "amounts paid must match recipients to settle" by inputs.map { it.owner }.containsAll(amountReceivedByOwner.keys) - "amount in settle command ${command.value.amount} matches settled total ${totalAmountSettled}" by (command.value.amount == totalAmountSettled) + "amount in settle command ${command.value.amount} matches settled total $totalAmountSettled" by (command.value.amount == totalAmountSettled) "signatures are present from all obligors" by command.signers.containsAll(requiredSigners) "there are no zero sized inputs" by inputs.none { it.amount.quantity == 0L } "at obligor ${obligor.name} the obligations after settlement balance" by @@ -384,7 +384,7 @@ class Obligation

: ClauseVerifier() { * A default command mutates inputs and produces identical outputs, except that the lifecycle changes. */ @VisibleForTesting - protected fun verifySetLifecycleCommand(inputs: List>>, + private fun verifySetLifecycleCommand(inputs: List>>, outputs: List>>, tx: TransactionForContract, setLifecycleCommand: AuthenticatedObject) { @@ -439,7 +439,7 @@ class Obligation

: ClauseVerifier() { "signer is in the state parties" by (signer in netState!!.partyKeys) } - val out = states.reduce { stateA, stateB -> stateA.net(stateB) } + val out = states.reduce(State

::net) if (out.quantity > 0L) tx.addOutputState(out) tx.addCommand(Commands.Net(NetType.PAYMENT), signer) @@ -456,11 +456,12 @@ class Obligation

: ClauseVerifier() { * the responsibility of the caller to check that they do not exit funds held by others. * @return the public key of the assets issuer, who must sign the transaction for it to be valid. */ + @Suppress("unused") fun generateExit(tx: TransactionBuilder, amountIssued: Amount>>, changeKey: PublicKey, assetStates: List>>): PublicKey = Clauses.ConserveAmount

().generateExit(tx, amountIssued, changeKey, assetStates, deriveState = { state, amount, owner -> state.copy(data = state.data.move(amount, owner)) }, - generateExitCommand = { amount -> Commands.Exit

(amount) } + generateExitCommand = { amount -> Commands.Exit(amount) } ) /** @@ -525,7 +526,7 @@ class Obligation

: ClauseVerifier() { Lifecycle.DEFAULTED -> Lifecycle.NORMAL Lifecycle.NORMAL -> Lifecycle.DEFAULTED } - require(states.all { it.lifecycle == existingLifecycle }) { "initial lifecycle must be ${existingLifecycle} for all input states" } + require(states.all { it.lifecycle == existingLifecycle }) { "initial lifecycle must be $existingLifecycle for all input states" } // Produce a new set of states val groups = statesAndRefs.groupBy { it.state.data.issuanceDef } @@ -713,8 +714,8 @@ infix fun Obligation.State.between(parties: Pair) = cop infix fun Obligation.State.`owned by`(owner: PublicKey) = copy(beneficiary = owner) infix fun Obligation.State.`issued by`(party: Party) = copy(obligor = party) // For Java users: -fun Obligation.State.ownedBy(owner: PublicKey) = copy(beneficiary = owner) -fun Obligation.State.issuedBy(party: Party) = copy(obligor = party) +@Suppress("unused") fun Obligation.State.ownedBy(owner: PublicKey) = copy(beneficiary = owner) +@Suppress("unused") fun Obligation.State.issuedBy(party: Party) = copy(obligor = party) val Issued.OBLIGATION_DEF: Obligation.Terms get() = Obligation.Terms(nonEmptySetOf(Cash().legalContractReference), nonEmptySetOf(this), TEST_TX_TIME) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/asset/OnLedgerAsset.kt b/contracts/src/main/kotlin/com/r3corda/contracts/asset/OnLedgerAsset.kt index 6e34b01ba4..677d24df23 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/asset/OnLedgerAsset.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/asset/OnLedgerAsset.kt @@ -2,10 +2,9 @@ package com.r3corda.contracts.asset import com.r3corda.contracts.clause.AbstractConserveAmount import com.r3corda.core.contracts.* -import com.r3corda.core.contracts.clauses.* -import com.r3corda.core.crypto.* +import com.r3corda.core.contracts.clauses.ClauseVerifier +import com.r3corda.core.crypto.Party import java.security.PublicKey -import java.util.* ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractConserveAmount.kt b/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractConserveAmount.kt index 04d553bb88..976e3f8b94 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractConserveAmount.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractConserveAmount.kt @@ -75,7 +75,7 @@ abstract class AbstractConserveAmount, T: Any> : GroupClause val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, Amount(amount.quantity, currency)) val takeChangeFrom = gathered.lastOrNull() val change = if (takeChangeFrom != null && gatheredAmount > amount) { - Amount>(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef) + Amount(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef) } else { null } @@ -139,7 +139,7 @@ abstract class AbstractConserveAmount, T: Any> : GroupClause val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, amount) val takeChangeFrom = gathered.firstOrNull() val change = if (takeChangeFrom != null && gatheredAmount > amount) { - Amount>(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef) + Amount(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef) } else { null } @@ -175,7 +175,7 @@ abstract class AbstractConserveAmount, T: Any> : GroupClause outputs: List, commands: Collection>, token: Issued): Set { - val inputAmount: Amount> = inputs.sumFungibleOrNull() ?: throw IllegalArgumentException("there is at least one asset input for group ${token}") + val inputAmount: Amount> = inputs.sumFungibleOrNull() ?: throw IllegalArgumentException("there is at least one asset input for group $token") val deposit = token.issuer val outputAmount: Amount> = outputs.sumFungibleOrZero(token) diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractIssue.kt b/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractIssue.kt index 8fd7c0e801..e94574aea8 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractIssue.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/clause/AbstractIssue.kt @@ -14,7 +14,7 @@ import com.r3corda.core.contracts.clauses.MatchBehaviour * @param sumOrZero function to convert a list of states into an amount of the token, and returns zero if there are * no states in the list. Takes in an instance of the token definition for constructing the zero amount if needed. */ -abstract class AbstractIssue( +abstract class AbstractIssue( val sum: List.() -> Amount>, val sumOrZero: List.(token: Issued) -> Amount> ) : GroupClause> { diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt b/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt index 506adfee13..cca285f51c 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/clause/Net.kt @@ -51,6 +51,7 @@ open class NetClause

: SingleClause { override val requiredCommands: Set> get() = setOf(Obligation.Commands.Net::class.java) + @Suppress("ConvertLambdaToReference") override fun verify(tx: TransactionForContract, commands: Collection>): Set { val command = commands.requireSingleCommand() val groups = when (command.value.type) { diff --git a/contracts/src/main/kotlin/com/r3corda/contracts/clause/NoZeroSizedOutputs.kt b/contracts/src/main/kotlin/com/r3corda/contracts/clause/NoZeroSizedOutputs.kt index e6b8db4159..59cd8d5688 100644 --- a/contracts/src/main/kotlin/com/r3corda/contracts/clause/NoZeroSizedOutputs.kt +++ b/contracts/src/main/kotlin/com/r3corda/contracts/clause/NoZeroSizedOutputs.kt @@ -9,7 +9,7 @@ import com.r3corda.core.contracts.clauses.MatchBehaviour * Clause for fungible asset contracts, which enforces that no output state should have * a balance of zero. */ -open class NoZeroSizedOutputs, T: Any> : GroupClause> { +open class NoZeroSizedOutputs, T: Any> : GroupClause> { override val ifMatched: MatchBehaviour get() = MatchBehaviour.CONTINUE override val ifNotMatched: MatchBehaviour diff --git a/contracts/src/main/kotlin/com/r3corda/protocols/TwoPartyTradeProtocol.kt b/contracts/src/main/kotlin/com/r3corda/protocols/TwoPartyTradeProtocol.kt index d3eebd3f93..5d58e3c772 100644 --- a/contracts/src/main/kotlin/com/r3corda/protocols/TwoPartyTradeProtocol.kt +++ b/contracts/src/main/kotlin/com/r3corda/protocols/TwoPartyTradeProtocol.kt @@ -48,7 +48,7 @@ object TwoPartyTradeProtocol { val TOPIC = "platform.trade" - class UnacceptablePriceException(val givenPrice: Amount) : Exception() + class UnacceptablePriceException(val givenPrice: Amount) : Exception("Unacceptable price: $givenPrice") class AssetMismatchException(val expectedTypeName: String, val typeName: String) : Exception() { override fun toString() = "The submitted asset didn't match the expected type: $expectedTypeName vs $typeName" } diff --git a/contracts/src/test/java/com/r3corda/contracts/asset/CashTestsJava.java b/contracts/src/test/java/com/r3corda/contracts/asset/CashTestsJava.java index 55c5fed4e3..c6e1f874ef 100644 --- a/contracts/src/test/java/com/r3corda/contracts/asset/CashTestsJava.java +++ b/contracts/src/test/java/com/r3corda/contracts/asset/CashTestsJava.java @@ -12,10 +12,10 @@ import static com.r3corda.core.testing.CoreTestUtils.*; * This is an incomplete Java replica of CashTests.kt to show how to use the Java test DSL */ public class CashTestsJava { - private OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1}); - private PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef); - private Cash.State inState = new Cash.State(issuedBy(DOLLARS(1000), defaultIssuer), getDUMMY_PUBKEY_1()); - private Cash.State outState = new Cash.State(inState.getAmount(), getDUMMY_PUBKEY_2()); + private final OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1}); + private final PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef); + private final Cash.State inState = new Cash.State(issuedBy(DOLLARS(1000), defaultIssuer), getDUMMY_PUBKEY_1()); + private final Cash.State outState = new Cash.State(inState.getAmount(), getDUMMY_PUBKEY_2()); @Test public void trivial() { diff --git a/contracts/src/test/kotlin/com/r3corda/contracts/IRSTests.kt b/contracts/src/test/kotlin/com/r3corda/contracts/IRSTests.kt index c1f3c960fa..2911676ba3 100644 --- a/contracts/src/test/kotlin/com/r3corda/contracts/IRSTests.kt +++ b/contracts/src/test/kotlin/com/r3corda/contracts/IRSTests.kt @@ -268,8 +268,8 @@ class IRSTests { LocalDate.of(2015, 12, 8) to "0.55", LocalDate.of(2016, 3, 8) to "0.644") - for (it in fixings) { - newCalculation = newCalculation.applyFixing(it.key, FixedRate(PercentageRatioUnit(it.value))) + for ((key, value) in fixings) { + newCalculation = newCalculation.applyFixing(key, FixedRate(PercentageRatioUnit(value))) } val newIRS = InterestRateSwap.State(irs.fixedLeg, irs.floatingLeg, newCalculation, irs.common) diff --git a/contracts/src/test/kotlin/com/r3corda/contracts/asset/ObligationTests.kt b/contracts/src/test/kotlin/com/r3corda/contracts/asset/ObligationTests.kt index 314e19a2df..a865fbd736 100644 --- a/contracts/src/test/kotlin/com/r3corda/contracts/asset/ObligationTests.kt +++ b/contracts/src/test/kotlin/com/r3corda/contracts/asset/ObligationTests.kt @@ -22,8 +22,8 @@ class ObligationTests { val defaultIssuer = MEGA_CORP.ref(defaultRef) val oneMillionDollars = 1000000.DOLLARS `issued by` defaultIssuer val trustedCashContract = nonEmptySetOf(SecureHash.Companion.randomSHA256() as SecureHash) - val megaIssuedDollars = nonEmptySetOf(Issued(defaultIssuer, USD)) - val megaIssuedPounds = nonEmptySetOf(Issued(defaultIssuer, GBP)) + val megaIssuedDollars = nonEmptySetOf(Issued(defaultIssuer, USD)) + val megaIssuedPounds = nonEmptySetOf(Issued(defaultIssuer, GBP)) val fivePm = TEST_TX_TIME.truncatedTo(ChronoUnit.DAYS).plus(17, ChronoUnit.HOURS) val sixPm = fivePm.plus(1, ChronoUnit.HOURS) val megaCorpDollarSettlement = Obligation.Terms(trustedCashContract, megaIssuedDollars, fivePm) @@ -181,7 +181,7 @@ class ObligationTests { this `fails with` "All commands must be matched at end of execution." } tweak { - command(MEGA_CORP_PUBKEY) { Obligation.Commands.Exit(inState.amount / 2) } + command(MEGA_CORP_PUBKEY) { Obligation.Commands.Exit(inState.amount / 2) } this `fails with` "All commands must be matched at end of execution." } this.verifies() @@ -451,7 +451,7 @@ class ObligationTests { input("Alice's $1,000,000 obligation to Bob") input("Alice's $1,000,000") output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY } - command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) } + command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) } command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation().legalContractReference) } this.verifies() } @@ -465,7 +465,7 @@ class ObligationTests { input(500000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY) output("Alice's $500,000 obligation to Bob") { halfAMillionDollars.OBLIGATION between Pair(ALICE, BOB_PUBKEY) } output("Bob's $500,000") { 500000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY } - command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) } + command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) } command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation().legalContractReference) } this.verifies() } @@ -478,7 +478,7 @@ class ObligationTests { input(defaultedObligation) // Alice's defaulted $1,000,000 obligation to Bob input(1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY) output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY } - command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) } + command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) } command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation().legalContractReference) } this `fails with` "all inputs are in the normal state" } @@ -491,7 +491,7 @@ class ObligationTests { input("Alice's $1,000,000 obligation to Bob") input("Alice's $1,000,000") output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY } - command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) } + command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) } command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation().legalContractReference) } this `fails with` "amount in settle command" } @@ -502,7 +502,7 @@ class ObligationTests { fun `commodity settlement`() { val defaultFcoj = FCOJ `issued by` defaultIssuer val oneUnitFcoj = Amount(1, defaultFcoj) - val obligationDef = Obligation.Terms(nonEmptySetOf(CommodityContract().legalContractReference), nonEmptySetOf(defaultFcoj), TEST_TX_TIME) + val obligationDef = Obligation.Terms(nonEmptySetOf(CommodityContract().legalContractReference), nonEmptySetOf(defaultFcoj), TEST_TX_TIME) val oneUnitFcojObligation = Obligation.State(Obligation.Lifecycle.NORMAL, ALICE, obligationDef, oneUnitFcoj.quantity, NullPublicKey) // Try settling a simple commodity obligation @@ -515,7 +515,7 @@ class ObligationTests { input("Alice's 1 FCOJ obligation to Bob") input("Alice's 1 FCOJ") output("Bob's 1 FCOJ") { CommodityContract.State(oneUnitFcoj, BOB_PUBKEY) } - command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneUnitFcoj.quantity, oneUnitFcojObligation.issuanceDef)) } + command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneUnitFcoj.quantity, oneUnitFcojObligation.issuanceDef)) } command(ALICE_PUBKEY) { CommodityContract.Commands.Move(Obligation().legalContractReference) } verifies() } @@ -646,13 +646,13 @@ class ObligationTests { output { outState.copy(quantity = inState.quantity - 200.DOLLARS.quantity) } tweak { - command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(100.DOLLARS.quantity, inState.issuanceDef)) } + command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(100.DOLLARS.quantity, inState.issuanceDef)) } command(DUMMY_PUBKEY_1) { Obligation.Commands.Move() } this `fails with` "the amounts balance" } tweak { - command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(200.DOLLARS.quantity, inState.issuanceDef)) } + command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(200.DOLLARS.quantity, inState.issuanceDef)) } this `fails with` "required com.r3corda.contracts.asset.FungibleAsset.Commands.Move command" tweak { @@ -817,7 +817,7 @@ class ObligationTests { 5000.DOLLARS.quantity, MINI_CORP_PUBKEY) val amount = fiveKDollarsFromMegaToMini.amount val expected = mapOf(Pair(Pair(MEGA_CORP_PUBKEY, MINI_CORP_PUBKEY), Amount(amount.quantity, amount.token.product))) - val actual = extractAmountsDue(megaCorpDollarSettlement, listOf(fiveKDollarsFromMegaToMini)) + val actual = extractAmountsDue(megaCorpDollarSettlement, listOf(fiveKDollarsFromMegaToMini)) assertEquals(expected, actual) } @@ -843,7 +843,7 @@ class ObligationTests { val expected = mapOf( Pair(Pair(BOB_PUBKEY, ALICE_PUBKEY), Amount(100000000, GBP)) ) - val actual = netAmountsDue(balanced) + val actual = netAmountsDue(balanced) assertEquals(expected, actual) } diff --git a/core/src/main/java/com/r3corda/core/crypto/Base58.java b/core/src/main/java/com/r3corda/core/crypto/Base58.java index 80f461b3fa..08e3836093 100644 --- a/core/src/main/java/com/r3corda/core/crypto/Base58.java +++ b/core/src/main/java/com/r3corda/core/crypto/Base58.java @@ -28,7 +28,7 @@ import java.util.*; * same as the original author of the R3 repository. */ public class Base58 { - public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); + private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final char ENCODED_ZERO = ALPHABET[0]; private static final int[] INDEXES = new int[128]; diff --git a/core/src/main/kotlin/com/r3corda/core/Utils.kt b/core/src/main/kotlin/com/r3corda/core/Utils.kt index 353700e060..7d6956a842 100644 --- a/core/src/main/kotlin/com/r3corda/core/Utils.kt +++ b/core/src/main/kotlin/com/r3corda/core/Utils.kt @@ -20,14 +20,18 @@ import kotlin.concurrent.withLock import kotlin.reflect.KProperty val Int.days: Duration get() = Duration.ofDays(this.toLong()) +@Suppress("unused") // It's here for completeness val Int.hours: Duration get() = Duration.ofHours(this.toLong()) +@Suppress("unused") // It's here for completeness val Int.minutes: Duration get() = Duration.ofMinutes(this.toLong()) val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong()) -val Int.bd: BigDecimal get() = BigDecimal(this) -val Double.bd: BigDecimal get() = BigDecimal(this) -val String.bd: BigDecimal get() = BigDecimal(this) -val Long.bd: BigDecimal get() = BigDecimal(this) + +// TODO: Review by EOY2016 if we ever found these utilities helpful. +@Suppress("unused") val Int.bd: BigDecimal get() = BigDecimal(this) +@Suppress("unused") val Double.bd: BigDecimal get() = BigDecimal(this) +@Suppress("unused") val String.bd: BigDecimal get() = BigDecimal(this) +@Suppress("unused") val Long.bd: BigDecimal get() = BigDecimal(this) fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else take(maxWidth - 1) + "…" @@ -149,8 +153,7 @@ fun logElapsedTime(label: String, logger: Logger? = null, body: () -> T): T * * val ii = state.locked { i } */ -class ThreadBox(content: T, val lock: ReentrantLock = ReentrantLock()) { - val content = content +class ThreadBox(val content: T, val lock: ReentrantLock = ReentrantLock()) { inline fun locked(body: T.() -> R): R = lock.withLock { body(content) } inline fun alreadyLocked(body: T.() -> R): R { check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." }) diff --git a/core/src/main/kotlin/com/r3corda/core/contracts/ContractsDSL.kt b/core/src/main/kotlin/com/r3corda/core/contracts/ContractsDSL.kt index f317961bc6..c2a82f1294 100644 --- a/core/src/main/kotlin/com/r3corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/com/r3corda/core/contracts/ContractsDSL.kt @@ -41,8 +41,8 @@ val Int.FCOJ: Amount get() = FCOJ(this) infix fun Currency.`issued by`(deposit: PartyAndReference) = issuedBy(deposit) infix fun Commodity.`issued by`(deposit: PartyAndReference) = issuedBy(deposit) infix fun Amount.`issued by`(deposit: PartyAndReference) = issuedBy(deposit) -infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued(deposit, this) -infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued(deposit, this) +infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued(deposit, this) +infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued(deposit, this) infix fun Amount.issuedBy(deposit: PartyAndReference) = Amount(quantity, token.issuedBy(deposit)) //// Requirements ///////////////////////////////////////////////////////////////////////////////////////////////////// @@ -64,7 +64,7 @@ inline fun Collection filter { it.value is T }. filter { if (signer == null) true else signer in it.signers }. filter { if (party == null) true else party in it.signingParties }. - map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) } + map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) } /** Filters the command list by type, parties and public keys all at once. */ inline fun Collection>.select(signers: Collection?, @@ -72,7 +72,7 @@ inline fun Collection filter { it.value is T }. filter { if (signers == null) true else it.signers.containsAll(signers)}. filter { if (parties == null) true else it.signingParties.containsAll(parties) }. - map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) } + map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) } inline fun Collection>.requireSingleCommand() = try { select().single() @@ -99,7 +99,7 @@ fun List>.getTimestampBy(timestampingAuthority: fun List>.getTimestampByName(vararg names: String): TimestampCommand? { val timestampCmd = filter { it.value is TimestampCommand }.singleOrNull() ?: return null val tsaNames = timestampCmd.signingParties.map { it.name.toLowerCase() } - val acceptableNames = names.map { it.toLowerCase() } + val acceptableNames = names.map(String::toLowerCase) val acceptableNameFound = tsaNames.intersect(acceptableNames).isNotEmpty() if (acceptableNameFound) return timestampCmd.value as TimestampCommand diff --git a/core/src/main/kotlin/com/r3corda/core/contracts/FinanceTypes.kt b/core/src/main/kotlin/com/r3corda/core/contracts/FinanceTypes.kt index 88553a1615..72b7711f4f 100644 --- a/core/src/main/kotlin/com/r3corda/core/contracts/FinanceTypes.kt +++ b/core/src/main/kotlin/com/r3corda/core/contracts/FinanceTypes.kt @@ -71,7 +71,7 @@ data class Amount(val quantity: Long, val token: T) : Comparable> { fun Iterable>.sumOrNull() = if (!iterator().hasNext()) null else sumOrThrow() fun Iterable>.sumOrThrow() = reduce { left, right -> left + right } -fun Iterable>.sumOrZero(currency: T) = if (iterator().hasNext()) sumOrThrow() else Amount(0, currency) +fun Iterable>.sumOrZero(currency: T) = if (iterator().hasNext()) sumOrThrow() else Amount(0, currency) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @@ -136,7 +136,7 @@ data class Tenor(val name: String) { return daysToMaturity.toInt() } - override fun toString(): String = "$name" + override fun toString(): String = name enum class TimeUnit(val code: String) { Day("D"), Week("W"), Month("M"), Year("Y") @@ -237,6 +237,7 @@ enum class PaymentRule { * Frequency at which an event occurs - the enumerator also casts to an integer specifying the number of times per year * that would divide into (eg annually = 1, semiannual = 2, monthly = 12 etc). */ +@Suppress("unused") // TODO: Revisit post-Vega and see if annualCompoundCount is still needed. enum class Frequency(val annualCompoundCount: Int) { Annual(1) { override fun offset(d: LocalDate, n: Long) = d.plusYears(1 * n) @@ -265,6 +266,7 @@ enum class Frequency(val annualCompoundCount: Int) { } +@Suppress("unused") // This utility may be useful in future. TODO: Review before API stability guarantees in place. fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = accordingToCalendar.isWorkingDay(this) // TODO: Make Calendar data come from an oracle @@ -274,7 +276,7 @@ fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = acc * typical feature of financial contracts, in which a business may not want a payment event to fall on a day when * no staff are around to handle problems. */ -open class BusinessCalendar private constructor(val calendars: Array, val holidayDates: List) { +open class BusinessCalendar private constructor(val holidayDates: List) { class UnknownCalendar(name: String) : Exception("$name not found") companion object { @@ -288,7 +290,7 @@ open class BusinessCalendar private constructor(val calendars: Array fun parseDateFromString(it: String) = LocalDate.parse(it, DateTimeFormatter.ISO_LOCAL_DATE) /** Returns a business calendar that combines all the named holiday calendars into one list of holiday dates. */ - fun getInstance(vararg calname: String) = BusinessCalendar(calname, + fun getInstance(vararg calname: String) = BusinessCalendar( calname.flatMap { (TEST_CALENDAR_DATA[it] ?: throw UnknownCalendar(it)).split(",") }. toSet(). map { parseDateFromString(it) }. @@ -426,7 +428,7 @@ data class Commodity(val symbol: String, val commodityCode: String = symbol, val defaultFractionDigits: Int = 0) { companion object { - private val registry = mapOf( + private val registry = mapOf( Pair("FCOJ", Commodity("FCOJ", "Frozen concentrated orange juice")) ) fun getInstance(symbol: String): Commodity? diff --git a/core/src/main/kotlin/com/r3corda/core/contracts/Structures.kt b/core/src/main/kotlin/com/r3corda/core/contracts/Structures.kt index 8bd276c240..dada08e978 100644 --- a/core/src/main/kotlin/com/r3corda/core/contracts/Structures.kt +++ b/core/src/main/kotlin/com/r3corda/core/contracts/Structures.kt @@ -40,7 +40,7 @@ interface BilateralNettableState> { /** * Interface for state objects that support being netted with other state objects. */ -interface MultilateralNettableState { +interface MultilateralNettableState { /** * Returns an object used to determine if two states can be subject to close-out netting. If two states return * equal objects, they can be close out netted together. diff --git a/core/src/main/kotlin/com/r3corda/core/contracts/TransactionVerification.kt b/core/src/main/kotlin/com/r3corda/core/contracts/TransactionVerification.kt index c93d2b56f6..8c7800f83b 100644 --- a/core/src/main/kotlin/com/r3corda/core/contracts/TransactionVerification.kt +++ b/core/src/main/kotlin/com/r3corda/core/contracts/TransactionVerification.kt @@ -21,11 +21,6 @@ data class TransactionForContract(val inputs: List, override fun hashCode() = origHash.hashCode() override fun equals(other: Any?) = other is TransactionForContract && other.origHash == origHash - @Deprecated("This property was renamed to inputs", ReplaceWith("inputs")) - val inStates: List get() = inputs - @Deprecated("This property was renamed to outputs", ReplaceWith("outputs")) - val outStates: List get() = outputs - /** * Given a type and a function that returns a grouping key, associates inputs and outputs together so that they * can be processed as one. The grouping key is any arbitrary object that can act as a map key (so must implement diff --git a/core/src/main/kotlin/com/r3corda/core/contracts/clauses/GroupClauseVerifier.kt b/core/src/main/kotlin/com/r3corda/core/contracts/clauses/GroupClauseVerifier.kt index 6bbe1ff480..db5d958416 100644 --- a/core/src/main/kotlin/com/r3corda/core/contracts/clauses/GroupClauseVerifier.kt +++ b/core/src/main/kotlin/com/r3corda/core/contracts/clauses/GroupClauseVerifier.kt @@ -19,7 +19,7 @@ interface GroupVerify { token: T): Set } -interface GroupClause : Clause, GroupVerify +interface GroupClause : Clause, GroupVerify abstract class GroupClauseVerifier : SingleClause { abstract val clauses: List> diff --git a/core/src/main/kotlin/com/r3corda/core/crypto/CryptoUtilities.kt b/core/src/main/kotlin/com/r3corda/core/crypto/CryptoUtilities.kt index dcd0261f29..6b286a6f0d 100644 --- a/core/src/main/kotlin/com/r3corda/core/crypto/CryptoUtilities.kt +++ b/core/src/main/kotlin/com/r3corda/core/crypto/CryptoUtilities.kt @@ -66,10 +66,9 @@ fun OpaqueBytes.sha256(): SecureHash.SHA256 = SecureHash.sha256(this.bits) * signature. It isn't used currently, but experience from Bitcoin suggests such a feature is useful, especially when * building partially signed transactions. */ -open class DigitalSignature(bits: ByteArray, val covering: Int = 0) : OpaqueBytes(bits) { - +open class DigitalSignature(bits: ByteArray) : OpaqueBytes(bits) { /** A digital signature that identifies who the public key is owned by. */ - open class WithKey(val by: PublicKey, bits: ByteArray, covering: Int = 0) : DigitalSignature(bits, covering) { + open class WithKey(val by: PublicKey, bits: ByteArray, covering: Int = 0) : DigitalSignature(bits) { fun verifyWithECDSA(content: ByteArray) = by.verifyWithECDSA(content, this) fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bits, this) } diff --git a/core/src/main/kotlin/com/r3corda/core/messaging/Messaging.kt b/core/src/main/kotlin/com/r3corda/core/messaging/Messaging.kt index 1bb07d52d3..4922f2f304 100644 --- a/core/src/main/kotlin/com/r3corda/core/messaging/Messaging.kt +++ b/core/src/main/kotlin/com/r3corda/core/messaging/Messaging.kt @@ -1,6 +1,5 @@ package com.r3corda.core.messaging -import com.google.common.util.concurrent.ListenableFuture import com.r3corda.core.node.services.DEFAULT_SESSION_ID import com.r3corda.core.serialization.DeserializeAsKotlinObjectDef import com.r3corda.core.serialization.serialize @@ -148,7 +147,7 @@ data class TopicSession(val topic: String, val sessionID: Long = DEFAULT_SESSION } fun isBlank() = topic.isBlank() && sessionID == DEFAULT_SESSION_ID - override fun toString(): String = "${topic}.${sessionID}" + override fun toString(): String = "$topic.$sessionID" } /** diff --git a/core/src/main/kotlin/com/r3corda/core/node/PhysicalLocationStructures.kt b/core/src/main/kotlin/com/r3corda/core/node/PhysicalLocationStructures.kt index 982c85d54c..308d3eb944 100644 --- a/core/src/main/kotlin/com/r3corda/core/node/PhysicalLocationStructures.kt +++ b/core/src/main/kotlin/com/r3corda/core/node/PhysicalLocationStructures.kt @@ -17,6 +17,7 @@ data class WorldCoordinate(val latitude: Double, val longitude: Double) { * to infinity. Google Maps, for example, uses a square map image, and square maps yield latitude extents * of 85.0511 to -85.0511 = arctan(sinh(π)). */ + @Suppress("unused") // Used from the visualiser GUI. fun project(screenWidth: Double, screenHeight: Double, topLatitude: Double, bottomLatitude: Double, leftLongitude: Double, rightLongitude: Double): Pair { require(latitude in bottomLatitude..topLatitude) diff --git a/core/src/main/kotlin/com/r3corda/core/protocols/ProtocolLogicRef.kt b/core/src/main/kotlin/com/r3corda/core/protocols/ProtocolLogicRef.kt index 5ac7fc525f..06ac12b156 100644 --- a/core/src/main/kotlin/com/r3corda/core/protocols/ProtocolLogicRef.kt +++ b/core/src/main/kotlin/com/r3corda/core/protocols/ProtocolLogicRef.kt @@ -46,7 +46,7 @@ class ProtocolLogicRefFactory(private val protocolWhitelist: Map String.output(): S = outputStateAndRef().state.data - /** - * Retrieves the output [StateRef] based on the label. - * @see OutputStateLookup.retrieveOutputStateAndRef - */ - fun String.outputRef(): StateRef = outputStateAndRef().ref - /** * @see OutputStateLookup.retrieveOutputStateAndRef */ diff --git a/core/src/main/kotlin/com/r3corda/core/testing/TestDSL.kt b/core/src/main/kotlin/com/r3corda/core/testing/TestDSL.kt index b905375f76..a8276513a8 100644 --- a/core/src/main/kotlin/com/r3corda/core/testing/TestDSL.kt +++ b/core/src/main/kotlin/com/r3corda/core/testing/TestDSL.kt @@ -40,7 +40,7 @@ import java.util.* message = "ledger doesn't nest, use tweak", replaceWith = ReplaceWith("tweak"), level = DeprecationLevel.ERROR) -@Suppress("UNUSED_PARAMETER") +@Suppress("UNUSED_PARAMETER", "unused") fun TransactionDSLInterpreter.ledger( dsl: LedgerDSL.() -> Unit) { } @@ -49,7 +49,7 @@ fun TransactionDSLInterpreter.ledger( message = "transaction doesn't nest, use tweak", replaceWith = ReplaceWith("tweak"), level = DeprecationLevel.ERROR) -@Suppress("UNUSED_PARAMETER") +@Suppress("UNUSED_PARAMETER", "unused") fun TransactionDSLInterpreter.transaction( dsl: TransactionDSL.() -> EnforceVerifyOrFail) { } @@ -58,7 +58,7 @@ fun TransactionDSLInterpreter.transaction( message = "ledger doesn't nest, use tweak", replaceWith = ReplaceWith("tweak"), level = DeprecationLevel.ERROR) -@Suppress("UNUSED_PARAMETER") +@Suppress("UNUSED_PARAMETER", "unused") fun LedgerDSLInterpreter.ledger( dsl: LedgerDSL.() -> Unit) { } diff --git a/core/src/main/kotlin/com/r3corda/core/utilities/NonEmptySet.kt b/core/src/main/kotlin/com/r3corda/core/utilities/NonEmptySet.kt index 1e961f7539..aab906daa5 100644 --- a/core/src/main/kotlin/com/r3corda/core/utilities/NonEmptySet.kt +++ b/core/src/main/kotlin/com/r3corda/core/utilities/NonEmptySet.kt @@ -12,7 +12,7 @@ import java.util.* * The underlying set is exposed for Kryo to access, but should not be accessed directly. */ class NonEmptySet(initial: T) : MutableSet { - private val set: MutableSet = HashSet() + private val set: MutableSet = HashSet() init { set.add(initial) @@ -28,7 +28,7 @@ class NonEmptySet(initial: T) : MutableSet { override fun containsAll(elements: Collection): Boolean = set.containsAll(elements) override fun isEmpty(): Boolean = false - override fun iterator(): MutableIterator = Iterator(set.iterator()) + override fun iterator(): MutableIterator = Iterator(set.iterator()) override fun remove(element: T): Boolean = // Test either there's more than one element, or the removal is a no-op @@ -65,7 +65,7 @@ class NonEmptySet(initial: T) : MutableSet { override fun equals(other: Any?): Boolean = if (other is Set<*>) // Delegate down to the wrapped set's equals() function - set.equals(other) + set == other else false @@ -84,7 +84,7 @@ class NonEmptySet(initial: T) : MutableSet { } fun nonEmptySetOf(initial: T, vararg elements: T): NonEmptySet { - val set = NonEmptySet(initial) + val set = NonEmptySet(initial) // We add the first element twice, but it's a set, so who cares set.addAll(elements) return set diff --git a/core/src/main/kotlin/com/r3corda/core/utilities/ProgressTracker.kt b/core/src/main/kotlin/com/r3corda/core/utilities/ProgressTracker.kt index 7305260f2a..a3149513fc 100644 --- a/core/src/main/kotlin/com/r3corda/core/utilities/ProgressTracker.kt +++ b/core/src/main/kotlin/com/r3corda/core/utilities/ProgressTracker.kt @@ -151,6 +151,7 @@ class ProgressTracker(vararg steps: Step) { var parent: ProgressTracker? = null private set + @Suppress("unused") // TODO: Review by EOY2016 if this property is useful anywhere. /** Walks up the tree to find the top level tracker. If this is the top level tracker, returns 'this' */ val topLevelTracker: ProgressTracker get() { diff --git a/core/src/main/kotlin/com/r3corda/core/utilities/RecordingMap.kt b/core/src/main/kotlin/com/r3corda/core/utilities/RecordingMap.kt deleted file mode 100644 index 35f5b2765c..0000000000 --- a/core/src/main/kotlin/com/r3corda/core/utilities/RecordingMap.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.r3corda.core.utilities - -import org.slf4j.Logger -import java.util.* -import javax.annotation.concurrent.ThreadSafe - -/** - * A RecordingMap wraps a regular Map and records the sequence of gets and puts to it. This is useful in - * white box unit tests to ensure that code is accessing a data store as much as you expect. - * - * Note: although this class itself thread safe, if the underlying map is not, then this class loses its thread safety. - */ -@ThreadSafe -class RecordingMap(private val wrappedMap: MutableMap, - private val logger: Logger = loggerFor>()) : MutableMap by wrappedMap { - // If/when Kotlin supports data classes inside sealed classes, that would be preferable to this. - interface Record - - data class Get(val key: K) : Record - data class Put(val key: K, val value: V) : Record - - private val _records = Collections.synchronizedList(ArrayList()) - - /** Returns a snapshot of the set of records */ - val records: List get() = _records.toList() - - fun clearRecords() = _records.clear() - - override fun get(key: K): V? { - _records.add(Get(key)) - logger.trace("GET ${logger.name} : $key = ${wrappedMap[key]}") - return wrappedMap[key] - } - - override fun put(key: K, value: V): V? { - _records.add(Put(key, value)) - logger.trace("PUT ${logger.name} : $key = $value") - return wrappedMap.put(key, value) - } - - override fun putAll(from: Map) { - for ((k, v) in from) { - put(k, v) - } - } - - fun putAllUnrecorded(from: Map) { - wrappedMap.putAll(from) - } -} diff --git a/core/src/main/kotlin/com/r3corda/protocols/AbstractStateReplacementProtocol.kt b/core/src/main/kotlin/com/r3corda/protocols/AbstractStateReplacementProtocol.kt index 7931dd09cf..275b884013 100644 --- a/core/src/main/kotlin/com/r3corda/protocols/AbstractStateReplacementProtocol.kt +++ b/core/src/main/kotlin/com/r3corda/protocols/AbstractStateReplacementProtocol.kt @@ -35,9 +35,9 @@ abstract class AbstractStateReplacementProtocol { override val replyToParty: Party, override val sessionID: Long) : PartyRequestMessage - abstract class Instigator(val originalState: StateAndRef, - val modification: T, - override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic>() { + abstract class Instigator(val originalState: StateAndRef, + val modification: T, + override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic>() { companion object { object SIGNING : ProgressTracker.Step("Requesting signatures from other parties") @@ -117,10 +117,10 @@ abstract class AbstractStateReplacementProtocol { } } - abstract class Acceptor(val otherSide: Party, - val sessionIdForSend: Long, - val sessionIdForReceive: Long, - override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic() { + abstract class Acceptor(val otherSide: Party, + val sessionIdForSend: Long, + val sessionIdForReceive: Long, + override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic() { companion object { object VERIFYING : ProgressTracker.Step("Verifying state replacement proposal") @@ -220,11 +220,9 @@ abstract class AbstractStateReplacementProtocol { } -/** Thrown when a participant refuses proposed the state replacement */ +/** Thrown when a participant refuses the proposed state replacement */ class StateReplacementRefused(val identity: Party, val state: StateRef, val detail: String?) { - override fun toString(): String - = "A participant $identity refused to change state $state" + override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided") } -class StateReplacementException(val error: StateReplacementRefused) -: Exception("State change failed - $error") \ No newline at end of file +class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error") \ No newline at end of file diff --git a/core/src/main/kotlin/com/r3corda/protocols/RatesFixProtocol.kt b/core/src/main/kotlin/com/r3corda/protocols/RatesFixProtocol.kt index d61ad3d968..e1e7e5b544 100644 --- a/core/src/main/kotlin/com/r3corda/protocols/RatesFixProtocol.kt +++ b/core/src/main/kotlin/com/r3corda/protocols/RatesFixProtocol.kt @@ -11,6 +11,7 @@ import com.r3corda.core.protocols.ProtocolLogic import com.r3corda.core.random63BitValue import com.r3corda.core.utilities.ProgressTracker import com.r3corda.core.utilities.suggestInterestRateAnnouncementTimeWindow +import com.r3corda.protocols.RatesFixProtocol.FixOutOfRange import java.math.BigDecimal import java.time.Duration import java.time.Instant @@ -46,7 +47,7 @@ open class RatesFixProtocol(protected val tx: TransactionBuilder, override val topic: String get() = TOPIC - class FixOutOfRange(val byAmount: BigDecimal) : Exception() + class FixOutOfRange(@Suppress("unused") val byAmount: BigDecimal) : Exception("Fix out of range by $byAmount") data class QueryRequest(val queries: List, override val replyToParty: Party, override val sessionID: Long, val deadline: Instant) : PartyRequestMessage data class SignRequest(val tx: WireTransaction, override val replyToParty: Party, override val sessionID: Long) : PartyRequestMessage diff --git a/core/src/main/kotlin/com/r3corda/protocols/TwoPartyDealProtocol.kt b/core/src/main/kotlin/com/r3corda/protocols/TwoPartyDealProtocol.kt index 4130267340..9fee22c3f8 100644 --- a/core/src/main/kotlin/com/r3corda/protocols/TwoPartyDealProtocol.kt +++ b/core/src/main/kotlin/com/r3corda/protocols/TwoPartyDealProtocol.kt @@ -157,9 +157,7 @@ object TwoPartyDealProtocol { if (regulators.isNotEmpty()) { // Copy the transaction to every regulator in the network. This is obviously completely bogus, it's // just for demo purposes. - for (regulator in regulators) { - send(regulator.identity, DEFAULT_SESSION_ID, fullySigned) - } + regulators.forEach { send(it.identity, DEFAULT_SESSION_ID, fullySigned) } } return fullySigned @@ -276,12 +274,12 @@ object TwoPartyDealProtocol { /** * One side of the protocol for inserting a pre-agreed deal. */ - open class Instigator(override val otherSide: Party, - val notary: Party, - override val payload: T, - override val myKeyPair: KeyPair, - override val otherSessionID: Long, - override val progressTracker: ProgressTracker = Primary.tracker()) : Primary() { + open class Instigator(override val otherSide: Party, + val notary: Party, + override val payload: T, + override val myKeyPair: KeyPair, + override val otherSessionID: Long, + override val progressTracker: ProgressTracker = Primary.tracker()) : Primary() { override val notaryNode: NodeInfo get() = serviceHub.networkMapCache.notaryNodes.filter { it.identity == notary }.single() @@ -378,7 +376,7 @@ object TwoPartyDealProtocol { val newDeal = deal val ptx = TransactionType.General.Builder() - val addFixing = object : RatesFixProtocol(ptx, serviceHub.networkMapCache.ratesOracleNodes[0].identity, fixOf, BigDecimal.ZERO, BigDecimal.ONE, initiation.timeout) { + val addFixing = object : RatesFixProtocol(ptx, serviceHub.networkMapCache.ratesOracleNodes[0].identity, fixOf, BigDecimal.ZERO, BigDecimal.ONE) { @Suspendable override fun beforeSigning(fix: Fix) { newDeal.generateFix(ptx, StateAndRef(txState, handshake.payload), fix) diff --git a/core/src/test/java/com/r3corda/core/protocols/ProtocolLogicRefFromJavaTest.java b/core/src/test/java/com/r3corda/core/protocols/ProtocolLogicRefFromJavaTest.java index 3af28e217f..ca9727b3e7 100644 --- a/core/src/test/java/com/r3corda/core/protocols/ProtocolLogicRefFromJavaTest.java +++ b/core/src/test/java/com/r3corda/core/protocols/ProtocolLogicRefFromJavaTest.java @@ -8,23 +8,23 @@ import java.util.*; public class ProtocolLogicRefFromJavaTest { - public static class ParamType1 { - public final int value; + private static class ParamType1 { + final int value; ParamType1(int v) { value = v; } } - public static class ParamType2 { - public final String value; + private static class ParamType2 { + final String value; ParamType2(String v) { value = v; } } - public static class JavaProtocolLogic extends ProtocolLogic { + private static class JavaProtocolLogic extends ProtocolLogic { public JavaProtocolLogic(ParamType1 A, ParamType2 b) { } @@ -41,7 +41,7 @@ public class ProtocolLogicRefFromJavaTest { } } - public static class JavaNoArgProtocolLogic extends ProtocolLogic { + private static class JavaNoArgProtocolLogic extends ProtocolLogic { public JavaNoArgProtocolLogic() { } @@ -72,8 +72,7 @@ public class ProtocolLogicRefFromJavaTest { @Test public void testNoArg() { Map> whiteList = new HashMap<>(); - Set argsList = new HashSet<>(); - whiteList.put(JavaNoArgProtocolLogic.class.getName(), argsList); + whiteList.put(JavaNoArgProtocolLogic.class.getName(), new HashSet<>()); ProtocolLogicRefFactory factory = new ProtocolLogicRefFactory(whiteList); factory.create(JavaNoArgProtocolLogic.class); } diff --git a/core/src/test/kotlin/com/r3corda/core/FinanceTypesTest.kt b/core/src/test/kotlin/com/r3corda/core/FinanceTypesTest.kt index 30f3b5b788..cb7c87aeed 100644 --- a/core/src/test/kotlin/com/r3corda/core/FinanceTypesTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/FinanceTypesTest.kt @@ -11,7 +11,7 @@ class FinanceTypesTest { @Test fun `make sure Amount has decimal places`() { - var x = Amount(1, Currency.getInstance("USD")) + val x = Amount(1, Currency.getInstance("USD")) assert("0.01" in x.toString()) } @@ -44,17 +44,17 @@ class FinanceTypesTest { @Test fun `schedule generator 1`() { - var ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2014, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3) + val ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2014, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3) // We know that Jan 25th 2015 is on the weekend -> It should not be in this list returned. - assert(!(LocalDate.of(2015, 1, 25) in ret)) + assert(LocalDate.of(2015, 1, 25) !in ret) println(ret) } @Test fun `schedule generator 2`() { - var ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2015, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3, calendar = BusinessCalendar.getInstance("London"), dateRollConvention = DateRollConvention.Following) + val ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2015, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3, calendar = BusinessCalendar.getInstance("London"), dateRollConvention = DateRollConvention.Following) // Xmas should not be in the list! - assert(!(LocalDate.of(2015, 12, 25) in ret)) + assert(LocalDate.of(2015, 12, 25) !in ret) println(ret) } @@ -126,7 +126,7 @@ class FinanceTypesTest { ) for ((inc, exp) in expected) { - var result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc) + val result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc) assertEquals(exp, result) } } @@ -146,7 +146,7 @@ class FinanceTypesTest { ) for ((inc, exp) in expected) { - var result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc) + val result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc) assertEquals(exp, result) } diff --git a/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt b/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt index e92826f566..1bdfe37c2d 100644 --- a/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/crypto/WhitelistTrustManagerTest.kt @@ -13,7 +13,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue -// We cast null to things in order to select overloads here but Kotlin doesn't know that it's OK. +// TODO: This suppress is needed due to KT-260, fixed in Kotlin 1.0.4 so remove after upgrading. @Suppress("CAST_NEVER_SUCCEEDS") class WhitelistTrustManagerTest { companion object { diff --git a/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt b/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt index 71b845af4f..b95ffe0d60 100644 --- a/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/crypto/X509UtilitiesTest.kt @@ -11,7 +11,6 @@ import java.io.DataOutputStream import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress -import java.nio.file.Paths import java.security.PrivateKey import java.security.SecureRandom import java.security.Signature diff --git a/core/src/test/kotlin/com/r3corda/core/protocols/ProtocolLogicRefTest.kt b/core/src/test/kotlin/com/r3corda/core/protocols/ProtocolLogicRefTest.kt index aa5651f12d..1ee3831b92 100644 --- a/core/src/test/kotlin/com/r3corda/core/protocols/ProtocolLogicRefTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/protocols/ProtocolLogicRefTest.kt @@ -10,7 +10,7 @@ class ProtocolLogicRefTest { data class ParamType1(val value: Int) data class ParamType2(val value: String) - @Suppress("UNUSED_PARAMETER") // We will never use A or b + @Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection. class KotlinProtocolLogic(A: ParamType1, b: ParamType2) : ProtocolLogic() { constructor() : this(ParamType1(1), ParamType2("2")) @@ -22,22 +22,18 @@ class ProtocolLogicRefTest { constructor(kotlinType: Int) : this(ParamType1(kotlinType), ParamType2("b")) - override fun call(): Unit { - } - + override fun call() = Unit override val topic: String get() = throw UnsupportedOperationException() } class KotlinNoArgProtocolLogic : ProtocolLogic() { - override fun call(): Unit { - } + override fun call() = Unit override val topic: String get() = throw UnsupportedOperationException() } @Suppress("UNUSED_PARAMETER") // We will never use A or b class NotWhiteListedKotlinProtocolLogic(A: Int, b: String) : ProtocolLogic() { - override fun call(): Unit { - } + override fun call() = Unit override val topic: String get() = throw UnsupportedOperationException() } @@ -99,5 +95,4 @@ class ProtocolLogicRefTest { val args = mapOf(Pair("kotlinType", 3)) factory.createKotlin(KotlinProtocolLogic::class.java, args) } - } diff --git a/core/src/test/kotlin/com/r3corda/core/serialization/TransactionSerializationTests.kt b/core/src/test/kotlin/com/r3corda/core/serialization/TransactionSerializationTests.kt index 5da8cc4e11..10f24d97c1 100644 --- a/core/src/test/kotlin/com/r3corda/core/serialization/TransactionSerializationTests.kt +++ b/core/src/test/kotlin/com/r3corda/core/serialization/TransactionSerializationTests.kt @@ -2,7 +2,6 @@ package com.r3corda.core.serialization import com.r3corda.core.contracts.* import com.r3corda.core.crypto.SecureHash -import com.r3corda.core.crypto.newSecureRandom import com.r3corda.core.seconds import com.r3corda.core.testing.* import org.junit.Before @@ -34,8 +33,6 @@ class TransactionSerializationTests { } interface Commands : CommandData { class Move() : TypeOnlyCommandData(), Commands - data class Issue(val nonce: Long = newSecureRandom().nextLong()) : Commands - data class Exit(val amount: Amount) : Commands } } diff --git a/core/src/test/kotlin/com/r3corda/core/utilities/ProgressTrackerTest.kt b/core/src/test/kotlin/com/r3corda/core/utilities/ProgressTrackerTest.kt index 8b1c99f2f3..a7c039c79e 100644 --- a/core/src/test/kotlin/com/r3corda/core/utilities/ProgressTrackerTest.kt +++ b/core/src/test/kotlin/com/r3corda/core/utilities/ProgressTrackerTest.kt @@ -111,7 +111,9 @@ class ProgressTrackerTest { pt.setChildProgressTracker(SimpleSteps.TWO, pt2) class Tmp { val unserializable = Unserializable() - val subscription = pt2.changes.subscribe { unserializable.foo() } + init { + pt2.changes.subscribe { unserializable.foo() } + } } Tmp() pt.serialize(kryo) diff --git a/core/src/test/kotlin/com/r3corda/protocols/ResolveTransactionsProtocolTest.kt b/core/src/test/kotlin/com/r3corda/protocols/ResolveTransactionsProtocolTest.kt new file mode 100644 index 0000000000..3099ad332e --- /dev/null +++ b/core/src/test/kotlin/com/r3corda/protocols/ResolveTransactionsProtocolTest.kt @@ -0,0 +1,4 @@ +package com.r3corda.protocols + +class ResolveTransactionsProtocolTest { +} \ No newline at end of file diff --git a/node/src/main/kotlin/com/r3corda/node/api/Query.kt b/node/src/main/kotlin/com/r3corda/node/api/Query.kt index b7ce582596..48ee6b3a4f 100644 --- a/node/src/main/kotlin/com/r3corda/node/api/Query.kt +++ b/node/src/main/kotlin/com/r3corda/node/api/Query.kt @@ -8,15 +8,6 @@ interface StatesQuery { fun select(criteria: Criteria): Selection { return Selection(criteria) } - - fun selectAllDeals(): Selection { - return select(Criteria.AllDeals) - } - - fun selectDeal(ref: String): Selection { - return select(Criteria.Deal(ref)) - } - } // TODO make constructors private diff --git a/node/src/main/kotlin/com/r3corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/com/r3corda/node/internal/AbstractNode.kt index 4b3cd105e7..1eaa3c9b76 100644 --- a/node/src/main/kotlin/com/r3corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/com/r3corda/node/internal/AbstractNode.kt @@ -6,13 +6,13 @@ import com.google.common.util.concurrent.SettableFuture import com.r3corda.core.RunOnCallerThread import com.r3corda.core.contracts.SignedTransaction import com.r3corda.core.crypto.Party -import com.r3corda.core.messaging.MessagingService import com.r3corda.core.messaging.runOnNextMessage import com.r3corda.core.node.CityDatabase import com.r3corda.core.node.CordaPluginRegistry import com.r3corda.core.node.NodeInfo import com.r3corda.core.node.PhysicalLocation import com.r3corda.core.node.services.* +import com.r3corda.core.node.services.NetworkMapCache.MapChangeType import com.r3corda.core.protocols.ProtocolLogic import com.r3corda.core.protocols.ProtocolLogicRefFactory import com.r3corda.core.random63BitValue @@ -27,14 +27,15 @@ import com.r3corda.node.services.events.NodeSchedulerService import com.r3corda.node.services.events.ScheduledActivityObserver import com.r3corda.node.services.identity.InMemoryIdentityService import com.r3corda.node.services.keys.E2ETestKeyManagementService -import com.r3corda.core.node.services.NetworkMapCache -import com.r3corda.core.node.services.NetworkMapCache.MapChangeType import com.r3corda.node.services.network.InMemoryNetworkMapCache import com.r3corda.node.services.network.InMemoryNetworkMapService import com.r3corda.node.services.network.NetworkMapService import com.r3corda.node.services.network.NetworkMapService.Companion.REGISTER_PROTOCOL_TOPIC import com.r3corda.node.services.network.NodeRegistration -import com.r3corda.node.services.persistence.* +import com.r3corda.node.services.persistence.NodeAttachmentService +import com.r3corda.node.services.persistence.PerFileCheckpointStorage +import com.r3corda.node.services.persistence.PerFileTransactionStorage +import com.r3corda.node.services.persistence.StorageServiceImpl import com.r3corda.node.services.statemachine.StateMachineManager import com.r3corda.node.services.transactions.InMemoryUniquenessProvider import com.r3corda.node.services.transactions.NotaryService @@ -158,7 +159,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration, storage = storageServices.first checkpointStorage = storageServices.second net = makeMessagingService() - netMapCache = InMemoryNetworkMapCache(net) + netMapCache = InMemoryNetworkMapCache() wallet = NodeWalletService(services) identity = makeIdentityService() @@ -201,8 +202,8 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration, private fun initialiseProtocolLogicFactory(): ProtocolLogicRefFactory { val protocolWhitelist = HashMap>() for (plugin in pluginRegistries) { - for (protocol in plugin.requiredProtocols) { - protocolWhitelist.merge(protocol.key, protocol.value, { x, y -> x + y }) + for ((className, classWhitelist) in plugin.requiredProtocols) { + protocolWhitelist.merge(className, classWhitelist, { x, y -> x + y }) } } diff --git a/node/src/main/kotlin/com/r3corda/node/internal/testing/MockNode.kt b/node/src/main/kotlin/com/r3corda/node/internal/testing/MockNode.kt index ccb7931821..5cdaee7462 100644 --- a/node/src/main/kotlin/com/r3corda/node/internal/testing/MockNode.kt +++ b/node/src/main/kotlin/com/r3corda/node/internal/testing/MockNode.kt @@ -4,7 +4,6 @@ import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.google.common.util.concurrent.Futures import com.r3corda.core.crypto.Party -import com.r3corda.core.messaging.MessagingService import com.r3corda.core.messaging.SingleMessageRecipient import com.r3corda.core.node.NodeInfo import com.r3corda.core.node.PhysicalLocation @@ -104,7 +103,8 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false, } // This does not indirect through the NodeInfo object so it can be called before the node is started. - val place: PhysicalLocation get() = findMyLocation()!! + // It is used from the network visualiser tool. + @Suppress("unused") val place: PhysicalLocation get() = findMyLocation()!! } /** Returns a node, optionally created by the passed factory method. */ @@ -168,6 +168,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false, fun createNotaryNode(legalName: String? = null, keyPair: KeyPair? = null) = createNode(null, -1, defaultFactory, true, legalName, keyPair, NetworkMapService.Type, SimpleNotaryService.Type) fun createPartyNode(networkMapAddr: NodeInfo, legalName: String? = null, keyPair: KeyPair? = null) = createNode(networkMapAddr, -1, defaultFactory, true, legalName, keyPair) + @Suppress("unused") // This is used from the network visualiser tool. fun addressToNode(address: SingleMessageRecipient): MockNode = nodes.single { it.net.myAddress == address } fun startNodes() { diff --git a/node/src/main/kotlin/com/r3corda/node/internal/testing/Simulation.kt b/node/src/main/kotlin/com/r3corda/node/internal/testing/Simulation.kt index e4f994baa1..c236896752 100644 --- a/node/src/main/kotlin/com/r3corda/node/internal/testing/Simulation.kt +++ b/node/src/main/kotlin/com/r3corda/node/internal/testing/Simulation.kt @@ -31,8 +31,8 @@ import java.util.* * in a few cities around the world. */ abstract class Simulation(val networkSendManuallyPumped: Boolean, - val runAsync: Boolean, - val latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) { + runAsync: Boolean, + latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) { init { if (!runAsync && latencyInjector != null) throw IllegalArgumentException("The latency injector is only useful when using manual pumping.") @@ -160,10 +160,11 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, val clocks = (serviceProviders + regulators + banks).map { it.services.clock as TestClock } + // These are used from the network visualiser tool. private val _allProtocolSteps = PublishSubject.create>() private val _doneSteps = PublishSubject.create>() - val allProtocolSteps: Observable> = _allProtocolSteps - val doneSteps: Observable> = _doneSteps + @Suppress("unused") val allProtocolSteps: Observable> = _allProtocolSteps + @Suppress("unused") val doneSteps: Observable> = _doneSteps private var pumpCursor = 0 @@ -258,6 +259,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } } + @Suppress("unused") // Used from the network visualiser tool. val networkInitialisationFinished: ListenableFuture<*> = Futures.allAsList(network.nodes.map { it.networkMapRegistrationFuture }) diff --git a/node/src/main/kotlin/com/r3corda/node/services/api/AbstractNodeService.kt b/node/src/main/kotlin/com/r3corda/node/services/api/AbstractNodeService.kt index 94eced249f..8e37dcc099 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/api/AbstractNodeService.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/api/AbstractNodeService.kt @@ -2,7 +2,6 @@ package com.r3corda.node.services.api import com.r3corda.core.messaging.Message import com.r3corda.core.messaging.MessagingService -import com.r3corda.core.messaging.TopicSession import com.r3corda.core.node.services.DEFAULT_SESSION_ID import com.r3corda.core.node.services.NetworkMapCache import com.r3corda.core.serialization.SingletonSerializeAsToken diff --git a/node/src/main/kotlin/com/r3corda/node/services/api/CheckpointStorage.kt b/node/src/main/kotlin/com/r3corda/node/services/api/CheckpointStorage.kt index 96945d52ad..9426e3cae5 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/api/CheckpointStorage.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/api/CheckpointStorage.kt @@ -3,7 +3,6 @@ package com.r3corda.node.services.api import com.r3corda.core.serialization.SerializedBytes import com.r3corda.node.services.statemachine.FiberRequest import com.r3corda.node.services.statemachine.ProtocolStateMachineImpl -import com.r3corda.node.services.statemachine.StateMachineManager /** * Thread-safe storage of fiber checkpoints. diff --git a/node/src/main/kotlin/com/r3corda/node/services/clientapi/FixingSessionInitiation.kt b/node/src/main/kotlin/com/r3corda/node/services/clientapi/FixingSessionInitiation.kt index 6f7706176c..4b8adbe17b 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/clientapi/FixingSessionInitiation.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/clientapi/FixingSessionInitiation.kt @@ -3,7 +3,6 @@ package com.r3corda.node.services.clientapi import com.r3corda.core.node.CordaPluginRegistry import com.r3corda.core.node.services.DEFAULT_SESSION_ID import com.r3corda.core.serialization.deserialize -import com.r3corda.node.internal.AbstractNode import com.r3corda.node.services.api.ServiceHubInternal import com.r3corda.protocols.TwoPartyDealProtocol diff --git a/node/src/main/kotlin/com/r3corda/node/services/clientapi/NodeInterestRates.kt b/node/src/main/kotlin/com/r3corda/node/services/clientapi/NodeInterestRates.kt index 6eacbe3716..65e75071aa 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/clientapi/NodeInterestRates.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/clientapi/NodeInterestRates.kt @@ -197,7 +197,7 @@ object NodeInterestRates { class UnknownFix(val fix: FixOf) : RetryableException("Unknown fix: $fix") /** Fix container, for every fix name & date pair stores a tenor to interest rate map - [InterpolatingRateMap] */ - class FixContainer(val fixes: List, val factory: InterpolatorFactory = CubicSplineInterpolator) { + class FixContainer(fixes: List, val factory: InterpolatorFactory = CubicSplineInterpolator) { private val container = buildContainer(fixes) val size = fixes.size @@ -227,7 +227,7 @@ object NodeInterestRates { * Interpolates missing values using the provided interpolation mechanism. */ class InterpolatingRateMap(val date: LocalDate, - val inputRates: Map, + inputRates: Map, val calendar: BusinessCalendar, val factory: InterpolatorFactory) { @@ -274,7 +274,7 @@ object NodeInterestRates { /** Parses lines containing fixes */ fun parseFile(s: String): FixContainer { val fixes = s.lines(). - map { it.trim() }. + map(String::trim). // Filter out comment and empty lines. filterNot { it.startsWith("#") || it.isBlank() }. map { parseFix(it) } @@ -283,7 +283,7 @@ object NodeInterestRates { /** Parses a string of the form "LIBOR 16-March-2016 1M = 0.678" into a [Fix] */ fun parseFix(s: String): Fix { - val (key, value) = s.split('=').map { it.trim() } + val (key, value) = s.split('=').map(String::trim) val of = parseFixOf(key) val rate = BigDecimal(value) return Fix(of, rate) diff --git a/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryMessagingNetwork.kt b/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryMessagingNetwork.kt index 29d7908d8a..7bc0cd20ca 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryMessagingNetwork.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryMessagingNetwork.kt @@ -50,6 +50,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria // The corresponding sentMessages stream reflects when a message was pumpSend'd private val messageSendQueue = LinkedBlockingQueue() private val _sentMessages = PublishSubject.create() + @Suppress("unused") // Used by the visualiser tool. /** A stream of (sender, message, recipients) triples */ val sentMessages: Observable get() = _sentMessages @@ -61,6 +62,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria // The corresponding stream reflects when a message was pumpReceive'd private val messageReceiveQueues = HashMap>() private val _receivedMessages = PublishSubject.create() + + @Suppress("unused") // Used by the visualiser tool. /** A stream of (sender, message, recipients) triples */ val receivedMessages: Observable get() = _receivedMessages @@ -202,18 +205,18 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria val callback: (Message, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration @Volatile - protected var running = true + private var running = true - protected inner class InnerState { + private inner class InnerState { val handlers: MutableList = ArrayList() val pendingRedelivery = LinkedList() } - protected val state = ThreadBox(InnerState()) + private val state = ThreadBox(InnerState()) override val myAddress: SingleMessageRecipient = handle - protected val backgroundThread = if (manuallyPumped) null else + private val backgroundThread = if (manuallyPumped) null else thread(isDaemon = true, name = "In-memory message dispatcher") { while (!Thread.currentThread().isInterrupted) { try { @@ -235,8 +238,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria pendingRedelivery.clear() Pair(handler, items) } - for (it in items) { - send(it.message, handle) + for ((sender, message) in items) { + send(message, handle) } return handler } @@ -329,10 +332,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria private fun pumpReceiveInternal(block: Boolean): MessageTransfer? { val q = getQueueForHandle(handle) - val next = getNextQueue(q, block) - if (next == null) { - return null - } + val next = getNextQueue(q, block) ?: return null val (transfer, deliverTo) = next for (handler in deliverTo) { diff --git a/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryNetworkMapCache.kt b/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryNetworkMapCache.kt index 1e99eaff4c..52c5e95944 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryNetworkMapCache.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/network/InMemoryNetworkMapCache.kt @@ -13,14 +13,13 @@ import com.r3corda.core.node.NodeInfo import com.r3corda.core.node.services.DEFAULT_SESSION_ID import com.r3corda.core.node.services.NetworkCacheError import com.r3corda.core.node.services.NetworkMapCache -import com.r3corda.core.node.services.NetworkMapCache.MapChangeType import com.r3corda.core.node.services.NetworkMapCache.MapChange +import com.r3corda.core.node.services.NetworkMapCache.MapChangeType import com.r3corda.core.node.services.ServiceType import com.r3corda.core.random63BitValue import com.r3corda.core.serialization.SingletonSerializeAsToken import com.r3corda.core.serialization.deserialize import com.r3corda.core.serialization.serialize -import com.r3corda.node.services.api.MessagingServiceInternal import com.r3corda.node.services.api.RegulatorService import com.r3corda.node.services.clientapi.NodeInterestRates import com.r3corda.node.services.transactions.NotaryService @@ -36,7 +35,7 @@ import javax.annotation.concurrent.ThreadSafe * Extremely simple in-memory cache of the network map. */ @ThreadSafe -open class InMemoryNetworkMapCache(val netInternal: MessagingServiceInternal?) : SingletonSerializeAsToken(), NetworkMapCache { +open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCache { override val networkMapNodes: List get() = get(NetworkMapService.Type) override val regulators: List diff --git a/node/src/main/kotlin/com/r3corda/node/services/network/MockNetworkMapCache.kt b/node/src/main/kotlin/com/r3corda/node/services/network/MockNetworkMapCache.kt index ea31653359..bc37111f63 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/network/MockNetworkMapCache.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/network/MockNetworkMapCache.kt @@ -12,14 +12,14 @@ import rx.subjects.PublishSubject /** * Network map cache with no backing map service. */ -class MockNetworkMapCache() : InMemoryNetworkMapCache(null) { +class MockNetworkMapCache() : InMemoryNetworkMapCache() { override val changed: Observable = PublishSubject.create() data class MockAddress(val id: String): SingleMessageRecipient init { - var mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C"))) - var mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D"))) + val mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C"))) + val mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D"))) registeredNodes[mockNodeA.identity] = mockNodeA registeredNodes[mockNodeB.identity] = mockNodeB } diff --git a/node/src/main/kotlin/com/r3corda/node/services/network/NetworkMapService.kt b/node/src/main/kotlin/com/r3corda/node/services/network/NetworkMapService.kt index 0aaa53f39c..e3679f6810 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/network/NetworkMapService.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/network/NetworkMapService.kt @@ -280,7 +280,7 @@ class NodeRegistration(val node: NodeInfo, val serial: Long, val type: AddOrRemo return WireNodeRegistration(regSerialized, regSig) } - override fun toString() : String = "$node #${serial} (${type})" + override fun toString() : String = "$node #$serial ($type)" } /** diff --git a/node/src/main/kotlin/com/r3corda/node/services/persistence/DataVendingService.kt b/node/src/main/kotlin/com/r3corda/node/services/persistence/DataVendingService.kt index 00b88887e3..0155655a42 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/persistence/DataVendingService.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/persistence/DataVendingService.kt @@ -62,7 +62,7 @@ object DataVending { if (data.accepted) { future.set(Unit) } else { - future.setException(TransactionRejectedError("Transaction ${transaction} rejected by remote party ${recipient.identity}")) + future.setException(TransactionRejectedError("Transaction $transaction rejected by remote party ${recipient.identity}")) } } val msg = NotifyTxRequestMessage(transaction, myIdentity, sessionID) diff --git a/node/src/main/kotlin/com/r3corda/node/services/persistence/NodeAttachmentService.kt b/node/src/main/kotlin/com/r3corda/node/services/persistence/NodeAttachmentService.kt index 2bf71ae512..018803a73e 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/persistence/NodeAttachmentService.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/persistence/NodeAttachmentService.kt @@ -22,7 +22,7 @@ import javax.annotation.concurrent.ThreadSafe * Stores attachments in the specified local directory, which must exist. Doesn't allow new attachments to be uploaded. */ @ThreadSafe -class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload { +class NodeAttachmentService(val storePath: Path, metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload { private val log = loggerFor() @VisibleForTesting @@ -122,7 +122,7 @@ class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) : Files.deleteIfExists(tmp) } if (automaticallyExtractAttachments) { - val extractTo = storePath.resolve("${id}.jar") + val extractTo = storePath.resolve("$id.jar") try { Files.createDirectory(extractTo) extractZipFile(finalPath, extractTo) diff --git a/node/src/main/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorage.kt b/node/src/main/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorage.kt index 1ef9e93ace..273ee2581c 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorage.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorage.kt @@ -40,7 +40,7 @@ class PerFileCheckpointStorage(val storeDir: Path) : CheckpointStorage { override fun addCheckpoint(checkpoint: Checkpoint) { val serialisedCheckpoint = checkpoint.serialize() - val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}${fileExtension}" + val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}$fileExtension" val checkpointFile = storeDir.resolve(fileName) atomicWrite(checkpointFile, serialisedCheckpoint) logger.trace { "Stored $checkpoint to $checkpointFile" } diff --git a/node/src/main/kotlin/com/r3corda/node/services/statemachine/FiberRequest.kt b/node/src/main/kotlin/com/r3corda/node/services/statemachine/FiberRequest.kt index d5714fee76..b3fd7911d8 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/statemachine/FiberRequest.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/statemachine/FiberRequest.kt @@ -59,15 +59,15 @@ sealed class FiberRequest(val topic: String, ) : FiberRequest(topic, destination, sessionIDForSend, sessionIDForReceive, obj) { private val responseTypeName: String = type.name - override fun equals(other: Any?): Boolean - = if (other is ExpectingResponse<*>) { - super.equals(other) - && responseTypeName == other.responseTypeName - } else - false + override fun equals(other: Any?): Boolean { + return if (other is ExpectingResponse<*>) { + super.equals(other) && responseTypeName == other.responseTypeName + } else + false + } override fun toString(): String { - return "Expecting response via topic ${receiveTopicSession} of type ${responseTypeName}" + return "Expecting response via topic $receiveTopicSession of type $responseTypeName" } // We have to do an unchecked cast, but unless the serialized form is damaged, this was diff --git a/node/src/main/kotlin/com/r3corda/node/services/wallet/CashBalanceAsMetricsObserver.kt b/node/src/main/kotlin/com/r3corda/node/services/wallet/CashBalanceAsMetricsObserver.kt index 336b962569..4409614b5f 100644 --- a/node/src/main/kotlin/com/r3corda/node/services/wallet/CashBalanceAsMetricsObserver.kt +++ b/node/src/main/kotlin/com/r3corda/node/services/wallet/CashBalanceAsMetricsObserver.kt @@ -30,13 +30,13 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) { // // Note: exported as pennies. val m = serviceHubInternal.monitoringService.metrics - for (balance in wallet.cashBalances) { - val metric = balanceMetrics.getOrPut(balance.key) { + for ((key, value) in wallet.cashBalances) { + val metric = balanceMetrics.getOrPut(key) { val newMetric = BalanceMetric() - m.register("WalletBalances.${balance.key}Pennies", newMetric) + m.register("WalletBalances.${key}Pennies", newMetric) newMetric } - metric.pennies = balance.value.quantity + metric.pennies = value.quantity } } } \ No newline at end of file diff --git a/node/src/main/kotlin/com/r3corda/node/utilities/ANSIProgressObserver.kt b/node/src/main/kotlin/com/r3corda/node/utilities/ANSIProgressObserver.kt index 408374d1ec..b3e39f9eed 100644 --- a/node/src/main/kotlin/com/r3corda/node/utilities/ANSIProgressObserver.kt +++ b/node/src/main/kotlin/com/r3corda/node/utilities/ANSIProgressObserver.kt @@ -4,7 +4,6 @@ import com.r3corda.core.ThreadBox import com.r3corda.core.protocols.ProtocolLogic import com.r3corda.core.utilities.ProgressTracker import com.r3corda.node.services.statemachine.StateMachineManager -import com.r3corda.protocols.TwoPartyDealProtocol import java.util.* /** diff --git a/node/src/main/kotlin/com/r3corda/node/utilities/FiberBox.kt b/node/src/main/kotlin/com/r3corda/node/utilities/FiberBox.kt index 4b3097d1e6..70730acd13 100644 --- a/node/src/main/kotlin/com/r3corda/node/utilities/FiberBox.kt +++ b/node/src/main/kotlin/com/r3corda/node/utilities/FiberBox.kt @@ -36,7 +36,7 @@ import kotlin.concurrent.withLock * TODO: We should consider using a [Semaphore] or [CountDownLatch] here to make it a little easier to understand, but it seems * as though the current version of Qasar does not support suspending on either of their implementations. */ -class FiberBox(private val content: T, private val lock: Lock = ReentrantLock()) { +class FiberBox(private val content: T, private val lock: Lock = ReentrantLock()) { private var mutated: SettableFuture? = null @Suppress("UNUSED_VALUE") // This is here due to the compiler thinking ourMutated is not used diff --git a/node/src/main/kotlin/com/r3corda/node/utilities/JsonSupport.kt b/node/src/main/kotlin/com/r3corda/node/utilities/JsonSupport.kt index 54e8224f3d..a35ef0e1cd 100644 --- a/node/src/main/kotlin/com/r3corda/node/utilities/JsonSupport.kt +++ b/node/src/main/kotlin/com/r3corda/node/utilities/JsonSupport.kt @@ -13,8 +13,6 @@ import com.r3corda.core.contracts.BusinessCalendar import com.r3corda.core.crypto.* import com.r3corda.core.node.services.IdentityService import net.i2p.crypto.eddsa.EdDSAPublicKey -import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable -import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec import java.math.BigDecimal import java.time.LocalDate import java.time.LocalDateTime diff --git a/node/src/test/kotlin/com/r3corda/node/services/MockServiceHubInternal.kt b/node/src/test/kotlin/com/r3corda/node/services/MockServiceHubInternal.kt index 251d3652c2..0f4a20a61a 100644 --- a/node/src/test/kotlin/com/r3corda/node/services/MockServiceHubInternal.kt +++ b/node/src/test/kotlin/com/r3corda/node/services/MockServiceHubInternal.kt @@ -19,6 +19,7 @@ import com.r3corda.node.services.statemachine.StateMachineManager import com.r3corda.node.services.wallet.NodeWalletService import java.time.Clock +@Suppress("LeakingThis") open class MockServiceHubInternal( customWallet: WalletService? = null, val keyManagement: KeyManagementService? = null, diff --git a/node/src/test/kotlin/com/r3corda/node/services/NodeInterestRatesTest.kt b/node/src/test/kotlin/com/r3corda/node/services/NodeInterestRatesTest.kt index 67550ebc10..d30eb3d4d0 100644 --- a/node/src/test/kotlin/com/r3corda/node/services/NodeInterestRatesTest.kt +++ b/node/src/test/kotlin/com/r3corda/node/services/NodeInterestRatesTest.kt @@ -22,7 +22,6 @@ import com.r3corda.protocols.RatesFixProtocol import org.junit.Assert import org.junit.Test import java.time.Clock -import java.time.Duration import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -109,7 +108,7 @@ class NodeInterestRatesTest { val tx = TransactionType.General.Builder() val fixOf = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M") - val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd, Duration.ofNanos(1)) + val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd) BriefLogFormatter.initVerbose("rates") net.runNetwork() val future = n1.smm.add("rates", protocol) diff --git a/node/src/test/kotlin/com/r3corda/node/services/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/com/r3corda/node/services/NodeSchedulerServiceTest.kt index 1b298893e9..93312e4f40 100644 --- a/node/src/test/kotlin/com/r3corda/node/services/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/com/r3corda/node/services/NodeSchedulerServiceTest.kt @@ -196,7 +196,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { @Test fun `test activity due in the future and schedule another for same time then unschedule original`() { val time = stoppedClock.instant() + 1.days - var scheduledRef1 = scheduleTX(time) + val scheduledRef1 = scheduleTX(time) val backgroundExecutor = Executors.newSingleThreadExecutor() backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() } @@ -214,7 +214,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() { @Test fun `test activity due in the future then unschedule`() { - var scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days) + val scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days) val backgroundExecutor = Executors.newSingleThreadExecutor() backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() } diff --git a/node/src/test/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorageTests.kt b/node/src/test/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorageTests.kt index 247b2f9ae5..cee289e5ee 100644 --- a/node/src/test/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorageTests.kt +++ b/node/src/test/kotlin/com/r3corda/node/services/persistence/PerFileCheckpointStorageTests.kt @@ -7,7 +7,6 @@ import com.r3corda.core.random63BitValue import com.r3corda.core.serialization.SerializedBytes import com.r3corda.node.services.api.Checkpoint import com.r3corda.node.services.statemachine.FiberRequest -import com.r3corda.node.services.statemachine.StateMachineManager import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.After diff --git a/node/src/test/kotlin/com/r3corda/node/services/statemachine/StateMachineManagerTests.kt b/node/src/test/kotlin/com/r3corda/node/services/statemachine/StateMachineManagerTests.kt index 8c9ab91a95..3f65e77526 100644 --- a/node/src/test/kotlin/com/r3corda/node/services/statemachine/StateMachineManagerTests.kt +++ b/node/src/test/kotlin/com/r3corda/node/services/statemachine/StateMachineManagerTests.kt @@ -2,7 +2,6 @@ package com.r3corda.node.services.statemachine import co.paralleluniverse.fibers.Fiber import co.paralleluniverse.fibers.Suspendable -import com.r3corda.core.messaging.MessagingService import com.r3corda.core.protocols.ProtocolLogic import com.r3corda.node.services.MockServiceHubInternal import com.r3corda.node.services.api.Checkpoint diff --git a/node/src/test/kotlin/com/r3corda/node/visualiser/GroupToGraphConversion.kt b/node/src/test/kotlin/com/r3corda/node/visualiser/GroupToGraphConversion.kt index 51ce731508..75fed7050c 100644 --- a/node/src/test/kotlin/com/r3corda/node/visualiser/GroupToGraphConversion.kt +++ b/node/src/test/kotlin/com/r3corda/node/visualiser/GroupToGraphConversion.kt @@ -11,6 +11,7 @@ import org.graphstream.graph.Node import org.graphstream.graph.implementations.SingleGraph import kotlin.reflect.memberProperties +@Suppress("unused") // TODO: Re-evaluate by EOY2016 if this code is still useful and if not, delete. class GraphVisualiser(val dsl: LedgerDSL) { companion object { val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText() diff --git a/node/src/test/kotlin/com/r3corda/node/visualiser/StateViewer.java b/node/src/test/kotlin/com/r3corda/node/visualiser/StateViewer.java index 0418197742..8917812171 100644 --- a/node/src/test/kotlin/com/r3corda/node/visualiser/StateViewer.java +++ b/node/src/test/kotlin/com/r3corda/node/visualiser/StateViewer.java @@ -37,7 +37,7 @@ public class StateViewer { frame.setVisible(true); } - public StateViewer(List> props) { + private StateViewer(List> props) { propsTable.setModel(new AbstractTableModel() { @Override public int getRowCount() { diff --git a/src/main/kotlin/com/r3corda/demos/RateFixDemo.kt b/src/main/kotlin/com/r3corda/demos/RateFixDemo.kt index 39e86788ff..21eed09269 100644 --- a/src/main/kotlin/com/r3corda/demos/RateFixDemo.kt +++ b/src/main/kotlin/com/r3corda/demos/RateFixDemo.kt @@ -90,7 +90,7 @@ fun main(args: Array) { // Make a garbage transaction that includes a rate fix. val tx = TransactionType.General.Builder() tx.addOutputState(TransactionState(Cash.State(1500.DOLLARS `issued by` node.storage.myLegalIdentity.ref(1), node.keyManagement.freshKey().public), notary.identity)) - val protocol = RatesFixProtocol(tx, oracleNode.identity, fixOf, expectedRate, rateTolerance, 24.hours) + val protocol = RatesFixProtocol(tx, oracleNode.identity, fixOf, expectedRate, rateTolerance) node.smm.add("demo.ratefix", protocol).get() node.stop() diff --git a/src/main/resources/com/r3corda/demos/irswebdemo/js/Deal.js b/src/main/resources/com/r3corda/demos/irswebdemo/js/Deal.js index 3a83b0a6be..bc326c4b10 100644 --- a/src/main/resources/com/r3corda/demos/irswebdemo/js/Deal.js +++ b/src/main/resources/com/r3corda/demos/irswebdemo/js/Deal.js @@ -1,4 +1,4 @@ -"use strict" +"use strict"; define(['viewmodel/FixedRate'], (fixedRateViewModel) => { let calculationModel = { @@ -25,7 +25,7 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => { let Deal = function(dealViewModel) { let now = new Date(); - let tradeId = `T${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}.${now.getUTCHours()}:${now.getUTCMinutes()}:${now.getUTCSeconds()}:${now.getUTCMilliseconds()}` + let tradeId = `T${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}.${now.getUTCHours()}:${now.getUTCMinutes()}:${now.getUTCSeconds()}:${now.getUTCMilliseconds()}`; this.toJson = () => { let fixedLeg = {}; @@ -70,10 +70,10 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => { floatingLeg: floatingLeg, calculation: calculationModel, common: common - } + }; return json; }; }; return Deal; -}) +}); diff --git a/src/main/resources/com/r3corda/demos/irswebdemo/js/app.js b/src/main/resources/com/r3corda/demos/irswebdemo/js/app.js index f95ed6a76b..fef33d756e 100644 --- a/src/main/resources/com/r3corda/demos/irswebdemo/js/app.js +++ b/src/main/resources/com/r3corda/demos/irswebdemo/js/app.js @@ -1,4 +1,4 @@ -"use strict" +"use strict"; function formatDateForNode(date) { // Produces yyyy-dd-mm. JS is missing proper date formatting libs diff --git a/src/main/resources/com/r3corda/demos/irswebdemo/js/controllers/Home.js b/src/main/resources/com/r3corda/demos/irswebdemo/js/controllers/Home.js index 61ab970448..6a99583728 100644 --- a/src/main/resources/com/r3corda/demos/irswebdemo/js/controllers/Home.js +++ b/src/main/resources/com/r3corda/demos/irswebdemo/js/controllers/Home.js @@ -6,7 +6,7 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no let handleHttpFail = (resp) => { $scope.httpError = resp.data - } + }; $scope.infoMsg = ""; $scope.errorText = ""; @@ -20,4 +20,4 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no nodeService.getDate().then((date) => $scope.date = date); nodeService.getDeals().then((deals) => $scope.deals = deals); }); -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/src/main/resources/com/r3corda/demos/irswebdemo/js/services/NodeApi.js b/src/main/resources/com/r3corda/demos/irswebdemo/js/services/NodeApi.js index b228878369..2d84ae295b 100644 --- a/src/main/resources/com/r3corda/demos/irswebdemo/js/services/NodeApi.js +++ b/src/main/resources/com/r3corda/demos/irswebdemo/js/services/NodeApi.js @@ -15,7 +15,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => { curLoading[type] = false; throw arg; }); - } + }; let changeDateOnNode = (newDate) => { const dateStr = formatDateForNode(newDate); @@ -24,7 +24,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => { date = newDate; return this.getDateModel(date); }); - } + }; this.getDate = () => { return load('date', $http.get('/api/irs/demodate')).then((resp) => { @@ -32,7 +32,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => { date = new Date(parts[0], parts[1] - 1, parts[2]); // JS uses 0 based months return this.getDateModel(date); }); - } + }; this.updateDate = (type) => { let newDate = date; @@ -74,17 +74,17 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => { "month": date.getMonth() + 1, // JS uses 0 based months "day": date.getDate() }; - } + }; this.isLoading = () => { return _.reduce(Object.keys(curLoading), (last, key) => { return (last || curLoading[key]); }, false); - } + }; this.newDeal = () => { return dealViewModel; - } + }; this.createDeal = (deal) => { return load('create-deal', $http.post('/api/irs/deals', deal.toJson())) diff --git a/src/main/resources/com/r3corda/demos/irswebdemo/js/utils/dayCountBasisLookup.js b/src/main/resources/com/r3corda/demos/irswebdemo/js/utils/dayCountBasisLookup.js index eeb9cb1b3d..be80477ac2 100644 --- a/src/main/resources/com/r3corda/demos/irswebdemo/js/utils/dayCountBasisLookup.js +++ b/src/main/resources/com/r3corda/demos/irswebdemo/js/utils/dayCountBasisLookup.js @@ -31,4 +31,4 @@ define([], () => { "year": "YICMA" }, }; -}) \ No newline at end of file +}); \ No newline at end of file