From 7b40be83612ece05c7d23c8c10e94863ea0567a0 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Wed, 30 Nov 2016 14:40:34 +0000 Subject: [PATCH 1/2] Run the IntelliJ reformatter across the Kotlin code. Did not reformat JS/web code. --- .../net/corda/client/CordaRPCClientTest.kt | 2 +- .../kotlin/net/corda/client/CordaRPCClient.kt | 1 + .../corda/client/fxutils/AmountBindings.kt | 6 +- .../net/corda/client/fxutils/ChosenList.kt | 2 +- .../corda/client/fxutils/ConcatenatedList.kt | 18 +-- .../net/corda/client/fxutils/FlattenedList.kt | 4 +- .../client/fxutils/LeftOuterJoinedMap.kt | 3 +- .../client/fxutils/ObservableUtilities.kt | 7 + .../net/corda/client/fxutils/ReplayedList.kt | 8 +- .../corda/client/impl/CordaRPCClientImpl.kt | 4 +- .../kotlin/net/corda/client/mock/Generator.kt | 17 ++- .../net/corda/client/mock/Generators.kt | 2 +- .../corda/client/model/ExchangeRateModel.kt | 4 +- .../model/GatheredTransactionDataModel.kt | 8 +- .../kotlin/net/corda/client/model/Models.kt | 28 ++-- .../client/ClientRPCInfrastructureTests.kt | 4 +- .../client/fxutils/ConcatenatedListTest.kt | 2 +- .../client/fxutils/LeftOuterJoinedMapTest.kt | 3 +- .../java/net/corda/core/crypto/Base58.java | 6 +- core/src/main/kotlin/net/corda/core/Utils.kt | 13 +- .../net/corda/core/contracts/ContractsDSL.kt | 14 +- .../net/corda/core/contracts/DummyState.kt | 1 + .../net/corda/core/contracts/FinanceTypes.kt | 12 +- .../net/corda/core/contracts/FungibleAsset.kt | 4 +- .../net/corda/core/contracts/Structures.kt | 13 +- .../corda/core/contracts/TransactionTypes.kt | 11 +- .../core/contracts/TransactionVerification.kt | 4 + .../core/contracts/clauses/ClauseVerifier.kt | 12 +- .../core/contracts/clauses/CompositeClause.kt | 4 +- .../contracts/clauses/GroupClauseVerifier.kt | 2 +- .../corda/core/crypto/PartialMerkleTree.kt | 10 +- .../net/corda/core/flows/FlowLogicRef.kt | 2 +- .../core/node/PhysicalLocationStructures.kt | 2 +- .../kotlin/net/corda/core/node/ServiceHub.kt | 1 + .../net/corda/core/serialization/Kryo.kt | 14 +- .../net/corda/core/testing/Generators.kt | 13 +- .../core/transactions/LedgerTransaction.kt | 4 +- .../core/transactions/MerkleTransaction.kt | 22 +-- .../core/transactions/SignedTransaction.kt | 2 + .../core/transactions/TransactionBuilder.kt | 3 +- .../core/transactions/WireTransaction.kt | 4 +- .../net/corda/core/utilities/ApiUtils.kt | 2 +- .../net/corda/core/utilities/Logging.kt | 9 +- .../net/corda/core/utilities/NonEmptySet.kt | 4 +- .../corda/core/utilities/ProgressTracker.kt | 4 +- .../net/corda/core/utilities/TestConstants.kt | 1 + .../flows/AbstractStateReplacementFlow.kt | 4 +- .../net/corda/flows/NotaryChangeFlow.kt | 2 +- .../main/kotlin/net/corda/flows/NotaryFlow.kt | 2 +- .../net/corda/flows/TwoPartyDealFlow.kt | 2 +- .../core/flows/FlowLogicRefFromJavaTest.java | 7 +- .../contracts/TransactionGraphSearchTests.kt | 2 +- .../contracts/clauses/AnyCompositionTests.kt | 2 - .../core/contracts/clauses/ClauseTestUtils.kt | 2 +- .../core/crypto/PartialMerkleTreeTest.kt | 16 ++- .../corda/core/crypto/X509UtilitiesTest.kt | 6 +- .../net/corda/core/flows/FlowLogicRefTest.kt | 2 +- .../core/node/AttachmentClassLoaderTests.kt | 2 +- .../TransactionSerializationTests.kt | 1 + .../core/utilities/ProgressTrackerTest.kt | 3 + .../contracts/ICommercialPaperState.java | 11 +- .../corda/contracts/JavaCommercialPaper.java | 76 +++++------ .../net/corda/contracts/CommercialPaper.kt | 16 +-- .../kotlin/net/corda/contracts/asset/Cash.kt | 7 +- .../contracts/asset/CommodityContract.kt | 8 +- .../net/corda/contracts/asset/Obligation.kt | 16 ++- .../corda/contracts/asset/OnLedgerAsset.kt | 4 +- .../corda/contracts/clause/AbstractIssue.kt | 2 +- .../kotlin/net/corda/contracts/clause/Net.kt | 2 +- .../contracts/clause/NoZeroSizedOutputs.kt | 1 - .../net/corda/contracts/testing/Generators.kt | 4 +- .../corda/contracts/testing/VaultFiller.kt | 1 + .../corda/contracts/asset/CashTestsJava.java | 2 +- .../corda/contracts/asset/ObligationTests.kt | 1 + .../node/utilities/JDBCHashMapTestSuite.kt | 6 +- node/src/main/java/CordaCaplet.java | 13 +- .../kotlin/net/corda/node/driver/Driver.kt | 9 +- .../corda/node/internal/CordaRPCOpsImpl.kt | 3 +- .../node/services/api/CheckpointStorage.kt | 2 +- .../node/services/config/ConfigUtilities.kt | 1 + .../node/services/config/NodeConfiguration.kt | 18 +-- .../services/events/NodeSchedulerService.kt | 4 +- .../messaging/ArtemisMessagingComponent.kt | 6 +- .../services/messaging/NodeMessagingClient.kt | 12 +- .../services/network/NetworkMapService.kt | 6 +- ...achineRecordedTransactionMappingStorage.kt | 2 +- .../persistence/StorageServiceImpl.kt | 2 +- .../node/services/schema/HibernateObserver.kt | 2 +- .../statemachine/StateMachineManager.kt | 2 +- .../node/services/vault/NodeVaultService.kt | 2 +- .../corda/node/utilities/DatabaseSupport.kt | 1 + .../net/corda/node/utilities/JDBCHashMap.kt | 6 +- .../net/corda/node/utilities/JsonSupport.kt | 8 +- .../certsigning/CertificateSigner.kt | 4 +- .../certsigning/CertificateSigningService.kt | 1 + .../net/corda/node/CordaRPCOpsImplTest.kt | 2 +- .../messaging/TwoPartyTradeProtocolTests.kt | 8 +- .../services/InMemoryNetworkMapServiceTest.kt | 4 +- .../node/visualiser/GroupToGraphConversion.kt | 2 +- .../corda/attachmentdemo/AttachmentDemo.kt | 3 +- .../plugin/AttachmentDemoPlugin.kt | 2 +- .../src/main/kotlin/net/corda/irs/IRSDemo.kt | 1 + .../src/main/kotlin/net/corda/irs/Main.kt | 6 +- .../net/corda/irs/api/NodeInterestRates.kt | 3 +- .../main/kotlin/net/corda/irs/contract/IRS.kt | 4 +- .../kotlin/net/corda/irs/contract/IRSUtils.kt | 1 + .../net/corda/irs/flows/ExitServerFlow.kt | 2 +- .../kotlin/net/corda/irs/flows/FixingFlow.kt | 1 + .../net/corda/irs/flows/RatesFixFlow.kt | 2 +- .../corda/irs/flows/UpdateBusinessDayFlow.kt | 2 +- .../net/corda/irs/utilities/HttpUtils.kt | 10 +- .../kotlin/net/corda/irs/testing/IRSTests.kt | 4 +- .../irs/testing/NodeInterestRatesTest.kt | 6 +- .../net/corda/netmap/NetworkMapVisualiser.kt | 12 +- .../kotlin/net/corda/netmap/VisualiserView.kt | 4 +- .../net/corda/netmap/VisualiserViewModel.kt | 14 +- .../net/corda/netmap/MainWindow.fxml | 47 +++---- .../resources/net/corda/netmap/styles.css | 8 ++ .../corda/vega/contracts/PortfolioState.kt | 2 +- .../kotlin/net/corda/vega/flows/SimmFlow.kt | 2 +- .../test/kotlin/net/corda/vega/SwapExample.kt | 8 +- .../kotlin/net/corda/traderdemo/TraderDemo.kt | 2 +- .../kotlin/net/corda/explorer/AmountDiff.kt | 4 +- .../explorer/model/ReportingCurrencyModel.kt | 8 +- .../corda/explorer/ui/ListViewUtilities.kt | 3 +- .../corda/explorer/ui/TableViewUtilities.kt | 3 +- .../explorer/ui/TreeTableViewUtilities.kt | 2 +- .../explorer/css/corda-dark-color-scheme.css | 3 +- .../net/corda/explorer/images/user_b.svg | 40 +++--- .../explorer/views/ContractStatesView.fxml | 8 +- .../net/corda/explorer/views/Dashboard.fxml | 9 +- .../net/corda/explorer/views/LoginView.fxml | 15 +- .../net/corda/explorer/views/MainView.fxml | 16 ++- .../net/corda/explorer/views/Network.fxml | 7 +- .../corda/explorer/views/NewTransaction.fxml | 20 ++- .../net/corda/explorer/views/SearchField.fxml | 13 +- .../net/corda/explorer/views/Settings.fxml | 13 +- .../explorer/views/TransactionViewer.fxml | 11 +- .../views/cordapps/cash/CashStateViewer.fxml | 3 +- .../views/cordapps/cash/CashViewer.fxml | 11 +- .../views/cordapps/cash/NewTransaction.fxml | 20 ++- .../net/corda/explorer/views/login.fxml | 112 +++++++-------- .../net/corda/explorer/views/schedule.fxml | 128 +++++++++--------- .../net/corda/explorer/views/search.fxml | 46 +++---- .../corda/explorer/views/wallet-hover.fxml | 75 +++++----- .../net/corda/loadtest/ConnectionManager.kt | 10 +- .../kotlin/net/corda/loadtest/LoadTest.kt | 3 +- .../net/corda/loadtest/tests/CrossCashTest.kt | 4 +- .../net/corda/loadtest/tests/SelfIssueTest.kt | 2 +- 149 files changed, 763 insertions(+), 618 deletions(-) diff --git a/client/src/integration-test/kotlin/net/corda/client/CordaRPCClientTest.kt b/client/src/integration-test/kotlin/net/corda/client/CordaRPCClientTest.kt index 06ce13c99b..95baaca2ca 100644 --- a/client/src/integration-test/kotlin/net/corda/client/CordaRPCClientTest.kt +++ b/client/src/integration-test/kotlin/net/corda/client/CordaRPCClientTest.kt @@ -84,4 +84,4 @@ class CordaRPCClientTest { } println("Result: ${flowHandle.returnValue.toBlocking().first()}") } - } +} diff --git a/client/src/main/kotlin/net/corda/client/CordaRPCClient.kt b/client/src/main/kotlin/net/corda/client/CordaRPCClient.kt index ce9a52753c..e47dce195d 100644 --- a/client/src/main/kotlin/net/corda/client/CordaRPCClient.kt +++ b/client/src/main/kotlin/net/corda/client/CordaRPCClient.kt @@ -34,6 +34,7 @@ class CordaRPCClient(val host: HostAndPort, override val config: NodeSSLConfigur lateinit var session: ClientSession lateinit var clientImpl: CordaRPCClientImpl } + private val state = ThreadBox(State()) /** Opens the connection to the server and registers a JVM shutdown hook to cleanly disconnect. */ diff --git a/client/src/main/kotlin/net/corda/client/fxutils/AmountBindings.kt b/client/src/main/kotlin/net/corda/client/fxutils/AmountBindings.kt index fb014293b8..cbfc7020c4 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/AmountBindings.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/AmountBindings.kt @@ -1,11 +1,11 @@ package net.corda.client.fxutils -import net.corda.client.model.ExchangeRate -import net.corda.core.contracts.Amount import javafx.beans.binding.Bindings import javafx.beans.value.ObservableValue import javafx.collections.ObservableList import kotlinx.support.jdk8.collections.stream +import net.corda.client.model.ExchangeRate +import net.corda.core.contracts.Amount import org.fxmisc.easybind.EasyBind import java.util.* import java.util.stream.Collectors @@ -44,7 +44,7 @@ object AmountBindings { EasyBind.map( Bindings.createLongBinding({ amounts.stream().collect(Collectors.summingLong { exchange(it) }) - } , arrayOf(amounts)) + }, arrayOf(amounts)) ) { Amount(it.toLong(), currencyValue) } } } diff --git a/client/src/main/kotlin/net/corda/client/fxutils/ChosenList.kt b/client/src/main/kotlin/net/corda/client/fxutils/ChosenList.kt index 7fa60b876c..32a618b851 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/ChosenList.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/ChosenList.kt @@ -22,7 +22,7 @@ import javafx.collections.ObservableListBase */ class ChosenList( private val chosenListObservable: ObservableValue> -): ObservableListBase() { +) : ObservableListBase() { private var currentList = chosenListObservable.value diff --git a/client/src/main/kotlin/net/corda/client/fxutils/ConcatenatedList.kt b/client/src/main/kotlin/net/corda/client/fxutils/ConcatenatedList.kt index 44ca20b229..280f8293d0 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/ConcatenatedList.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/ConcatenatedList.kt @@ -41,6 +41,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans internal val indexMap = HashMap, Pair>>() @VisibleForTesting internal val nestedIndexOffsets = ArrayList(sourceList.size) + init { var offset = 0 sourceList.forEachIndexed { index, observableList -> @@ -78,7 +79,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans permutation[i] = i } // Then the permuted ones. - for (i in firstTouched .. startingOffset + change.to - 1) { + for (i in firstTouched..startingOffset + change.to - 1) { permutation[startingOffset + i] = change.getPermutation(i) } nextPermutation(firstTouched, startingOffset + change.to, permutation) @@ -144,7 +145,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val newSubNestedIndexOffsets = IntArray(change.to - change.from) val firstTouched = if (change.from == 0) 0 else nestedIndexOffsets[change.from - 1] var currentOffset = firstTouched - for (i in 0 .. change.to - change.from - 1) { + for (i in 0..change.to - change.from - 1) { currentOffset += source[change.from + i].size newSubNestedIndexOffsets[i] = currentOffset } @@ -152,24 +153,24 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val concatenatedPermutation = IntArray(newSubNestedIndexOffsets.last()) // Set the non-permuted part var offset = 0 - for (i in 0 .. change.from - 1) { + for (i in 0..change.from - 1) { val nestedList = source[i] - for (j in offset .. offset + nestedList.size - 1) { + for (j in offset..offset + nestedList.size - 1) { concatenatedPermutation[j] = j } offset += nestedList.size } // Now the permuted part - for (i in 0 .. newSubNestedIndexOffsets.size - 1) { + for (i in 0..newSubNestedIndexOffsets.size - 1) { val startingOffset = startingOffsetOf(change.from + i) val permutedListIndex = change.getPermutation(change.from + i) val permutedOffset = (if (permutedListIndex == 0) 0 else newSubNestedIndexOffsets[permutedListIndex - 1]) - for (j in 0 .. source[permutedListIndex].size - 1) { + for (j in 0..source[permutedListIndex].size - 1) { concatenatedPermutation[startingOffset + j] = permutedOffset + j } } // Record permuted offsets - for (i in 0 .. newSubNestedIndexOffsets.size - 1) { + for (i in 0..newSubNestedIndexOffsets.size - 1) { nestedIndexOffsets[change.from + i] = newSubNestedIndexOffsets[i] } nextPermutation(firstTouched, newSubNestedIndexOffsets.last(), concatenatedPermutation) @@ -229,6 +230,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans // Tracks the first position where the *nested* offset is invalid private var firstInvalidatedPosition = sourceList.size + private fun invalidateOffsets(index: Int) { firstInvalidatedPosition = Math.min(firstInvalidatedPosition, index) } @@ -237,7 +239,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans if (firstInvalidatedPosition < source.size) { val firstInvalid = firstInvalidatedPosition var offset = if (firstInvalid == 0) 0 else nestedIndexOffsets[firstInvalid - 1] - for (i in firstInvalid .. source.size - 1) { + for (i in firstInvalid..source.size - 1) { offset += source[i].size if (i < nestedIndexOffsets.size) { nestedIndexOffsets[i] = offset diff --git a/client/src/main/kotlin/net/corda/client/fxutils/FlattenedList.kt b/client/src/main/kotlin/net/corda/client/fxutils/FlattenedList.kt index 8500e0b012..35531f8ede 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/FlattenedList.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/FlattenedList.kt @@ -1,12 +1,10 @@ package net.corda.client.fxutils -import javafx.beans.InvalidationListener import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.collections.transformation.TransformationList -import org.eclipse.jetty.server.Authentication import java.util.* import kotlin.test.assertEquals @@ -30,7 +28,9 @@ class FlattenedList(val sourceList: ObservableList class WrappedObservableValue( val observableValue: ObservableValue ) + val indexMap = HashMap, Pair>>() + init { sourceList.forEachIndexed { index, observableValue -> val wrappedObservableValue = WrappedObservableValue(observableValue) diff --git a/client/src/main/kotlin/net/corda/client/fxutils/LeftOuterJoinedMap.kt b/client/src/main/kotlin/net/corda/client/fxutils/LeftOuterJoinedMap.kt index a893910e5e..4e20966128 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/LeftOuterJoinedMap.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/LeftOuterJoinedMap.kt @@ -2,7 +2,8 @@ package net.corda.client.fxutils import javafx.beans.property.SimpleObjectProperty import javafx.beans.value.ObservableValue -import javafx.collections.* +import javafx.collections.MapChangeListener +import javafx.collections.ObservableMap /** * [LeftOuterJoinedMap] implements a special case of a left outer join where we're matching on primary keys of both diff --git a/client/src/main/kotlin/net/corda/client/fxutils/ObservableUtilities.kt b/client/src/main/kotlin/net/corda/client/fxutils/ObservableUtilities.kt index e158a44950..1cabac56a2 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/ObservableUtilities.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/ObservableUtilities.kt @@ -48,18 +48,22 @@ fun ObservableList.map(cached: Boolean = true, function: (A) -> B) * val aliceHeightPlus2 = ::sumHeight.lift(aliceHeight, 2L.lift()) */ fun A.lift(): ObservableValue = ReadOnlyObjectWrapper(this) + fun ((A) -> R).lift( arg0: ObservableValue ): ObservableValue = EasyBind.map(arg0, this) + fun ((A, B) -> R).lift( arg0: ObservableValue, arg1: ObservableValue ): ObservableValue = EasyBind.combine(arg0, arg1, this) + fun ((A, B, C) -> R).lift( arg0: ObservableValue, arg1: ObservableValue, arg2: ObservableValue ): ObservableValue = EasyBind.combine(arg0, arg1, arg2, this) + fun ((A, B, C, D) -> R).lift( arg0: ObservableValue, arg1: ObservableValue, @@ -74,6 +78,7 @@ fun ((A, B, C, D) -> R).lift( */ fun ObservableValue.bind(function: (A) -> ObservableValue): ObservableValue = EasyBind.monadic(this).flatMap(function) + /** * A variant of [bind] that has out variance on the output type. This is sometimes useful when kotlin is too eager to * propagate variance constraints and type inference fails. @@ -264,9 +269,11 @@ fun ObservableList.leftOuterJoin( fun ObservableList.getValueAt(index: Int): ObservableValue { return Bindings.valueAt(this, index) } + fun ObservableList.first(): ObservableValue { return getValueAt(0) } + fun ObservableList.last(): ObservableValue { return Bindings.createObjectBinding({ if (size > 0) { diff --git a/client/src/main/kotlin/net/corda/client/fxutils/ReplayedList.kt b/client/src/main/kotlin/net/corda/client/fxutils/ReplayedList.kt index b4119bb6d9..162107b5a0 100644 --- a/client/src/main/kotlin/net/corda/client/fxutils/ReplayedList.kt +++ b/client/src/main/kotlin/net/corda/client/fxutils/ReplayedList.kt @@ -25,7 +25,7 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( val permutation = IntArray(to, { c.getPermutation(it) }) val permutedSubList = ArrayList(to - from) permutedSubList.addAll(Collections.nCopies(to - from, null)) - for (i in 0 .. (to - from - 1)) { + for (i in 0..(to - from - 1)) { permutedSubList[permutation[from + i]] = replayedList[from + i] } permutedSubList.forEachIndexed { i, element -> @@ -33,14 +33,14 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { - for (i in c.from .. c.to - 1) { + for (i in c.from..c.to - 1) { replayedList[i] = c.list[i] nextUpdate(i) } } else { if (c.wasRemoved()) { val removePosition = c.from - for (i in 0 .. c.removedSize - 1) { + for (i in 0..c.removedSize - 1) { replayedList.removeAt(removePosition) } nextRemove(c.from, c.removed) @@ -48,7 +48,7 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( if (c.wasAdded()) { val addStart = c.from val addEnd = c.to - for (i in addStart .. addEnd - 1) { + for (i in addStart..addEnd - 1) { replayedList.add(i, c.list[i]) } nextAdd(addStart, addEnd) diff --git a/client/src/main/kotlin/net/corda/client/impl/CordaRPCClientImpl.kt b/client/src/main/kotlin/net/corda/client/impl/CordaRPCClientImpl.kt index abf8c3fe2e..67c8a07d38 100644 --- a/client/src/main/kotlin/net/corda/client/impl/CordaRPCClientImpl.kt +++ b/client/src/main/kotlin/net/corda/client/impl/CordaRPCClientImpl.kt @@ -324,8 +324,8 @@ class CordaRPCClientImpl(private val session: ClientSession, val c = synchronized(this) { consumer } if (c != null) { rpcLog.warn("A hot observable returned from an RPC ($rpcName) was never subscribed to or explicitly closed. " + - "This wastes server-side resources because it was queueing observations for retrieval. " + - "It is being closed now, but please adjust your code to cast the observable to AutoCloseable and then close it explicitly.", rpcLocation) + "This wastes server-side resources because it was queueing observations for retrieval. " + + "It is being closed now, but please adjust your code to cast the observable to AutoCloseable and then close it explicitly.", rpcLocation) c.close() } } diff --git a/client/src/main/kotlin/net/corda/client/mock/Generator.kt b/client/src/main/kotlin/net/corda/client/mock/Generator.kt index 6a5eee00d7..ccc0df1b2f 100644 --- a/client/src/main/kotlin/net/corda/client/mock/Generator.kt +++ b/client/src/main/kotlin/net/corda/client/mock/Generator.kt @@ -1,5 +1,6 @@ package net.corda.client.mock +import net.corda.client.mock.Generator.Companion.choice import net.corda.core.ErrorOr import java.util.* @@ -39,12 +40,16 @@ class Generator(val generate: (SplittableRandom) -> ErrorOr) { // Applicative fun product(other: Generator<(A) -> B>) = Generator { generate(it).combine(other.generate(it)) { a, f -> f(a) } } + fun combine(other1: Generator, function: (A, B) -> R) = product(other1.product(pure({ b -> { a -> function(a, b) } }))) + fun combine(other1: Generator, other2: Generator, function: (A, B, C) -> R) = product(other1.product(other2.product(pure({ c -> { b -> { a -> function(a, b, c) } } })))) + fun combine(other1: Generator, other2: Generator, other3: Generator, function: (A, B, C, D) -> R) = product(other1.product(other2.product(other3.product(pure({ d -> { c -> { b -> { a -> function(a, b, c, d) } } } }))))) + fun combine(other1: Generator, other2: Generator, other3: Generator, other4: Generator, function: (A, B, C, D, E) -> R) = product(other1.product(other2.product(other3.product(other4.product(pure({ e -> { d -> { c -> { b -> { a -> function(a, b, c, d, e) } } } } })))))) @@ -102,7 +107,7 @@ fun Generator.Companion.frequency(vararg generators: Pair Generator.generateOrFail(random: SplittableRandom, numberOfTries: Int = 1): A { var error: Throwable? = null - for (i in 0 .. numberOfTries - 1) { + for (i in 0..numberOfTries - 1) { val result = generate(random) val v = result.value if (v != null) { @@ -122,14 +127,17 @@ fun Generator.Companion.int() = Generator.success(SplittableRandom::nextInt) fun Generator.Companion.bytes(size: Int): Generator = Generator.success { random -> ByteArray(size) { random.nextInt().toByte() } } + fun Generator.Companion.intRange(range: IntRange) = intRange(range.first, range.last) fun Generator.Companion.intRange(from: Int, to: Int): Generator = Generator.success { (from + Math.abs(it.nextInt()) % (to - from + 1)).toInt() } + fun Generator.Companion.longRange(range: LongRange) = longRange(range.first, range.last) fun Generator.Companion.longRange(from: Long, to: Long): Generator = Generator.success { (from + Math.abs(it.nextLong()) % (to - from + 1)).toLong() } + fun Generator.Companion.double() = Generator.success { it.nextDouble() } fun Generator.Companion.doubleRange(from: Double, to: Double): Generator = Generator.success { from + it.nextDouble() * (to - from) @@ -137,7 +145,7 @@ fun Generator.Companion.doubleRange(from: Double, to: Double): Generator fun Generator.Companion.replicate(number: Int, generator: Generator): Generator> { val generators = mutableListOf>() - for (i in 1 .. number) { + for (i in 1..number) { generators.add(generator) } return sequence(generators) @@ -168,10 +176,10 @@ fun Generator.Companion.replicatePoisson(meanSize: Double, generator: fun Generator.Companion.pickOne(list: List) = Generator.intRange(0, list.size - 1).map { list[it] } fun Generator.Companion.pickN(number: Int, list: List) = Generator> { val mask = BitSet(list.size) - for (i in 0 .. Math.min(list.size, number) - 1) { + for (i in 0..Math.min(list.size, number) - 1) { mask[i] = 1 } - for (i in 0 .. mask.size() - 1) { + for (i in 0..mask.size() - 1) { val byte = mask[i] val swapIndex = i + it.nextInt(mask.size() - i) mask[i] = mask[swapIndex] @@ -188,6 +196,7 @@ fun Generator.Companion.pickN(number: Int, list: List) = Generator< fun Generator.Companion.sampleBernoulli(maxRatio: Double = 1.0, vararg collection: A) = sampleBernoulli(listOf(collection), maxRatio) + fun Generator.Companion.sampleBernoulli(collection: Collection, maxRatio: Double = 1.0): Generator> = intRange(0, (maxRatio * collection.size).toInt()).bind { howMany -> replicate(collection.size, Generator.doubleRange(0.0, 1.0)).map { chances -> diff --git a/client/src/main/kotlin/net/corda/client/mock/Generators.kt b/client/src/main/kotlin/net/corda/client/mock/Generators.kt index f41cdc4999..dd766cc4c9 100644 --- a/client/src/main/kotlin/net/corda/client/mock/Generators.kt +++ b/client/src/main/kotlin/net/corda/client/mock/Generators.kt @@ -9,7 +9,7 @@ fun generateCurrency(): Generator { } fun generateAmount(min: Long, max: Long, tokenGenerator: Generator): Generator> { - return Generator.longRange(min, max).combine(tokenGenerator) { quantity, token -> Amount(quantity, token) } + return Generator.longRange(min, max).combine(tokenGenerator) { quantity, token -> Amount(quantity, token) } } fun generateCurrencyAmount(min: Long, max: Long): Generator> { diff --git a/client/src/main/kotlin/net/corda/client/model/ExchangeRateModel.kt b/client/src/main/kotlin/net/corda/client/model/ExchangeRateModel.kt index 43058a0aa7..a3108649fb 100644 --- a/client/src/main/kotlin/net/corda/client/model/ExchangeRateModel.kt +++ b/client/src/main/kotlin/net/corda/client/model/ExchangeRateModel.kt @@ -1,16 +1,18 @@ package net.corda.client.model -import net.corda.core.contracts.Amount import javafx.beans.property.SimpleObjectProperty import javafx.beans.value.ObservableValue +import net.corda.core.contracts.Amount import java.util.* interface ExchangeRate { fun rate(from: Currency, to: Currency): Double } + fun ExchangeRate.exchangeAmount(amount: Amount, to: Currency) = Amount(exchangeDouble(amount, to).toLong(), to) + fun ExchangeRate.exchangeDouble(amount: Amount, to: Currency) = rate(amount.token, to) * amount.quantity diff --git a/client/src/main/kotlin/net/corda/client/model/GatheredTransactionDataModel.kt b/client/src/main/kotlin/net/corda/client/model/GatheredTransactionDataModel.kt index be0ed0ae4f..5132b3b2c1 100644 --- a/client/src/main/kotlin/net/corda/client/model/GatheredTransactionDataModel.kt +++ b/client/src/main/kotlin/net/corda/client/model/GatheredTransactionDataModel.kt @@ -10,7 +10,6 @@ import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateRef import net.corda.core.crypto.SecureHash import net.corda.core.flows.StateMachineRunId -import net.corda.core.node.services.StateMachineTransactionMapping import net.corda.core.transactions.SignedTransaction import net.corda.node.services.messaging.StateMachineUpdate import org.fxmisc.easybind.EasyBind @@ -29,6 +28,7 @@ data class PartiallyResolvedTransaction( val transaction: SignedTransaction, val inputs: List>) { val id = transaction.id + sealed class InputResolution(val stateRef: StateRef) { class Unresolved(stateRef: StateRef) : InputResolution(stateRef) class Resolved(val stateAndRef: StateAndRef) : InputResolution(stateAndRef.ref) @@ -56,6 +56,7 @@ data class PartiallyResolvedTransaction( sealed class TransactionCreateStatus(val message: String?) { class Started(message: String?) : TransactionCreateStatus(message) class Failed(message: String?) : TransactionCreateStatus(message) + override fun toString(): String = message ?: javaClass.simpleName } @@ -64,8 +65,9 @@ data class FlowStatus( ) sealed class StateMachineStatus(val stateMachineName: String) { - class Added(stateMachineName: String): StateMachineStatus(stateMachineName) - class Removed(stateMachineName: String): StateMachineStatus(stateMachineName) + class Added(stateMachineName: String) : StateMachineStatus(stateMachineName) + class Removed(stateMachineName: String) : StateMachineStatus(stateMachineName) + override fun toString(): String = "${javaClass.simpleName}($stateMachineName)" } diff --git a/client/src/main/kotlin/net/corda/client/model/Models.kt b/client/src/main/kotlin/net/corda/client/model/Models.kt index 0db4945f27..1d2b6ab460 100644 --- a/client/src/main/kotlin/net/corda/client/model/Models.kt +++ b/client/src/main/kotlin/net/corda/client/model/Models.kt @@ -106,7 +106,7 @@ object Models { private val dependencyGraph = HashMap, MutableSet>>() fun initModel(klass: KClass) = modelStore.getOrPut(klass) { klass.java.newInstance() } - fun get(klass: KClass, origin: KClass<*>) : M { + fun get(klass: KClass, origin: KClass<*>): M { dependencyGraph.getOrPut(origin) { mutableSetOf>() }.add(klass) val model = initModel(klass) if (model.javaClass != klass.java) { @@ -116,57 +116,69 @@ object Models { @Suppress("UNCHECKED_CAST") return model as M } - inline fun get(origin: KClass<*>) : M = get(M::class, origin) + + inline fun get(origin: KClass<*>): M = get(M::class, origin) } sealed class TrackedDelegate(val klass: KClass) { - init { Models.initModel(klass) } + init { + Models.initModel(klass) + } - class ObservableDelegate (klass: KClass, val observableProperty: (M) -> Observable) : TrackedDelegate(klass) { + class ObservableDelegate(klass: KClass, val observableProperty: (M) -> Observable) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): Observable { return observableProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } - class ObserverDelegate (klass: KClass, val observerProperty: (M) -> Observer) : TrackedDelegate(klass) { + + class ObserverDelegate(klass: KClass, val observerProperty: (M) -> Observer) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): Observer { return observerProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } - class SubjectDelegate (klass: KClass, val subjectProperty: (M) -> Subject) : TrackedDelegate(klass) { + + class SubjectDelegate(klass: KClass, val subjectProperty: (M) -> Subject) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): Subject { return subjectProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } - class EventStreamDelegate (klass: KClass, val eventStreamProperty: (M) -> org.reactfx.EventStream) : TrackedDelegate(klass) { + + class EventStreamDelegate(klass: KClass, val eventStreamProperty: (M) -> org.reactfx.EventStream) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): org.reactfx.EventStream { return eventStreamProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } - class EventSinkDelegate (klass: KClass, val eventSinkProperty: (M) -> org.reactfx.EventSink) : TrackedDelegate(klass) { + + class EventSinkDelegate(klass: KClass, val eventSinkProperty: (M) -> org.reactfx.EventSink) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): org.reactfx.EventSink { return eventSinkProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } + class ObservableValueDelegate(klass: KClass, val observableValueProperty: (M) -> ObservableValue) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableValue { return observableValueProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } + class WritableValueDelegate(klass: KClass, val writableValueProperty: (M) -> WritableValue) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): WritableValue { return writableValueProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } + class ObservableListDelegate(klass: KClass, val observableListProperty: (M) -> ObservableList) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableList { return observableListProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } + class ObservableListReadOnlyDelegate(klass: KClass, val observableListReadOnlyProperty: (M) -> ObservableList) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableList { return observableListReadOnlyProperty(Models.get(klass, thisRef.javaClass.kotlin)) } } + class ObjectPropertyDelegate(klass: KClass, val objectPropertyProperty: (M) -> ObjectProperty) : TrackedDelegate(klass) { operator fun getValue(thisRef: Any, property: KProperty<*>): ObjectProperty { return objectPropertyProperty(Models.get(klass, thisRef.javaClass.kotlin)) diff --git a/client/src/test/kotlin/net/corda/client/ClientRPCInfrastructureTests.kt b/client/src/test/kotlin/net/corda/client/ClientRPCInfrastructureTests.kt index ada6567c81..f9d4ef14cd 100644 --- a/client/src/test/kotlin/net/corda/client/ClientRPCInfrastructureTests.kt +++ b/client/src/test/kotlin/net/corda/client/ClientRPCInfrastructureTests.kt @@ -81,6 +81,7 @@ class ClientRPCInfrastructureTests { } producer.send(toAddress, msg) } + override fun getUser(message: ClientMessage): User = authenticatedUser } serverThread = AffinityExecutor.ServiceAffinityExecutor("unit-tests-rpc-dispatch-thread", 1) @@ -139,7 +140,8 @@ class ClientRPCInfrastructureTests { override fun barf(): Unit = throw IllegalArgumentException("Barf!") - override fun void() { } + override fun void() { + } override fun someCalculation(str: String, num: Int) = "$str $num" diff --git a/client/src/test/kotlin/net/corda/client/fxutils/ConcatenatedListTest.kt b/client/src/test/kotlin/net/corda/client/fxutils/ConcatenatedListTest.kt index 75482612ff..001d567ac7 100644 --- a/client/src/test/kotlin/net/corda/client/fxutils/ConcatenatedListTest.kt +++ b/client/src/test/kotlin/net/corda/client/fxutils/ConcatenatedListTest.kt @@ -24,7 +24,7 @@ class ConcatenatedListTest { fun ConcatenatedList.checkInvariants() { assertEquals(nestedIndexOffsets.size, source.size) var currentOffset = 0 - for (i in 0 .. source.size - 1) { + for (i in 0..source.size - 1) { currentOffset += source[i].size assertEquals(nestedIndexOffsets[i], currentOffset) } diff --git a/client/src/test/kotlin/net/corda/client/fxutils/LeftOuterJoinedMapTest.kt b/client/src/test/kotlin/net/corda/client/fxutils/LeftOuterJoinedMapTest.kt index e46e4ebd3d..eb6bbc18da 100644 --- a/client/src/test/kotlin/net/corda/client/fxutils/LeftOuterJoinedMapTest.kt +++ b/client/src/test/kotlin/net/corda/client/fxutils/LeftOuterJoinedMapTest.kt @@ -4,7 +4,6 @@ import javafx.collections.FXCollections import javafx.collections.ObservableList import org.junit.Before import org.junit.Test -import java.util.* import kotlin.test.assertEquals class LeftOuterJoinedMapTest { @@ -23,7 +22,7 @@ class LeftOuterJoinedMapTest { dogs = FXCollections.observableArrayList(Dog("Scruffy", owner = "Bob")) joinedList = people.leftOuterJoin(dogs, Person::name, Dog::owner) { person, dogs -> Pair(person, dogs) } // We replay the nested observable as well - replayedList = ReplayedList(joinedList.map { Pair(it.first, ReplayedList(it.second)) }) + replayedList = ReplayedList(joinedList.map { Pair(it.first, ReplayedList(it.second)) }) } // TODO perhaps these are too brittle because they test indices that are not stable. Use Expect dsl? diff --git a/core/src/main/java/net/corda/core/crypto/Base58.java b/core/src/main/java/net/corda/core/crypto/Base58.java index fe8141a8a0..b831886e87 100644 --- a/core/src/main/java/net/corda/core/crypto/Base58.java +++ b/core/src/main/java/net/corda/core/crypto/Base58.java @@ -1,7 +1,7 @@ package net.corda.core.crypto; -import java.math.BigInteger; -import java.util.Arrays; +import java.math.*; +import java.util.*; /** * Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings. @@ -128,8 +128,8 @@ public class Base58 { * removed from the returned data. * * @param input the base58-encoded string to decode (which should include the checksum) - * @throws AddressFormatException if the input is not base 58 or the checksum does not validate. * @return the original data bytes less the last 4 bytes (the checksum). + * @throws AddressFormatException if the input is not base 58 or the checksum does not validate. */ public static byte[] decodeChecked(String input) throws AddressFormatException { byte[] decoded = decode(input); diff --git a/core/src/main/kotlin/net/corda/core/Utils.kt b/core/src/main/kotlin/net/corda/core/Utils.kt index 847535ab2d..2f73a3238c 100644 --- a/core/src/main/kotlin/net/corda/core/Utils.kt +++ b/core/src/main/kotlin/net/corda/core/Utils.kt @@ -34,7 +34,7 @@ import kotlin.concurrent.withLock import kotlin.reflect.KProperty val Int.days: Duration get() = Duration.ofDays(this.toLong()) -@Suppress("unused") // It's here for completeness +@Suppress("unused") // It's here for completeness val Int.hours: Duration get() = Duration.ofHours(this.toLong()) val Int.minutes: Duration get() = Duration.ofMinutes(this.toLong()) val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong()) @@ -51,6 +51,7 @@ fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else /** Like the + operator but throws an exception in case of integer overflow. */ infix fun Int.checkedAdd(b: Int) = Math.addExact(this, b) + /** Like the + operator but throws an exception in case of integer overflow. */ @Suppress("unused") infix fun Long.checkedAdd(b: Long) = Math.addExact(this, b) @@ -125,6 +126,7 @@ fun ListenableFuture.toObservable(): Observable { /** Allows you to write code like: Paths.get("someDir") / "subdir" / "filename" but using the Paths API to avoid platform separator problems. */ operator fun Path.div(other: String): Path = resolve(other) + fun Path.createDirectory(vararg attrs: FileAttribute<*>): Path = Files.createDirectory(this, *attrs) fun Path.createDirectories(vararg attrs: FileAttribute<*>): Path = Files.createDirectories(this, *attrs) fun Path.exists(vararg options: LinkOption): Boolean = Files.exists(this, *options) @@ -142,6 +144,7 @@ inline fun Path.write(createDirs: Boolean = false, vararg options: OpenOption = } Files.newOutputStream(this, *options).use(block) } + inline fun Path.readLines(charset: Charset = UTF_8, block: (Stream) -> R): R = Files.lines(this, charset).use(block) fun Path.writeLines(lines: Iterable, charset: Charset = UTF_8, vararg options: OpenOption): Path = Files.write(this, lines, charset, *options) @@ -233,6 +236,7 @@ class ThreadBox(val content: T, val lock: ReentrantLock = ReentrantLock() check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." }) return body(content) } + fun checkNotLocked() = check(!lock.isHeldByCurrentThread) } @@ -300,7 +304,12 @@ data class ErrorOr private constructor(val value: A?, val error: Throwabl companion object { /** Runs the given lambda and wraps the result. */ - inline fun catch(body: () -> T): ErrorOr = try { ErrorOr(body()) } catch (t: Throwable) { ErrorOr.of(t) } + inline fun catch(body: () -> T): ErrorOr = try { + ErrorOr(body()) + } catch (t: Throwable) { + ErrorOr.of(t) + } + fun of(t: Throwable) = ErrorOr(null, t) } diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt index f7953b61c9..d1396f40e3 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt @@ -1,4 +1,5 @@ @file:JvmName("ContractsDSL") + package net.corda.core.contracts import net.corda.core.crypto.CompositeKey @@ -19,6 +20,7 @@ import java.util.* //// Currencies /////////////////////////////////////////////////////////////////////////////////////////////////////// fun currency(code: String) = Currency.getInstance(code)!! + fun commodity(code: String) = Commodity.getInstance(code)!! @JvmField val USD = currency("USD") @@ -63,17 +65,17 @@ inline fun requireThat(body: Requirements.() -> R) = Requirements.body() inline fun Collection>.select(signer: CompositeKey? = null, party: Party? = null) = 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) } + 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) } /** Filters the command list by type, parties and public keys all at once. */ inline fun Collection>.select(signers: Collection?, parties: 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) } + 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) } inline fun Collection>.requireSingleCommand() = try { select().single() diff --git a/core/src/main/kotlin/net/corda/core/contracts/DummyState.kt b/core/src/main/kotlin/net/corda/core/contracts/DummyState.kt index 73567fbd49..48195ed0d6 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/DummyState.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/DummyState.kt @@ -1,6 +1,7 @@ package net.corda.core.contracts import net.corda.core.crypto.CompositeKey + /** * Dummy state for use in testing. Not part of any contract, not even the [DummyContract]. */ diff --git a/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt b/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt index 84276a0eef..8fa86b3aa7 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt @@ -61,7 +61,7 @@ data class Amount(val quantity: Long, val token: T) : Comparable> { operator fun times(other: Long): Amount = Amount(Math.multiplyExact(quantity, other), token) operator fun div(other: Int): Amount = Amount(quantity / other, token) operator fun times(other: Int): Amount = Amount(Math.multiplyExact(quantity, other.toLong()), token) - + override fun toString(): String = (BigDecimal(quantity).divide(BigDecimal(100))).setScale(2).toPlainString() + " " + token override fun compareTo(other: Amount): Int { @@ -267,7 +267,7 @@ enum class Frequency(val annualCompoundCount: Int) { } -@Suppress("unused") // This utility may be useful in future. TODO: Review before API stability guarantees in place. +@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 @@ -379,7 +379,7 @@ open class BusinessCalendar private constructor(val holidayDates: List= 0) - if ( i == 0 ) return date + if (i == 0) return date var retDate = date var ctr = 0 while (ctr < i) { @@ -442,6 +442,7 @@ data class Commodity(val commodityCode: String, // Simple example commodity, as in http://www.investopedia.com/university/commodities/commodities14.asp Pair("FCOJ", Commodity("FCOJ", "Frozen concentrated orange juice")) ) + fun getInstance(commodityCode: String): Commodity? = registry[commodityCode] } @@ -461,13 +462,14 @@ data class Commodity(val commodityCode: String, */ data class UniqueIdentifier(val externalId: String? = null, val id: UUID = UUID.randomUUID()) : Comparable { override fun toString(): String = if (externalId != null) "${externalId}_$id" else id.toString() + companion object { /** * Helper function for unit tests where the UUID needs to be manually initialised for consistency. */ @VisibleForTesting - fun fromString(name: String) : UniqueIdentifier - = UniqueIdentifier(null, UUID.fromString(name)) + fun fromString(name: String): UniqueIdentifier + = UniqueIdentifier(null, UUID.fromString(name)) } override fun compareTo(other: UniqueIdentifier): Int = id.compareTo(other.id) diff --git a/core/src/main/kotlin/net/corda/core/contracts/FungibleAsset.kt b/core/src/main/kotlin/net/corda/core/contracts/FungibleAsset.kt index 62c48147d4..34b618750e 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/FungibleAsset.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/FungibleAsset.kt @@ -46,7 +46,9 @@ interface FungibleAsset : OwnableState { * A command stating that money has been withdrawn from the shared ledger and is now accounted for * in some other way. */ - interface Exit : Commands { val amount: Amount> } + interface Exit : Commands { + val amount: Amount> + } } } diff --git a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt index 663a89d0eb..1434087756 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt @@ -26,7 +26,7 @@ interface NamedByHash { /** * Interface for state objects that support being netted with other state objects. */ -interface BilateralNettableState> { +interface BilateralNettableState> { /** * 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. @@ -43,7 +43,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. @@ -51,7 +51,7 @@ interface MultilateralNettableState { val multilateralNetState: T } -interface NettableState, T: Any>: BilateralNettableState, +interface NettableState, T : Any> : BilateralNettableState, MultilateralNettableState /** @@ -154,6 +154,7 @@ data class TransactionState( /** Wraps the [ContractState] in a [TransactionState] object */ infix fun T.`with notary`(newNotary: Party) = withNotary(newNotary) + infix fun T.withNotary(newNotary: Party) = TransactionState(this, newNotary) /** @@ -222,7 +223,7 @@ data class ScheduledActivity(val logicRef: FlowLogicRef, override val scheduledA * * This simplifies the job of tracking the current version of certain types of state in e.g. a vault. */ -interface LinearState: ContractState { +interface LinearState : ContractState { /** * Unique id shared by all LinearState states throughout history within the vaults of all parties. * Verify methods should check that one input and one output share the id in a transaction, @@ -465,11 +466,11 @@ interface Attachment : NamedByHash { * @throws FileNotFoundException if the given path doesn't exist in the attachment. */ fun extractFile(path: String, outputTo: OutputStream) { - val p = path.toLowerCase().split('\\','/') + val p = path.toLowerCase().split('\\', '/') openAsJAR().use { jar -> while (true) { val e = jar.nextJarEntry ?: break - if (e.name.toLowerCase().split('\\','/') == p) { + if (e.name.toLowerCase().split('\\', '/') == p) { jar.copyTo(outputTo) return } diff --git a/core/src/main/kotlin/net/corda/core/contracts/TransactionTypes.kt b/core/src/main/kotlin/net/corda/core/contracts/TransactionTypes.kt index ff943a6d66..37935f4257 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/TransactionTypes.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/TransactionTypes.kt @@ -58,8 +58,7 @@ sealed class TransactionType { // are any inputs, all outputs must have the same notary. // TODO: Is that the correct set of restrictions? May need to come back to this, see if we can be more // flexible on output notaries. - if (tx.notary != null - && tx.inputs.isNotEmpty()) { + if (tx.notary != null && tx.inputs.isNotEmpty()) { tx.outputs.forEach { if (it.notary != tx.notary) { throw TransactionVerificationException.NotaryChangeInWrongTransactionType(tx, it.notary) @@ -82,8 +81,10 @@ sealed class TransactionType { // Validate that all encumbrances exist within the set of input states. tx.inputs.filter { it.state.data.encumbrance != null }.forEach { encumberedInput -> - if (tx.inputs.none { it.ref.txhash == encumberedInput.ref.txhash && - it.ref.index == encumberedInput.state.data.encumbrance }) { + if (tx.inputs.none { + it.ref.txhash == encumberedInput.ref.txhash && + it.ref.index == encumberedInput.state.data.encumbrance + }) { throw TransactionVerificationException.TransactionMissingEncumbranceException( tx, encumberedInput.state.data.encumbrance!!, TransactionVerificationException.Direction.INPUT @@ -93,7 +94,7 @@ sealed class TransactionType { // Check that, in the outputs, an encumbered state does not refer to itself as the encumbrance, // and that the number of outputs can contain the encumbrance. - for ((i, output) in tx.outputs.withIndex() ) { + for ((i, output) in tx.outputs.withIndex()) { val encumbranceIndex = output.data.encumbrance ?: continue if (encumbranceIndex == i || encumbranceIndex >= tx.outputs.size) { throw TransactionVerificationException.TransactionMissingEncumbranceException( diff --git a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt index 2f281a3542..034dc16c63 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt @@ -88,6 +88,7 @@ data class TransactionForContract(val inputs: List, class TransactionResolutionException(val hash: SecureHash) : Exception() { override fun toString() = "Transaction resolution failure for $hash" } + class TransactionConflictException(val conflictRef: StateRef, val tx1: LedgerTransaction, val tx2: LedgerTransaction) : Exception() sealed class TransactionVerificationException(val tx: LedgerTransaction, cause: Throwable?) : Exception(cause) { @@ -96,14 +97,17 @@ sealed class TransactionVerificationException(val tx: LedgerTransaction, cause: class SignersMissing(tx: LedgerTransaction, val missing: List) : TransactionVerificationException(tx, null) { override fun toString() = "Signers missing: ${missing.joinToString()}" } + class InvalidNotaryChange(tx: LedgerTransaction) : TransactionVerificationException(tx, null) class NotaryChangeInWrongTransactionType(tx: LedgerTransaction, val outputNotary: Party) : TransactionVerificationException(tx, null) { override fun toString(): String = "Found unexpected notary change in transaction. Tx notary: ${tx.notary}, found: ${outputNotary}" } + class TransactionMissingEncumbranceException(tx: LedgerTransaction, val missing: Int, val inOut: Direction) : TransactionVerificationException(tx, null) { override val message: String? get() = "Missing required encumbrance ${missing} in ${inOut}" } + enum class Direction { INPUT, OUTPUT diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/ClauseVerifier.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/ClauseVerifier.kt index 4fd06c4518..c9991a5e22 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/ClauseVerifier.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/ClauseVerifier.kt @@ -1,7 +1,11 @@ @file:JvmName("ClauseVerifier") + package net.corda.core.contracts.clauses -import net.corda.core.contracts.* +import net.corda.core.contracts.AuthenticatedObject +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.TransactionForContract /** * Verify a transaction against the given list of clauses. @@ -11,9 +15,9 @@ import net.corda.core.contracts.* * @param commands commands extracted from the transaction, which are relevant to the * clauses. */ -fun verifyClause(tx: TransactionForContract, - clause: Clause, - commands: List>) { +fun verifyClause(tx: TransactionForContract, + clause: Clause, + commands: List>) { if (Clause.log.isTraceEnabled) { clause.getExecutionPath(commands).forEach { Clause.log.trace("Tx ${tx.origHash} clause: ${clause}") diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/CompositeClause.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/CompositeClause.kt index a8907755e7..875544ec0c 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/CompositeClause.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/CompositeClause.kt @@ -7,11 +7,13 @@ import net.corda.core.contracts.ContractState /** * Abstract supertype for clauses which compose other clauses together in some logical manner. */ -abstract class CompositeClause: Clause() { +abstract class CompositeClause : Clause() { /** List of clauses under this composite clause */ abstract val clauses: List> + override fun getExecutionPath(commands: List>): List> = matchedClauses(commands).flatMap { it.getExecutionPath(commands) } + /** Determine which clauses are matched by the supplied commands */ abstract fun matchedClauses(commands: List>): List> } diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/GroupClauseVerifier.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/GroupClauseVerifier.kt index 99625cdfb4..f8634a812a 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/GroupClauseVerifier.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/GroupClauseVerifier.kt @@ -10,7 +10,7 @@ abstract class GroupClauseVerifier( abstract fun groupStates(tx: TransactionForContract): List> override fun getExecutionPath(commands: List>): List> - = clause.getExecutionPath(commands) + = clause.getExecutionPath(commands) override fun verify(tx: TransactionForContract, inputs: List, diff --git a/core/src/main/kotlin/net/corda/core/crypto/PartialMerkleTree.kt b/core/src/main/kotlin/net/corda/core/crypto/PartialMerkleTree.kt index bcc13f810f..36d12a1924 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/PartialMerkleTree.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/PartialMerkleTree.kt @@ -5,7 +5,7 @@ import net.corda.core.transactions.hashConcat import java.util.* -class MerkleTreeException(val reason: String): Exception() { +class MerkleTreeException(val reason: String) : Exception() { override fun toString() = "Partial Merkle Tree exception. Reason: $reason" } @@ -55,9 +55,9 @@ class PartialMerkleTree(val root: PartialTree) { * it's easier to extract hashes used as a base for this tree. */ sealed class PartialTree() { - class IncludedLeaf(val hash: SecureHash): PartialTree() - class Leaf(val hash: SecureHash): PartialTree() - class Node(val left: PartialTree, val right: PartialTree): PartialTree() + class IncludedLeaf(val hash: SecureHash) : PartialTree() + class Leaf(val hash: SecureHash) : PartialTree() + class Node(val left: PartialTree, val right: PartialTree) : PartialTree() } companion object { @@ -70,7 +70,7 @@ class PartialMerkleTree(val root: PartialTree) { val usedHashes = ArrayList() val tree = buildPartialTree(merkleRoot, includeHashes, usedHashes) //Too much included hashes or different ones. - if(includeHashes.size != usedHashes.size) + if (includeHashes.size != usedHashes.size) throw MerkleTreeException("Some of the provided hashes are not in the tree.") return PartialMerkleTree(tree.second) } diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowLogicRef.kt b/core/src/main/kotlin/net/corda/core/flows/FlowLogicRef.kt index 08acb753cb..9ee5cf9556 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowLogicRef.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowLogicRef.kt @@ -52,7 +52,7 @@ class FlowLogicRefFactory(private val flowWhitelist: Map>) : fun createKotlin(flowLogicClassName: String, args: Map, attachments: List = emptyList()): FlowLogicRef { val context = AppContext(attachments) validateFlowClassName(flowLogicClassName, context) - for(arg in args.values.filterNotNull()) { + for (arg in args.values.filterNotNull()) { validateArgClassName(flowLogicClassName, arg.javaClass.name, context) } val clazz = Class.forName(flowLogicClassName) diff --git a/core/src/main/kotlin/net/corda/core/node/PhysicalLocationStructures.kt b/core/src/main/kotlin/net/corda/core/node/PhysicalLocationStructures.kt index e567ad468e..6f595a4fbc 100644 --- a/core/src/main/kotlin/net/corda/core/node/PhysicalLocationStructures.kt +++ b/core/src/main/kotlin/net/corda/core/node/PhysicalLocationStructures.kt @@ -17,7 +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. + @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/net/corda/core/node/ServiceHub.kt b/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt index 515f33adf0..18664fdf82 100644 --- a/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt +++ b/core/src/main/kotlin/net/corda/core/node/ServiceHub.kt @@ -75,6 +75,7 @@ interface ServiceHub { val notaryIdentityKey: KeyPair get() = this.keyManagementService.toKeyPair(this.myInfo.notaryIdentity.owningKey.keys) } + /** * Given some [SignedTransaction]s, writes them to the local storage for validated transactions and then * sends them to the vault for further processing. diff --git a/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt b/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt index 999b7b29bc..611ec060d2 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt @@ -201,13 +201,12 @@ class ImmutableClassSerializer(val klass: KClass) : Serializer() } } -inline fun Kryo.useClassLoader(cl: ClassLoader, body: () -> T) : T { +inline fun Kryo.useClassLoader(cl: ClassLoader, body: () -> T): T { val tmp = this.classLoader ?: ClassLoader.getSystemClassLoader() this.classLoader = cl try { return body() - } - finally { + } finally { this.classLoader = tmp } } @@ -333,6 +332,7 @@ fun createKryo(k: Kryo = Kryo()): Kryo { register(Kryo::class.java, object : Serializer() { override fun write(kryo: Kryo, output: Output, obj: Kryo) { } + override fun read(kryo: Kryo, input: Input, type: Class): Kryo { return createKryo((Fiber.getFiberSerializer() as KryoSerializer).kryo) } @@ -412,8 +412,7 @@ object ReferencesAwareJavaSerializer : JavaSerializer() { override fun write(kryo: Kryo, output: Output, obj: Any) { if (kryo.references) { super.write(kryo, output, obj) - } - else { + } else { ObjectOutputStream(output).use { it.writeObject(obj) } @@ -423,8 +422,7 @@ object ReferencesAwareJavaSerializer : JavaSerializer() { override fun read(kryo: Kryo, input: Input, type: Class): Any { return if (kryo.references) { super.read(kryo, input, type) - } - else { + } else { ObjectInputStream(input).use(ObjectInputStream::readObject) } } @@ -455,7 +453,7 @@ object OrderedSerializer : Serializer>() { val linkedMap = LinkedHashMap() val sorted = obj.toList().sortedBy { it.first.hashCode() } for ((k, v) in sorted) { - linkedMap.put(k,v) + linkedMap.put(k, v) } kryo.writeClassAndObject(output, linkedMap) } diff --git a/core/src/main/kotlin/net/corda/core/testing/Generators.kt b/core/src/main/kotlin/net/corda/core/testing/Generators.kt index b70640f7e2..5247506ee1 100644 --- a/core/src/main/kotlin/net/corda/core/testing/Generators.kt +++ b/core/src/main/kotlin/net/corda/core/testing/Generators.kt @@ -27,13 +27,13 @@ fun Generator.generateList(random: SourceOfRandomness, status: Generation return arrayGenerator.generate(random, status) as List } -class PrivateKeyGenerator: Generator(PrivateKey::class.java) { +class PrivateKeyGenerator : Generator(PrivateKey::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): PrivateKey { return entropyToKeyPair(random.nextBigInteger(32)).private } } -class PublicKeyGenerator: Generator(PublicKey::class.java) { +class PublicKeyGenerator : Generator(PublicKey::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): PublicKey { return entropyToKeyPair(random.nextBigInteger(32)).public } @@ -45,25 +45,25 @@ class CompositeKeyGenerator : Generator(CompositeKey::class.java) } } -class PartyGenerator: Generator(Party::class.java) { +class PartyGenerator : Generator(Party::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): Party { return Party(StringGenerator().generate(random, status), CompositeKeyGenerator().generate(random, status)) } } -class PartyAndReferenceGenerator: Generator(PartyAndReference::class.java) { +class PartyAndReferenceGenerator : Generator(PartyAndReference::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): PartyAndReference { return PartyAndReference(PartyGenerator().generate(random, status), OpaqueBytes(random.nextBytes(16))) } } -class SecureHashGenerator: Generator(SecureHash::class.java) { +class SecureHashGenerator : Generator(SecureHash::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): SecureHash { return SecureHash.Companion.sha256(random.nextBytes(16)) } } -class StateRefGenerator: Generator(StateRef::class.java) { +class StateRefGenerator : Generator(StateRef::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): StateRef { return StateRef(SecureHash.Companion.sha256(random.nextBytes(16)), random.nextInt(0, 10)) } @@ -94,6 +94,7 @@ class CurrencyGenerator() : Generator(Currency::class.java) { companion object { val currencies = Currency.getAvailableCurrencies().toList() } + override fun generate(random: SourceOfRandomness, status: GenerationStatus): Currency { return currencies[random.nextInt(0, currencies.size - 1)] } diff --git a/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt index e00c0c5fa4..26c44f711f 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt @@ -31,7 +31,9 @@ class LedgerTransaction( timestamp: Timestamp?, type: TransactionType ) : BaseTransaction(inputs, outputs, notary, signers, type, timestamp) { - init { checkInvariants() } + init { + checkInvariants() + } @Suppress("UNCHECKED_CAST") fun outRef(index: Int) = StateAndRef(outputs[index] as TransactionState, StateRef(id, index)) diff --git a/core/src/main/kotlin/net/corda/core/transactions/MerkleTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/MerkleTransaction.kt index dc8b269b54..1eacf56258 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/MerkleTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/MerkleTransaction.kt @@ -32,7 +32,7 @@ fun WireTransaction.calculateLeavesHashes(): List { fun SecureHash.hashConcat(other: SecureHash) = (this.bytes + other.bytes).sha256() -fun serializedHash(x: T): SecureHash { +fun serializedHash(x: T): SecureHash { val kryo = extendKryoHash(createKryo()) //Dealing with HashMaps inside states. return x.serialize(kryo).hash } @@ -47,12 +47,12 @@ fun serializedHash(x: T): SecureHash { * If a row in a tree has an odd number of elements - the final hash is hashed with itself. */ sealed class MerkleTree(val hash: SecureHash) { - class Leaf(val value: SecureHash): MerkleTree(value) - class Node(val value: SecureHash, val left: MerkleTree, val right: MerkleTree): MerkleTree(value) + class Leaf(val value: SecureHash) : MerkleTree(value) + class Node(val value: SecureHash, val left: MerkleTree, val right: MerkleTree) : MerkleTree(value) //DuplicatedLeaf is storing a hash of the rightmost node that had to be duplicated to obtain the tree. //That duplication can cause problems while building and verifying partial tree (especially for trees with duplicate //attachments or commands). - class DuplicatedLeaf(val value: SecureHash): MerkleTree(value) + class DuplicatedLeaf(val value: SecureHash) : MerkleTree(value) fun hashNodes(right: MerkleTree): MerkleTree { val newHash = this.hash.hashConcat(right.hash) @@ -84,15 +84,15 @@ sealed class MerkleTree(val hash: SecureHash) { while (i < lastNodesList.size) { val left = lastNodesList[i] val n = lastNodesList.size + // If there is an odd number of elements at this level, + // the last element is hashed with itself and stored as a Leaf. val right = when { - //If there is an odd number of elements at this level, - //the last element is hashed with itself and stored as a Leaf. - i + 1 > n - 1 -> MerkleTree.DuplicatedLeaf(lastNodesList[n-1].hash) - else -> lastNodesList[i+1] + i + 1 > n - 1 -> MerkleTree.DuplicatedLeaf(lastNodesList[n - 1].hash) + else -> lastNodesList[i + 1] } val combined = left.hashNodes(right) newLevelHashes.add(combined) - i+=2 + i += 2 } return buildMerkleTree(newLevelHashes) } @@ -109,7 +109,7 @@ class FilteredLeaves( val attachments: List, val commands: List ) { - fun getFilteredHashes(): List{ + fun getFilteredHashes(): List { val resultHashes = ArrayList() val entries = listOf(inputs, outputs, attachments, commands) entries.forEach { it.mapTo(resultHashes, { x -> serializedHash(x) }) } @@ -127,7 +127,7 @@ class FilterFuns( val filterAttachments: (SecureHash) -> Boolean = { false }, val filterCommands: (Command) -> Boolean = { false } ) { - fun genericFilter(elem: T): Boolean { + fun genericFilter(elem: T): Boolean { return when (elem) { is StateRef -> filterInputs(elem) is TransactionState<*> -> filterOutputs(elem) diff --git a/core/src/main/kotlin/net/corda/core/transactions/SignedTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/SignedTransaction.kt index b80d057c68..9bf8f9ff53 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/SignedTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/SignedTransaction.kt @@ -110,11 +110,13 @@ data class SignedTransaction(val txBits: SerializedBytes, /** Returns the same transaction but with an additional (unchecked) signature. */ fun withAdditionalSignature(sig: DigitalSignature.WithKey) = copy(sigs = sigs + sig) + /** Returns the same transaction but with an additional (unchecked) signatures. */ fun withAdditionalSignatures(sigList: Iterable) = copy(sigs = sigs + sigList) /** Alias for [withAdditionalSignature] to let you use Kotlin operator overloading. */ operator fun plus(sig: DigitalSignature.WithKey) = withAdditionalSignature(sig) + /** Alias for [withAdditionalSignatures] to let you use Kotlin operator overloading. */ operator fun plus(sigList: Collection) = withAdditionalSignatures(sigList) diff --git a/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt b/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt index 66124dd228..76accc297a 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt @@ -63,8 +63,7 @@ open class TransactionBuilder( * collaborating parties may therefore require a higher time tolerance than a transaction being built by a single * node. */ - fun setTime(time: Instant, timeTolerance: Duration) - = setTime(Timestamp(time, timeTolerance)) + fun setTime(time: Instant, timeTolerance: Duration) = setTime(Timestamp(time, timeTolerance)) fun setTime(newTimestamp: Timestamp) { check(notary != null) { "Only notarised transactions can have a timestamp" } diff --git a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt index 548883b9b4..eb67965b46 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt @@ -34,7 +34,9 @@ class WireTransaction( type: TransactionType, timestamp: Timestamp? ) : BaseTransaction(inputs, outputs, notary, signers, type, timestamp) { - init { checkInvariants() } + init { + checkInvariants() + } // Cache the serialised form of the transaction and its hash to give us fast access to it. @Volatile @Transient private var cachedBytes: SerializedBytes? = null diff --git a/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt index e8fbdc4e05..7a0083a537 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt @@ -19,7 +19,7 @@ class ApiUtils(val services: ServiceHub) { return try { val partyKey = CompositeKey.parseFromBase58(partyKeyStr) val party = services.identityService.partyFromKey(partyKey) - if(party == null) notFound("Unknown party") else found(party) + if (party == null) notFound("Unknown party") else found(party) } catch (e: IllegalArgumentException) { notFound("Invalid base58 key passed for party key") } diff --git a/core/src/main/kotlin/net/corda/core/utilities/Logging.kt b/core/src/main/kotlin/net/corda/core/utilities/Logging.kt index c718db410e..b126728e6b 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/Logging.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/Logging.kt @@ -13,8 +13,13 @@ import kotlin.reflect.KClass // logging at that level is enabled. inline fun loggerFor(): org.slf4j.Logger = LoggerFactory.getLogger(T::class.java) -inline fun org.slf4j.Logger.trace(msg: () -> String) { if (isTraceEnabled) trace(msg()) } -inline fun org.slf4j.Logger.debug(msg: () -> String) { if (isDebugEnabled) debug(msg()) } +inline fun org.slf4j.Logger.trace(msg: () -> String) { + if (isTraceEnabled) trace(msg()) +} + +inline fun org.slf4j.Logger.debug(msg: () -> String) { + if (isDebugEnabled) debug(msg()) +} /** A configuration helper that allows modifying the log level for specific loggers */ object LogHelper { diff --git a/core/src/main/kotlin/net/corda/core/utilities/NonEmptySet.kt b/core/src/main/kotlin/net/corda/core/utilities/NonEmptySet.kt index 1146619617..13920ba788 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/NonEmptySet.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/NonEmptySet.kt @@ -109,7 +109,9 @@ object NonEmptySetSerializer : Serializer>() { // Read the first item and use it to construct the NonEmptySet val set = NonEmptySet(first) // Read in the rest of the set - for (i in 2..size) { set.add(kryo.readClassAndObject(input)) } + for (i in 2..size) { + set.add(kryo.readClassAndObject(input)) + } return set } } diff --git a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt index a67173f93c..55b344c485 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt @@ -80,7 +80,9 @@ class ProgressTracker(vararg steps: Step) { // This field won't be serialized. private val _changes by TransientProperty { PublishSubject.create() } + private data class Child(val tracker: ProgressTracker, @Transient val subscription: Subscription?) + private val childProgressTrackers = HashMap() init { @@ -151,8 +153,8 @@ 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' */ + @Suppress("unused") // TODO: Review by EOY2016 if this property is useful anywhere. val topLevelTracker: ProgressTracker get() { var cursor: ProgressTracker = this diff --git a/core/src/main/kotlin/net/corda/core/utilities/TestConstants.kt b/core/src/main/kotlin/net/corda/core/utilities/TestConstants.kt index 3581829ef7..ae281e0554 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/TestConstants.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/TestConstants.kt @@ -1,4 +1,5 @@ @file:JvmName("TestConstants") + package net.corda.core.utilities import net.corda.core.crypto.* diff --git a/core/src/main/kotlin/net/corda/flows/AbstractStateReplacementFlow.kt b/core/src/main/kotlin/net/corda/flows/AbstractStateReplacementFlow.kt index 7d9e1acae2..8e749b9903 100644 --- a/core/src/main/kotlin/net/corda/flows/AbstractStateReplacementFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/AbstractStateReplacementFlow.kt @@ -215,7 +215,7 @@ abstract class AbstractStateReplacementFlow { /** Thrown when a participant refuses the proposed state replacement */ class StateReplacementRefused(val identity: Party, val state: StateRef, val detail: String?) { - override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided") + 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") +class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error") diff --git a/core/src/main/kotlin/net/corda/flows/NotaryChangeFlow.kt b/core/src/main/kotlin/net/corda/flows/NotaryChangeFlow.kt index 89fe318cf8..2bc8f9fd33 100644 --- a/core/src/main/kotlin/net/corda/flows/NotaryChangeFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/NotaryChangeFlow.kt @@ -34,7 +34,7 @@ object NotaryChangeFlow : AbstractStateReplacementFlow() { : AbstractStateReplacementFlow.Instigator(originalState, newNotary, progressTracker) { override fun assembleProposal(stateRef: StateRef, modification: Party, stx: SignedTransaction): AbstractStateReplacementFlow.Proposal - = Proposal(stateRef, modification, stx) + = Proposal(stateRef, modification, stx) override fun assembleTx(): Pair> { val state = originalState.state diff --git a/core/src/main/kotlin/net/corda/flows/NotaryFlow.kt b/core/src/main/kotlin/net/corda/flows/NotaryFlow.kt index 30e9f868ba..81315a7164 100644 --- a/core/src/main/kotlin/net/corda/flows/NotaryFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/NotaryFlow.kt @@ -150,7 +150,7 @@ object NotaryFlow { data class SignRequest(val tx: SignedTransaction, val callerIdentity: Party) sealed class Result { - class Error(val error: NotaryError): Result() + class Error(val error: NotaryError) : Result() class Success(val sig: DigitalSignature.WithKey) : Result() } diff --git a/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt b/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt index 290e677588..07defc2ce5 100644 --- a/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt @@ -275,7 +275,7 @@ object TwoPartyDealFlow { override val progressTracker: ProgressTracker = Primary.tracker()) : Primary() { override val notaryNode: NodeInfo get() = - serviceHub.networkMapCache.notaryNodes.filter { it.notaryIdentity == payload.notary }.single() + serviceHub.networkMapCache.notaryNodes.filter { it.notaryIdentity == payload.notary }.single() } /** diff --git a/core/src/test/java/net/corda/core/flows/FlowLogicRefFromJavaTest.java b/core/src/test/java/net/corda/core/flows/FlowLogicRefFromJavaTest.java index 95ac1e92ce..f9c43dfb09 100644 --- a/core/src/test/java/net/corda/core/flows/FlowLogicRefFromJavaTest.java +++ b/core/src/test/java/net/corda/core/flows/FlowLogicRefFromJavaTest.java @@ -1,11 +1,8 @@ package net.corda.core.flows; -import org.junit.Test; +import org.junit.*; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; public class FlowLogicRefFromJavaTest { diff --git a/core/src/test/kotlin/net/corda/core/contracts/TransactionGraphSearchTests.kt b/core/src/test/kotlin/net/corda/core/contracts/TransactionGraphSearchTests.kt index 88f282f07d..2ac1841a62 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/TransactionGraphSearchTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/TransactionGraphSearchTests.kt @@ -13,7 +13,7 @@ import java.security.KeyPair import kotlin.test.assertEquals class TransactionGraphSearchTests { - class GraphTransactionStorage(val originTx: SignedTransaction, val inputTx: SignedTransaction): MockTransactionStorage() { + class GraphTransactionStorage(val originTx: SignedTransaction, val inputTx: SignedTransaction) : MockTransactionStorage() { init { addTransaction(originTx) addTransaction(inputTx) diff --git a/core/src/test/kotlin/net/corda/core/contracts/clauses/AnyCompositionTests.kt b/core/src/test/kotlin/net/corda/core/contracts/clauses/AnyCompositionTests.kt index 13f3870809..1d58b7e85e 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/clauses/AnyCompositionTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/clauses/AnyCompositionTests.kt @@ -2,13 +2,11 @@ package net.corda.core.contracts.clauses import net.corda.core.contracts.AuthenticatedObject import net.corda.core.contracts.CommandData -import net.corda.core.contracts.ContractState import net.corda.core.contracts.TransactionForContract import net.corda.core.crypto.SecureHash import org.junit.Test import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertEquals -import kotlin.test.assertFailsWith class AnyCompositionTests { @Test diff --git a/core/src/test/kotlin/net/corda/core/contracts/clauses/ClauseTestUtils.kt b/core/src/test/kotlin/net/corda/core/contracts/clauses/ClauseTestUtils.kt index 2bd87c1907..9d023670ae 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/clauses/ClauseTestUtils.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/clauses/ClauseTestUtils.kt @@ -18,7 +18,7 @@ internal fun matchedClause(counter: AtomicInteger? = null) = object : Clause() { - override val requiredCommands: Set> = setOf(object: CommandData {}.javaClass) + override val requiredCommands: Set> = setOf(object : CommandData {}.javaClass) override fun verify(tx: TransactionForContract, inputs: List, outputs: List, diff --git a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt index 919b37d265..53ac8e0f33 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt @@ -1,15 +1,17 @@ package net.corda.core.crypto + import com.esotericsoftware.kryo.serializers.MapSerializer -import net.corda.contracts.asset.* +import net.corda.contracts.asset.Cash import net.corda.core.contracts.DOLLARS import net.corda.core.contracts.`issued by` import net.corda.core.serialization.* import net.corda.core.transactions.* import net.corda.core.utilities.DUMMY_PUBKEY_1 -import net.corda.testing.* - - +import net.corda.testing.ALICE_PUBKEY +import net.corda.testing.MEGA_CORP +import net.corda.testing.MEGA_CORP_PUBKEY +import net.corda.testing.ledger import org.junit.Test import java.util.* import kotlin.test.assertEquals @@ -114,7 +116,7 @@ class PartialMerkleTreeTest { val leaves = "aaa" val hashes = leaves.map { it.serialize().hash } val mt = MerkleTree.getMerkleTree(hashes) - assertFailsWith { PartialMerkleTree.build(mt, hashes.subList(0,1)) } + assertFailsWith { PartialMerkleTree.build(mt, hashes.subList(0, 1)) } } @Test @@ -135,7 +137,7 @@ class PartialMerkleTreeTest { @Test fun `verify Partial Merkle Tree - duplicate leaves failure`() { - val mt = MerkleTree.getMerkleTree(hashed.subList(0,5)) //Odd number of leaves. Last one is duplicated. + val mt = MerkleTree.getMerkleTree(hashed.subList(0, 5)) //Odd number of leaves. Last one is duplicated. val inclHashes = arrayListOf(hashed[3], hashed[4]) val pmt = PartialMerkleTree.build(mt, inclHashes) inclHashes.add(hashed[4]) @@ -158,7 +160,7 @@ class PartialMerkleTreeTest { } @Test - fun `hash map serialization`(){ + fun `hash map serialization`() { val hm1 = hashMapOf("a" to 1, "b" to 2, "c" to 3, "e" to 4) assert(serializedHash(hm1) == serializedHash(hm1.serialize().deserialize())) //It internally uses the ordered HashMap extension. val kryo = extendKryoHash(createKryo()) diff --git a/core/src/test/kotlin/net/corda/core/crypto/X509UtilitiesTest.kt b/core/src/test/kotlin/net/corda/core/crypto/X509UtilitiesTest.kt index 57e76502de..b91043446d 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/X509UtilitiesTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/X509UtilitiesTest.kt @@ -67,10 +67,10 @@ class X509UtilitiesTest { for (entry in serverCert.subjectAlternativeNames) { val typeId = entry[0] as Int val value = entry[1] as String - if(typeId == GeneralName.iPAddress) { + if (typeId == GeneralName.iPAddress) { assertEquals("10.0.0.54", value) - } else if(typeId == GeneralName.dNSName) { - if(value == "Server Cert") { + } else if (typeId == GeneralName.dNSName) { + if (value == "Server Cert") { foundMainDnsName = true } else if (value == "alias name") { foundAliasDnsName = true diff --git a/core/src/test/kotlin/net/corda/core/flows/FlowLogicRefTest.kt b/core/src/test/kotlin/net/corda/core/flows/FlowLogicRefTest.kt index 60bfd4880a..d96d878afc 100644 --- a/core/src/test/kotlin/net/corda/core/flows/FlowLogicRefTest.kt +++ b/core/src/test/kotlin/net/corda/core/flows/FlowLogicRefTest.kt @@ -10,7 +10,7 @@ class FlowLogicRefTest { data class ParamType1(val value: Int) data class ParamType2(val value: String) - @Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection. + @Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection. class KotlinFlowLogic(A: ParamType1, b: ParamType2) : FlowLogic() { constructor() : this(ParamType1(1), ParamType2("2")) diff --git a/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt b/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt index e96aaa4dd5..38f6f54a82 100644 --- a/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt +++ b/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt @@ -95,7 +95,7 @@ class AttachmentClassLoaderTests { return bs.toByteArray() } - fun readAttachment(attachment: Attachment, filepath: String) : ByteArray { + fun readAttachment(attachment: Attachment, filepath: String): ByteArray { ByteArrayOutputStream().use { attachment.extractFile(filepath, it) return it.toByteArray() diff --git a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt index 593690a8ce..08987a2992 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt @@ -35,6 +35,7 @@ class TransactionSerializationTests { override fun withNewOwner(newOwner: CompositeKey) = Pair(Commands.Move(), copy(owner = newOwner)) } + interface Commands : CommandData { class Move() : TypeOnlyCommandData(), Commands } diff --git a/core/src/test/kotlin/net/corda/core/utilities/ProgressTrackerTest.kt b/core/src/test/kotlin/net/corda/core/utilities/ProgressTrackerTest.kt index 440c2c8404..ebe7d3e872 100644 --- a/core/src/test/kotlin/net/corda/core/utilities/ProgressTrackerTest.kt +++ b/core/src/test/kotlin/net/corda/core/utilities/ProgressTrackerTest.kt @@ -21,6 +21,7 @@ class ProgressTrackerTest { fun tracker() = ProgressTracker(ONE, TWO, THREE, FOUR) } + object ChildSteps { object AYY : ProgressTracker.Step("ayy") object BEE : ProgressTracker.Step("bee") @@ -104,6 +105,7 @@ class ProgressTrackerTest { println("bar") } } + val kryo = createKryo().apply { // This is required to make sure Kryo walks through the auto-generated members for the lambda below. fieldSerializerConfig.isIgnoreSyntheticFields = false @@ -111,6 +113,7 @@ class ProgressTrackerTest { pt.setChildProgressTracker(SimpleSteps.TWO, pt2) class Tmp { val unserializable = Unserializable() + init { pt2.changes.subscribe { unserializable.foo() } } diff --git a/finance/src/main/java/net/corda/contracts/ICommercialPaperState.java b/finance/src/main/java/net/corda/contracts/ICommercialPaperState.java index 51ecb33851..d3697d1628 100644 --- a/finance/src/main/java/net/corda/contracts/ICommercialPaperState.java +++ b/finance/src/main/java/net/corda/contracts/ICommercialPaperState.java @@ -1,13 +1,10 @@ package net.corda.contracts; -import net.corda.core.contracts.Amount; -import net.corda.core.contracts.ContractState; -import net.corda.core.contracts.Issued; -import net.corda.core.contracts.PartyAndReference; -import net.corda.core.crypto.CompositeKey; +import net.corda.core.contracts.*; +import net.corda.core.crypto.*; -import java.time.Instant; -import java.util.Currency; +import java.time.*; +import java.util.*; /* This is an interface solely created to demonstrate that the same kotlin tests can be run against * either a Java implementation of the CommercialPaper or a kotlin implementation. diff --git a/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java b/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java index 28c727bb0a..7159eadcd9 100644 --- a/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java +++ b/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java @@ -1,34 +1,22 @@ package net.corda.contracts; -import com.google.common.collect.ImmutableList; -import kotlin.Pair; -import kotlin.Unit; -import net.corda.contracts.asset.CashKt; +import com.google.common.collect.*; +import kotlin.*; +import net.corda.contracts.asset.*; import net.corda.core.contracts.*; -import net.corda.core.contracts.TransactionForContract.InOutGroup; -import net.corda.core.contracts.clauses.AnyComposition; -import net.corda.core.contracts.clauses.Clause; -import net.corda.core.contracts.clauses.ClauseVerifier; -import net.corda.core.contracts.clauses.GroupClauseVerifier; -import net.corda.core.crypto.CompositeKey; -import net.corda.core.crypto.CryptoUtilitiesKt; -import net.corda.core.crypto.Party; -import net.corda.core.crypto.SecureHash; -import net.corda.core.node.services.VaultService; -import net.corda.core.transactions.TransactionBuilder; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import net.corda.core.contracts.TransactionForContract.*; +import net.corda.core.contracts.clauses.*; +import net.corda.core.crypto.*; +import net.corda.core.node.services.*; +import net.corda.core.transactions.*; +import org.jetbrains.annotations.*; -import java.time.Instant; -import java.util.Collections; -import java.util.Currency; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +import java.time.*; +import java.util.*; +import java.util.stream.*; -import static kotlin.collections.CollectionsKt.single; -import static net.corda.core.contracts.ContractsDSL.requireSingleCommand; -import static net.corda.core.contracts.ContractsDSL.requireThat; +import static kotlin.collections.CollectionsKt.*; +import static net.corda.core.contracts.ContractsDSL.*; /** @@ -173,10 +161,10 @@ public class JavaCommercialPaper implements Contract { @NotNull @Override public Set verify(@NotNull TransactionForContract tx, - @NotNull List inputs, - @NotNull List outputs, - @NotNull List> commands, - @NotNull State groupingKey) { + @NotNull List inputs, + @NotNull List outputs, + @NotNull List> commands, + @NotNull State groupingKey) { AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.Move.class); // There should be only a single input due to aggregation above State input = single(inputs); @@ -204,10 +192,10 @@ public class JavaCommercialPaper implements Contract { @NotNull @Override public Set verify(@NotNull TransactionForContract tx, - @NotNull List inputs, - @NotNull List outputs, - @NotNull List> commands, - @NotNull State groupingKey) { + @NotNull List inputs, + @NotNull List outputs, + @NotNull List> commands, + @NotNull State groupingKey) { AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.Redeem.class); // There should be only a single input due to aggregation above @@ -246,10 +234,10 @@ public class JavaCommercialPaper implements Contract { @NotNull @Override public Set verify(@NotNull TransactionForContract tx, - @NotNull List inputs, - @NotNull List outputs, - @NotNull List> commands, - @NotNull State groupingKey) { + @NotNull List inputs, + @NotNull List outputs, + @NotNull List> commands, + @NotNull State groupingKey) { AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.Issue.class); State output = single(outputs); Timestamp timestampCommand = tx.getTimestamp(); @@ -274,17 +262,23 @@ public class JavaCommercialPaper implements Contract { public interface Commands extends CommandData { class Move implements Commands { @Override - public boolean equals(Object obj) { return obj instanceof Move; } + public boolean equals(Object obj) { + return obj instanceof Move; + } } class Redeem implements Commands { @Override - public boolean equals(Object obj) { return obj instanceof Redeem; } + public boolean equals(Object obj) { + return obj instanceof Redeem; + } } class Issue implements Commands { @Override - public boolean equals(Object obj) { return obj instanceof Issue; } + public boolean equals(Object obj) { + return obj instanceof Issue; + } } } diff --git a/finance/src/main/kotlin/net/corda/contracts/CommercialPaper.kt b/finance/src/main/kotlin/net/corda/contracts/CommercialPaper.kt index daaa7d0c5e..63582620af 100644 --- a/finance/src/main/kotlin/net/corda/contracts/CommercialPaper.kt +++ b/finance/src/main/kotlin/net/corda/contracts/CommercialPaper.kt @@ -51,8 +51,8 @@ class CommercialPaper : Contract { override val legalContractReference: SecureHash = SecureHash.sha256("https://en.wikipedia.org/wiki/Commercial_paper") data class Terms( - val asset: Issued, - val maturityDate: Instant + val asset: Issued, + val maturityDate: Instant ) override fun verify(tx: TransactionForContract) = verifyClause(tx, Clauses.Group(), tx.commands.select()) @@ -103,10 +103,10 @@ class CommercialPaper : Contract { interface Clauses { class Group : GroupClauseVerifier>( - AnyComposition( - Redeem(), - Move(), - Issue())) { + AnyComposition( + Redeem(), + Move(), + Issue())) { override fun groupStates(tx: TransactionForContract): List>> = tx.groupStates> { it.token } } @@ -132,7 +132,7 @@ class CommercialPaper : Contract { } } - class Move: Clause>() { + class Move : Clause>() { override val requiredCommands: Set> = setOf(Commands.Move::class.java) override fun verify(tx: TransactionForContract, @@ -152,7 +152,7 @@ class CommercialPaper : Contract { } } - class Redeem(): Clause>() { + class Redeem() : Clause>() { override val requiredCommands: Set> = setOf(Commands.Redeem::class.java) override fun verify(tx: TransactionForContract, diff --git a/finance/src/main/kotlin/net/corda/contracts/asset/Cash.kt b/finance/src/main/kotlin/net/corda/contracts/asset/Cash.kt index 457bff1962..83e8e94add 100644 --- a/finance/src/main/kotlin/net/corda/contracts/asset/Cash.kt +++ b/finance/src/main/kotlin/net/corda/contracts/asset/Cash.kt @@ -86,7 +86,7 @@ class Cash : OnLedgerAsset() { override val encumbrance: Int? = null ) : FungibleAsset, QueryableState { constructor(deposit: PartyAndReference, amount: Amount, owner: CompositeKey) - : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) + : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) override val exitKeys = setOf(owner, amount.token.issuer.party.owningKey) override val contract = CASH_PROGRAM_ID @@ -160,13 +160,14 @@ class Cash : OnLedgerAsset() { } override fun deriveState(txState: TransactionState, amount: Amount>, owner: CompositeKey) - = txState.copy(data = txState.data.copy(amount = amount, owner = owner)) + = txState.copy(data = txState.data.copy(amount = amount, owner = owner)) + override fun generateExitCommand(amount: Amount>) = Commands.Exit(amount) override fun generateIssueCommand() = Commands.Issue() override fun generateMoveCommand() = Commands.Move() override fun verify(tx: TransactionForContract) - = verifyClause(tx, Clauses.Group(), extractCommands(tx.commands)) + = verifyClause(tx, Clauses.Group(), extractCommands(tx.commands)) } // Small DSL extensions. diff --git a/finance/src/main/kotlin/net/corda/contracts/asset/CommodityContract.kt b/finance/src/main/kotlin/net/corda/contracts/asset/CommodityContract.kt index 7191aadde8..4c4af24ef3 100644 --- a/finance/src/main/kotlin/net/corda/contracts/asset/CommodityContract.kt +++ b/finance/src/main/kotlin/net/corda/contracts/asset/CommodityContract.kt @@ -21,7 +21,6 @@ import java.util.* // Just a fake program identifier for now. In a real system it could be, for instance, the hash of the program bytecode. val COMMODITY_PROGRAM_ID = CommodityContract() - //SecureHash.sha256("commodity") /** * A commodity contract represents an amount of some commodity, tracked on a distributed ledger. The design of this @@ -98,14 +97,14 @@ class CommodityContract : OnLedgerAsset { constructor(deposit: PartyAndReference, amount: Amount, owner: CompositeKey) - : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) + : this(Amount(amount.quantity, Issued(deposit, amount.token)), owner) override val contract = COMMODITY_PROGRAM_ID override val exitKeys = Collections.singleton(owner) override val participants = listOf(owner) override fun move(newAmount: Amount>, newOwner: CompositeKey): FungibleAsset - = copy(amount = amount.copy(newAmount.quantity, amount.token), owner = newOwner) + = copy(amount = amount.copy(newAmount.quantity, amount.token), owner = newOwner) override fun toString() = "Commodity($amount at ${amount.token.issuer} owned by $owner)" @@ -135,8 +134,10 @@ class CommodityContract : OnLedgerAsset>) : Commands, FungibleAsset.Commands.Exit } + override fun verify(tx: TransactionForContract) = verifyClause(tx, Clauses.Group(), extractCommands(tx.commands)) + override fun extractCommands(commands: Collection>): List> = commands.select() @@ -160,6 +161,7 @@ class CommodityContract : OnLedgerAsset, amount: Amount>, owner: CompositeKey) = txState.copy(data = txState.data.copy(amount = amount, owner = owner)) + override fun generateExitCommand(amount: Amount>) = Commands.Exit(amount) override fun generateIssueCommand() = Commands.Issue() override fun generateMoveCommand() = Commands.Move() diff --git a/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt b/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt index 5d60833ffb..08d72b0143 100644 --- a/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt +++ b/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt @@ -81,7 +81,7 @@ class Obligation

: Contract { /** * Clause for supporting netting of obligations. */ - class Net : NetClause() { + class Net : NetClause() { val lifecycleClause = Clauses.VerifyLifecycle() override fun toString(): String = "Net obligations" @@ -203,15 +203,16 @@ class Obligation

: Contract { * any lifecycle change clause, which is the only clause that involve * non-standard lifecycle states on input/output. */ - class VerifyLifecycle : Clause() { + class VerifyLifecycle : Clause() { override fun verify(tx: TransactionForContract, inputs: List, outputs: List, commands: List>, groupingKey: T?): Set - = verify(inputs.filterIsInstance>(), outputs.filterIsInstance>()) + = verify(inputs.filterIsInstance>(), outputs.filterIsInstance>()) + private fun verify(inputs: List>, - outputs: List>): Set { + outputs: List>): Set { requireThat { "all inputs are in the normal state " by inputs.all { it.lifecycle == Lifecycle.NORMAL } "all outputs are in the normal state " by outputs.all { it.lifecycle == Lifecycle.NORMAL } @@ -373,9 +374,9 @@ class Obligation

: Contract { */ @VisibleForTesting private fun verifySetLifecycleCommand(inputs: List>>, - outputs: List>>, - tx: TransactionForContract, - setLifecycleCommand: AuthenticatedObject) { + outputs: List>>, + tx: TransactionForContract, + setLifecycleCommand: AuthenticatedObject) { // Default must not change anything except lifecycle, so number of inputs and outputs must match // exactly. require(inputs.size == outputs.size) { "Number of inputs and outputs must match" } @@ -704,6 +705,7 @@ infix fun Obligation.State.`owned by`(owner: CompositeKey) = copy(benefic infix fun Obligation.State.`issued by`(party: Party) = copy(obligor = party) // For Java users: @Suppress("unused") fun Obligation.State.ownedBy(owner: CompositeKey) = copy(beneficiary = owner) + @Suppress("unused") fun Obligation.State.issuedBy(party: Party) = copy(obligor = party) /** A randomly generated key. */ diff --git a/finance/src/main/kotlin/net/corda/contracts/asset/OnLedgerAsset.kt b/finance/src/main/kotlin/net/corda/contracts/asset/OnLedgerAsset.kt index e9320ea194..ad0637fb8c 100644 --- a/finance/src/main/kotlin/net/corda/contracts/asset/OnLedgerAsset.kt +++ b/finance/src/main/kotlin/net/corda/contracts/asset/OnLedgerAsset.kt @@ -23,7 +23,7 @@ import net.corda.core.transactions.TransactionBuilder * At the same time, other contracts that just want assets and don't care much who is currently holding it can ignore * the issuer/depositRefs and just examine the amount fields. */ -abstract class OnLedgerAsset> : Contract { +abstract class OnLedgerAsset> : Contract { abstract fun extractCommands(commands: Collection>): Collection> abstract val conserveClause: AbstractConserveAmount @@ -40,7 +40,7 @@ abstract class OnLedgerAsset> : Co */ fun generateExit(tx: TransactionBuilder, amountIssued: Amount>, assetStates: List>): CompositeKey - = conserveClause.generateExit(tx, amountIssued, assetStates, + = conserveClause.generateExit(tx, amountIssued, assetStates, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, generateMoveCommand = { -> generateMoveCommand() }, generateExitCommand = { amount -> generateExitCommand(amount) } diff --git a/finance/src/main/kotlin/net/corda/contracts/clause/AbstractIssue.kt b/finance/src/main/kotlin/net/corda/contracts/clause/AbstractIssue.kt index 14fdf22dbb..f9db0ce330 100644 --- a/finance/src/main/kotlin/net/corda/contracts/clause/AbstractIssue.kt +++ b/finance/src/main/kotlin/net/corda/contracts/clause/AbstractIssue.kt @@ -13,7 +13,7 @@ import net.corda.core.contracts.clauses.Clause * @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> ) : Clause>() { diff --git a/finance/src/main/kotlin/net/corda/contracts/clause/Net.kt b/finance/src/main/kotlin/net/corda/contracts/clause/Net.kt index e878d0d7df..629edf7123 100644 --- a/finance/src/main/kotlin/net/corda/contracts/clause/Net.kt +++ b/finance/src/main/kotlin/net/corda/contracts/clause/Net.kt @@ -42,7 +42,7 @@ data class MultilateralNetState

( * Clause for netting contract states. Currently only supports obligation contract. */ // TODO: Make this usable for any nettable contract states -open class NetClause : Clause() { +open class NetClause : Clause() { override val requiredCommands: Set> = setOf(Obligation.Commands.Net::class.java) @Suppress("ConvertLambdaToReference") diff --git a/finance/src/main/kotlin/net/corda/contracts/clause/NoZeroSizedOutputs.kt b/finance/src/main/kotlin/net/corda/contracts/clause/NoZeroSizedOutputs.kt index d377422cfd..027253e594 100644 --- a/finance/src/main/kotlin/net/corda/contracts/clause/NoZeroSizedOutputs.kt +++ b/finance/src/main/kotlin/net/corda/contracts/clause/NoZeroSizedOutputs.kt @@ -1,6 +1,5 @@ package net.corda.contracts.clause -import net.corda.core.contracts.FungibleAsset import net.corda.core.contracts.* import net.corda.core.contracts.clauses.Clause diff --git a/finance/src/main/kotlin/net/corda/contracts/testing/Generators.kt b/finance/src/main/kotlin/net/corda/contracts/testing/Generators.kt index 85b5038484..edc50cf43b 100644 --- a/finance/src/main/kotlin/net/corda/contracts/testing/Generators.kt +++ b/finance/src/main/kotlin/net/corda/contracts/testing/Generators.kt @@ -63,7 +63,7 @@ class CommandGenerator : Generator(Command::class.java) { } } -class WiredTransactionGenerator: Generator(WireTransaction::class.java) { +class WiredTransactionGenerator : Generator(WireTransaction::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): WireTransaction { val commands = CommandGenerator().generateList(random, status) + listOf(CommandGenerator().generate(random, status)) return WireTransaction( @@ -79,7 +79,7 @@ class WiredTransactionGenerator: Generator(WireTransaction::cla } } -class SignedTransactionGenerator: Generator(SignedTransaction::class.java) { +class SignedTransactionGenerator : Generator(SignedTransaction::class.java) { override fun generate(random: SourceOfRandomness, status: GenerationStatus): SignedTransaction { val wireTransaction = WiredTransactionGenerator().generate(random, status) return SignedTransaction( diff --git a/finance/src/main/kotlin/net/corda/contracts/testing/VaultFiller.kt b/finance/src/main/kotlin/net/corda/contracts/testing/VaultFiller.kt index 5c05b0e4a1..c8355d9b33 100644 --- a/finance/src/main/kotlin/net/corda/contracts/testing/VaultFiller.kt +++ b/finance/src/main/kotlin/net/corda/contracts/testing/VaultFiller.kt @@ -1,4 +1,5 @@ @file:JvmName("VaultFiller") + package net.corda.contracts.testing import net.corda.contracts.asset.Cash diff --git a/finance/src/test/java/net/corda/contracts/asset/CashTestsJava.java b/finance/src/test/java/net/corda/contracts/asset/CashTestsJava.java index 28484a6152..99e4cfd5d4 100644 --- a/finance/src/test/java/net/corda/contracts/asset/CashTestsJava.java +++ b/finance/src/test/java/net/corda/contracts/asset/CashTestsJava.java @@ -1,8 +1,8 @@ package net.corda.contracts.asset; +import kotlin.*; import net.corda.core.contracts.*; import net.corda.core.serialization.*; -import kotlin.*; import org.junit.*; import static net.corda.core.contracts.ContractsDSL.*; diff --git a/finance/src/test/kotlin/net/corda/contracts/asset/ObligationTests.kt b/finance/src/test/kotlin/net/corda/contracts/asset/ObligationTests.kt index 546d2d5b80..4e370a300b 100644 --- a/finance/src/test/kotlin/net/corda/contracts/asset/ObligationTests.kt +++ b/finance/src/test/kotlin/net/corda/contracts/asset/ObligationTests.kt @@ -665,6 +665,7 @@ class ObligationTests { } } + @Test fun `exit multiple product obligations`() { // Multi-product case. diff --git a/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt b/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt index 7e1d900852..348e62d59b 100644 --- a/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt +++ b/node/src/integration-test/kotlin/net/corda/node/utilities/JDBCHashMapTestSuite.kt @@ -1,7 +1,7 @@ package net.corda.node.utilities -import net.corda.testing.node.makeTestDataSourceProperties import junit.framework.TestSuite +import net.corda.testing.node.makeTestDataSourceProperties import org.assertj.core.api.Assertions.assertThat import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Transaction @@ -136,7 +136,7 @@ class JDBCHashMapTestSuite { */ class JDBCHashMapTestGenerator(val loadOnInit: Boolean, val constrained: Boolean) : com.google.common.collect.testing.TestStringMapGenerator() { override fun create(elements: Array>): Map { - val map = if (loadOnInit) loadOnInitTrueMap else if(constrained) memoryConstrainedMap else loadOnInitFalseMap + val map = if (loadOnInit) loadOnInitTrueMap else if (constrained) memoryConstrainedMap else loadOnInitFalseMap map.clear() map.putAll(elements.associate { Pair(it.key, it.value) }) return map @@ -178,7 +178,7 @@ class JDBCHashMapTestSuite { */ class JDBCHashSetTestGenerator(val loadOnInit: Boolean, val constrained: Boolean) : com.google.common.collect.testing.TestStringSetGenerator() { override fun create(elements: Array): Set { - val set = if (loadOnInit) loadOnInitTrueSet else if(constrained) memoryConstrainedSet else loadOnInitFalseSet + val set = if (loadOnInit) loadOnInitTrueSet else if (constrained) memoryConstrainedSet else loadOnInitFalseSet set.clear() set.addAll(elements) return set diff --git a/node/src/main/java/CordaCaplet.java b/node/src/main/java/CordaCaplet.java index 6c4fa92b5b..fc20bcc1e6 100644 --- a/node/src/main/java/CordaCaplet.java +++ b/node/src/main/java/CordaCaplet.java @@ -2,12 +2,9 @@ // must also be in the default package. When using Kotlin there are a whole host of exceptions // trying to construct this from Capsule, so it is written in Java. -import org.apache.commons.io.FilenameUtils; - -import java.io.File; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; +import java.io.*; +import java.nio.file.*; +import java.util.*; public class CordaCaplet extends Capsule { @@ -23,7 +20,7 @@ public class CordaCaplet extends Capsule { protected T attribute(Map.Entry attr) { // Equality is used here because Capsule never instantiates these attributes but instead reuses the ones // defined as public static final fields on the Capsule class, therefore referential equality is safe. - if(ATTR_APP_CLASS_PATH == attr) { + if (ATTR_APP_CLASS_PATH == attr) { T cp = super.attribute(attr); List classpath = augmentClasspath((List) cp, "plugins"); return (T) augmentClasspath(classpath, "dependencies"); @@ -35,7 +32,7 @@ public class CordaCaplet extends Capsule { // TODO: Add working directory variable to capsules string replacement variables. private List augmentClasspath(List classpath, String dirName) { File dir = new File(dirName); - if(!dir.exists()) { + if (!dir.exists()) { dir.mkdir(); } diff --git a/node/src/main/kotlin/net/corda/node/driver/Driver.kt b/node/src/main/kotlin/net/corda/node/driver/Driver.kt index 72547e36bd..d816227be3 100644 --- a/node/src/main/kotlin/net/corda/node/driver/Driver.kt +++ b/node/src/main/kotlin/net/corda/node/driver/Driver.kt @@ -95,7 +95,8 @@ sealed class PortAllocation { val portCounter = AtomicInteger(startingPort) override fun nextPort() = portCounter.andIncrement } - class RandomFree(): PortAllocation() { + + class RandomFree() : PortAllocation() { override fun nextPort(): Int { return ServerSocket().use { it.bind(InetSocketAddress(0)) @@ -128,7 +129,7 @@ sealed class PortAllocation { * @param isDebug Indicates whether the spawned nodes should start in jdwt debug mode. * @param dsl The dsl itself. * @return The value returned in the [dsl] closure. - */ + */ fun driver( driverDirectory: Path = Paths.get("build", getTimestampAsDirectoryName()), portAllocation: PortAllocation = PortAllocation.Incremental(10000), @@ -233,6 +234,7 @@ open class DriverDSL( val clients = LinkedList() var localServer: ArtemisMessagingServer? = null } + private val state = ThreadBox(State()) //TODO: remove this once we can bundle quasar properly. @@ -394,6 +396,7 @@ open class DriverDSL( "Bob", "Bank" ) + fun pickA(array: Array): A = array[Math.abs(Random().nextInt()) % array.size] private fun startNode( @@ -409,7 +412,7 @@ open class DriverDSL( val classpath = System.getProperty("java.class.path") val path = System.getProperty("java.home") + separator + "bin" + separator + "java" - val debugPortArg = if(debugPort != null) + val debugPortArg = if (debugPort != null) listOf("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$debugPort") else emptyList() diff --git a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt index f9d863496d..933028ce7e 100644 --- a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt @@ -41,6 +41,7 @@ class CordaRPCOpsImpl( Pair(vault.states.toList(), updates) } } + override fun verifiedTransactions(): Pair, Observable> { return databaseTransaction(database) { services.storageService.validatedTransactions.track() @@ -67,7 +68,7 @@ class CordaRPCOpsImpl( override fun addVaultTransactionNote(txnId: SecureHash, txnNote: String) { return databaseTransaction(database) { - services.vaultService.addNoteToTransaction(txnId, txnNote) + services.vaultService.addNoteToTransaction(txnId, txnNote) } } diff --git a/node/src/main/kotlin/net/corda/node/services/api/CheckpointStorage.kt b/node/src/main/kotlin/net/corda/node/services/api/CheckpointStorage.kt index c4042ed82e..867e9d6c65 100644 --- a/node/src/main/kotlin/net/corda/node/services/api/CheckpointStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/api/CheckpointStorage.kt @@ -25,7 +25,7 @@ interface CheckpointStorage { * The checkpoints are only valid during the lifetime of a single call to the block, to allow memory management. * Return false from the block to terminate further iteration. */ - fun forEach(block: (Checkpoint)->Boolean) + fun forEach(block: (Checkpoint) -> Boolean) } diff --git a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt index 9c0f031011..fa399976f2 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt @@ -118,6 +118,7 @@ fun configureTestSSL(): NodeSSLConfiguration = object : NodeSSLConfiguration { override val certificatesPath = Files.createTempDirectory("certs") override val keyStorePassword: String get() = "cordacadevpass" override val trustStorePassword: String get() = "trustpass" + init { configureWithDevSSLCertificate() } diff --git a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt index 9d2ace3310..31dea8a679 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt @@ -53,14 +53,14 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration { val notaryNodeAddress: HostAndPort? by config.getOrElse { null } val notaryClusterAddresses: List = config.getListOrElse("notaryClusterAddresses") { emptyList() }.map { HostAndPort.fromString(it) } val rpcUsers: List = - config.getListOrElse("rpcUsers") { emptyList() } - .map { - val username = it.getString("user") - require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" } - val password = it.getString("password") - val permissions = it.getListOrElse("permissions") { emptyList() }.toSet() - User(username, password, permissions) - } + config.getListOrElse("rpcUsers") { emptyList() } + .map { + val username = it.getString("user") + require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" } + val password = it.getString("password") + val permissions = it.getListOrElse("permissions") { emptyList() }.toSet() + User(username, password, permissions) + } fun createNode(): Node { // This is a sanity feature do not remove. @@ -74,7 +74,7 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration { } if (networkMapAddress == null) advertisedServices.add(ServiceInfo(NetworkMapService.type)) val networkMapMessageAddress: SingleMessageRecipient? = if (networkMapAddress == null) null else NodeMessagingClient.makeNetworkMapAddress(networkMapAddress!!) - return Node(this, networkMapMessageAddress, advertisedServices, if(useTestClock == true) TestClock() else NodeClock()) + return Node(this, networkMapMessageAddress, advertisedServices, if (useTestClock == true) TestClock() else NodeClock()) } } diff --git a/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt b/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt index 9bc65d7d71..151d0c23d8 100644 --- a/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt +++ b/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt @@ -47,7 +47,7 @@ class NodeSchedulerService(private val database: Database, private val services: ServiceHubInternal, private val flowLogicRefFactory: FlowLogicRefFactory, private val schedulerTimerExecutor: Executor = Executors.newSingleThreadExecutor()) -: SchedulerService, SingletonSerializeAsToken() { + : SchedulerService, SingletonSerializeAsToken() { private val log = loggerFor() @@ -170,7 +170,7 @@ class NodeSchedulerService(private val database: Database, // Ensure we are still scheduled. val scheduledLogic: FlowLogic<*>? = getScheduledLogic() - if(scheduledLogic != null) { + if (scheduledLogic != null) { subFlow(scheduledLogic) } } diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingComponent.kt b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingComponent.kt index 2028583bba..c45b5c98c6 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingComponent.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingComponent.kt @@ -84,7 +84,7 @@ abstract class ArtemisMessagingComponent() : SingletonSerializeAsToken() { * For instance it may contain onion routing data. */ data class NodeAddress(val identity: CompositeKey, override val hostAndPort: HostAndPort) : SingleMessageRecipient, ArtemisAddress { - override val queueName: SimpleString by lazy { SimpleString(PEERS_PREFIX+identity.toBase58String()) } + override val queueName: SimpleString by lazy { SimpleString(PEERS_PREFIX + identity.toBase58String()) } override fun toString(): String = "${javaClass.simpleName}(identity = $queueName, $hostAndPort)" } @@ -117,10 +117,10 @@ abstract class ArtemisMessagingComponent() : SingletonSerializeAsToken() { */ fun checkStorePasswords() { config.keyStorePath.read { - KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray()) + KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray()) } config.trustStorePath.read { - KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray()) + KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray()) } } diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt index 5b0822ecef..dea10db946 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/NodeMessagingClient.kt @@ -104,13 +104,13 @@ class NodeMessagingClient(override val config: NodeConfiguration, } private val processedMessages: MutableSet = Collections.synchronizedSet( - object : AbstractJDBCHashSet(Table, loadOnInit = true) { - override fun elementFromRow(row: ResultRow): UUID = row[table.uuid] + object : AbstractJDBCHashSet(Table, loadOnInit = true) { + override fun elementFromRow(row: ResultRow): UUID = row[table.uuid] - override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) { - insert[table.uuid] = entry - } - }) + override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) { + insert[table.uuid] = entry + } + }) fun start(rpcOps: RPCOps, userService: RPCUserService) { state.locked { diff --git a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt index 6bf695a978..0f98f0894b 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt @@ -72,21 +72,25 @@ interface NetworkMapService { val ifChangedSinceVersion: Int?, override val replyTo: SingleMessageRecipient, override val sessionID: Long = random63BitValue()) : ServiceRequestMessage + data class FetchMapResponse(val nodes: Collection?, val version: Int) class QueryIdentityRequest(val identity: Party, override val replyTo: SingleMessageRecipient, override val sessionID: Long) : ServiceRequestMessage + data class QueryIdentityResponse(val node: NodeInfo?) class RegistrationRequest(val wireReg: WireNodeRegistration, override val replyTo: SingleMessageRecipient, override val sessionID: Long = random63BitValue()) : ServiceRequestMessage + data class RegistrationResponse(val success: Boolean) class SubscribeRequest(val subscribe: Boolean, override val replyTo: SingleMessageRecipient, override val sessionID: Long = random63BitValue()) : ServiceRequestMessage + data class SubscribeResponse(val confirmed: Boolean) data class Update(val wireReg: WireNodeRegistration, val mapVersion: Int, val replyTo: MessageRecipients) @@ -338,7 +342,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/net/corda/node/services/persistence/InMemoryStateMachineRecordedTransactionMappingStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/InMemoryStateMachineRecordedTransactionMappingStorage.kt index eccd071b1b..9199471cad 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/InMemoryStateMachineRecordedTransactionMappingStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/InMemoryStateMachineRecordedTransactionMappingStorage.kt @@ -3,9 +3,9 @@ package net.corda.node.services.persistence import net.corda.core.ThreadBox import net.corda.core.bufferUntilSubscribed import net.corda.core.crypto.SecureHash +import net.corda.core.flows.StateMachineRunId import net.corda.core.node.services.StateMachineRecordedTransactionMappingStorage import net.corda.core.node.services.StateMachineTransactionMapping -import net.corda.core.flows.StateMachineRunId import rx.Observable import rx.subjects.PublishSubject import java.util.* diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/StorageServiceImpl.kt b/node/src/main/kotlin/net/corda/node/services/persistence/StorageServiceImpl.kt index a481ef3c02..5e42cc8aec 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/StorageServiceImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/StorageServiceImpl.kt @@ -9,4 +9,4 @@ import net.corda.core.serialization.SingletonSerializeAsToken open class StorageServiceImpl(override val attachments: AttachmentStorage, override val validatedTransactions: TransactionStorage, override val stateMachineRecordedTransactionMapping: StateMachineRecordedTransactionMappingStorage) -: SingletonSerializeAsToken(), TxWritableStorageService + : SingletonSerializeAsToken(), TxWritableStorageService diff --git a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt index 3680f9ccc1..f8dd0d4599 100644 --- a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt +++ b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt @@ -1,5 +1,6 @@ package net.corda.node.services.schema +import kotlinx.support.jdk7.use import net.corda.core.contracts.ContractState import net.corda.core.contracts.StateAndRef import net.corda.core.contracts.StateRef @@ -9,7 +10,6 @@ import net.corda.core.schemas.QueryableState import net.corda.core.utilities.debug import net.corda.core.utilities.loggerFor import net.corda.node.services.api.ServiceHubInternal -import kotlinx.support.jdk7.use import org.hibernate.SessionFactory import org.hibernate.boot.model.naming.Identifier import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt index 7260ef962a..90c2d060ea 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt @@ -442,7 +442,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, interface SessionMessage - interface ExistingSessionMessage: SessionMessage { + interface ExistingSessionMessage : SessionMessage { val recipientSessionId: Long } diff --git a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt index 460ebb8696..a03b65cbf7 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt @@ -74,7 +74,7 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT } // TODO: caching (2nd tier db cache) and db results filtering (max records, date, other) - fun select(txnId: SecureHash) : Iterable { + fun select(txnId: SecureHash): Iterable { return table.select { table.txnId.eq(txnId) }.map { row -> row[table.note] }.toSet().asIterable() } } diff --git a/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt b/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt index 15da561797..703773abe8 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/DatabaseSupport.kt @@ -139,6 +139,7 @@ class StrandLocalTransactionManager(initWithDatabase: Database) : TransactionMan // Composite columns for use with below Exposed helpers. data class PartyColumns(val name: Column, val owningKey: Column) + data class StateRefColumns(val txId: Column, val index: Column) data class TxnNoteColumns(val txId: Column, val note: Column) diff --git a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt index 8b5f961e3c..bdc6fa71a2 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt @@ -58,7 +58,7 @@ fun bytesToBlob(value: SerializedBytes<*>, finalizables: MutableList<() -> Unit> fun serializeToBlob(value: Any, finalizables: MutableList<() -> Unit>): Blob = bytesToBlob(value.serialize(), finalizables) -fun bytesFromBlob(blob: Blob): SerializedBytes { +fun bytesFromBlob(blob: Blob): SerializedBytes { try { return SerializedBytes(blob.getBytes(0, blob.length().toInt())) } finally { @@ -194,10 +194,10 @@ abstract class AbstractJDBCHashSet(protected v */ abstract class AbstractJDBCHashMap(val table: T, val loadOnInit: Boolean = false, - val maxBuckets: Int = 256) : MutableMap, AbstractMap() { + val maxBuckets: Int = 256) : MutableMap, AbstractMap() { companion object { - protected val log = loggerFor>() + protected val log = loggerFor>() private const val INITIAL_CAPACITY: Int = 16 private const val LOAD_FACTOR: Float = 0.75f diff --git a/node/src/main/kotlin/net/corda/node/utilities/JsonSupport.kt b/node/src/main/kotlin/net/corda/node/utilities/JsonSupport.kt index 0de2025cb0..d97d895907 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JsonSupport.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JsonSupport.kt @@ -164,10 +164,10 @@ object JsonSupport { } object PublicKeySerializer : JsonSerializer() { - override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) { - check(obj.params == ed25519Curve) - generator.writeString(obj.toBase58String()) - } + override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) { + check(obj.params == ed25519Curve) + generator.writeString(obj.toBase58String()) + } } object PublicKeyDeserializer : JsonDeserializer() { diff --git a/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigner.kt b/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigner.kt index 9fb4d2d1a9..a01bfca19d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigner.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigner.kt @@ -1,5 +1,6 @@ package net.corda.node.utilities.certsigning +import joptsimple.OptionParser import net.corda.core.* import net.corda.core.crypto.X509Utilities import net.corda.core.crypto.X509Utilities.CORDA_CLIENT_CA @@ -12,7 +13,6 @@ import net.corda.node.services.config.ConfigHelper import net.corda.node.services.config.FullNodeConfiguration import net.corda.node.services.config.NodeConfiguration import net.corda.node.services.config.getValue -import joptsimple.OptionParser import java.net.URL import java.nio.file.Paths import java.security.KeyPair @@ -107,7 +107,7 @@ class CertificateSigner(val config: NodeConfiguration, val certService: Certific requestIdStore.writeLines(listOf(requestId)) requestId } else { - requestIdStore.readLines { it.findFirst().get() } + requestIdStore.readLines { it.findFirst().get() } } } } diff --git a/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigningService.kt b/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigningService.kt index b1a68a57ed..2f6394714e 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigningService.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/certsigning/CertificateSigningService.kt @@ -6,6 +6,7 @@ import java.security.cert.Certificate interface CertificateSigningService { /** Submits a CSR to the signing service and returns an opaque request ID. */ fun submitRequest(request: PKCS10CertificationRequest): String + /** Poll Certificate Signing Server for the request and returns a chain of certificates if request has been approved, null otherwise. */ fun retrieveCertificates(requestId: String): Array? } diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index 7fbf19ef29..718f398c6c 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -58,7 +58,7 @@ class CordaRPCOpsImplTest { @Test fun `cash issue accepted`() { val quantity = 1000L - val ref = OpaqueBytes(ByteArray(1) {1}) + val ref = OpaqueBytes(ByteArray(1) { 1 }) // Check the monitoring service wallet is empty databaseTransaction(aliceNode.database) { diff --git a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeProtocolTests.kt b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeProtocolTests.kt index 61a811f133..2bb8723913 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeProtocolTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeProtocolTests.kt @@ -305,9 +305,9 @@ class TwoPartyTradeFlowTests { // Bob answers with the transactions that are now all verifiable, as Alice bottomed out. // Bob's transactions are valid, so she commits to the database expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[0].id]!!)), - expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify + expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[2].id]!!)), - expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify + expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[1].id]!!)), // Now she verifies the transaction is contract-valid (not signature valid) which means // looking up the states again. @@ -413,7 +413,7 @@ class TwoPartyTradeFlowTests { val sellerId: StateMachineRunId ) - private fun runBuyerAndSeller(assetToSell: StateAndRef) : RunResult { + private fun runBuyerAndSeller(assetToSell: StateAndRef): RunResult { val buyerFuture = bobNode.initiateSingleShotFlow(Seller::class) { otherParty -> Buyer(otherParty, notaryNode.info.notaryIdentity, 1000.DOLLARS, CommercialPaper.State::class.java) }.map { it.fsm } @@ -488,7 +488,7 @@ class TwoPartyTradeFlowTests { if (!withError) command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Issue() } else - // Put a broken command on so at least a signature is created + // Put a broken command on so at least a signature is created command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Move() } timestamp(TEST_TX_TIME) if (withError) { diff --git a/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapServiceTest.kt index 0e0ab1fe4c..be387b6131 100644 --- a/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/InMemoryNetworkMapServiceTest.kt @@ -63,7 +63,7 @@ abstract class AbstractNetworkMapServiceTest { assertEquals(1, service().nodes.count()) // Confirm that de-registering the node succeeds and drops it from the node lists - val removeChange = NodeRegistration(registerNode.info, instant.toEpochMilli()+1, AddOrRemove.REMOVE, expires) + val removeChange = NodeRegistration(registerNode.info, instant.toEpochMilli() + 1, AddOrRemove.REMOVE, expires) val removeWireChange = removeChange.toWire(nodeKey.private) assert(service().processRegistrationChangeRequest(RegistrationRequest(removeWireChange, mapServiceNode.info.address, Long.MIN_VALUE)).success) swizzle() @@ -92,7 +92,7 @@ abstract class AbstractNetworkMapServiceTest { val nodeKey = registerNode.services.legalIdentityKey val instant = Instant.now() val expires = instant + NetworkMapService.DEFAULT_EXPIRATION_PERIOD - val reg = NodeRegistration(registerNode.info, instant.toEpochMilli()+1, AddOrRemove.REMOVE, expires) + val reg = NodeRegistration(registerNode.info, instant.toEpochMilli() + 1, AddOrRemove.REMOVE, expires) val registerResult = registerNode.registration(mapServiceNode, reg, nodeKey.private) network.runNetwork() assertTrue(registerResult.getOrThrow().success) diff --git a/node/src/test/kotlin/net/corda/node/visualiser/GroupToGraphConversion.kt b/node/src/test/kotlin/net/corda/node/visualiser/GroupToGraphConversion.kt index 4918b710b1..046447c0f9 100644 --- a/node/src/test/kotlin/net/corda/node/visualiser/GroupToGraphConversion.kt +++ b/node/src/test/kotlin/net/corda/node/visualiser/GroupToGraphConversion.kt @@ -11,7 +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. +@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/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt index 9b502ca3a4..5deda0066a 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt @@ -1,9 +1,8 @@ package net.corda.attachmentdemo import com.google.common.net.HostAndPort -import net.corda.core.utilities.loggerFor -import net.corda.testing.http.HttpUtils import joptsimple.OptionParser +import net.corda.core.utilities.loggerFor import kotlin.system.exitProcess fun main(args: Array) { diff --git a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/plugin/AttachmentDemoPlugin.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/plugin/AttachmentDemoPlugin.kt index 4605eb3f1c..a5bfd72082 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/plugin/AttachmentDemoPlugin.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/plugin/AttachmentDemoPlugin.kt @@ -10,7 +10,7 @@ class AttachmentDemoPlugin : CordaPluginRegistry() { override val webApis: List> = listOf(AttachmentDemoApi::class.java) // A list of flows that are required for this cordapp override val requiredFlows: Map> = mapOf( - FinalityFlow::class.java.name to setOf(SignedTransaction::class.java.name, setOf(Unit).javaClass.name, setOf(Unit).javaClass.name) + FinalityFlow::class.java.name to setOf(SignedTransaction::class.java.name, setOf(Unit).javaClass.name, setOf(Unit).javaClass.name) ) override val servicePlugins: List> = listOf() } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/IRSDemo.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/IRSDemo.kt index 9ee1b39ec3..35b185838d 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/IRSDemo.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/IRSDemo.kt @@ -1,4 +1,5 @@ @file:JvmName("IRSDemo") + package net.corda.irs import com.google.common.net.HostAndPort diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/Main.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/Main.kt index fa3f7efb70..4e2589e7fb 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/Main.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/Main.kt @@ -1,11 +1,9 @@ package net.corda.irs +import net.corda.core.node.services.ServiceInfo +import net.corda.irs.api.NodeInterestRates import net.corda.node.driver.driver import net.corda.node.services.transactions.SimpleNotaryService -import net.corda.core.node.services.ServiceInfo -import net.corda.irs.api.IRSDemoClientApi -import net.corda.irs.api.NodeInterestRates -import net.corda.testing.getHostAndPort /** * This file is exclusively for being able to run your nodes through an IDE (as opposed to running deployNodes) diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt index e7dbbb3498..077def22e4 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt @@ -145,6 +145,7 @@ object NodeInterestRates { } var container: FixContainer = FixContainer(fixes) } + private val mutex = FiberBox(InnerState()) var knownFixes: FixContainer @@ -187,7 +188,7 @@ object NodeInterestRates { // It will be fixed by adding partial signatures later. // DOCSTART 1 fun sign(ftx: FilteredTransaction, merkleRoot: SecureHash): DigitalSignature.LegallyIdentifiable { - if (!ftx.verify(merkleRoot)){ + if (!ftx.verify(merkleRoot)) { throw MerkleTreeException("Rate Fix Oracle: Couldn't verify partial Merkle tree.") } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRS.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRS.kt index 3e51db166a..7e0d87356a 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRS.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRS.kt @@ -505,8 +505,8 @@ class InterestRateSwap() : Contract { class Group : GroupClauseVerifier(AnyComposition(Agree(), Fix(), Pay(), Mature())) { override fun groupStates(tx: TransactionForContract): List> - // Group by Trade ID for in / out states - = tx.groupStates() { state -> state.linearId } + // Group by Trade ID for in / out states + = tx.groupStates() { state -> state.linearId } } class Timestamped : Clause() { diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt index 1f6bd92403..2cd489ce71 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt @@ -52,6 +52,7 @@ open class Rate(val ratioUnit: RatioUnit? = null) { * for equality. */ override fun hashCode() = ratioUnit?.hashCode() ?: 0 + override fun toString() = ratioUnit.toString() } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/ExitServerFlow.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/ExitServerFlow.kt index ff3770f03d..f15f34e5fd 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/ExitServerFlow.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/ExitServerFlow.kt @@ -19,7 +19,7 @@ object ExitServerFlow { // resolve itself when the flow session stuff is done. data class ExitMessage(val exitCode: Int) - class Plugin: CordaPluginRegistry() { + class Plugin : CordaPluginRegistry() { override val servicePlugins: List> = listOf(Service::class.java) } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt index 2c8ec11a50..7658bc83df 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt @@ -73,6 +73,7 @@ object FixingFlow { // TODO Could it be solved in better way, move filtering here not in RatesFixFlow? // DOCSTART 1 fun filterCommands(c: Command) = oracleParty.owningKey in c.signers && c.value is Fix + val filterFuns = FilterFuns(filterCommands = ::filterCommands) val addFixing = object : RatesFixFlow(ptx, filterFuns, oracleParty, fixOf, BigDecimal.ZERO, BigDecimal.ONE) { @Suspendable diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/RatesFixFlow.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/RatesFixFlow.kt index ad9ef0ef59..237264cfc8 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/RatesFixFlow.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/RatesFixFlow.kt @@ -28,7 +28,7 @@ import java.util.* * @throws FixOutOfRange if the returned fix was further away from the expected rate by the given amount. */ open class RatesFixFlow(protected val tx: TransactionBuilder, - // Filtering functions over transaction, used to build partial transaction presented to oracle. + /** Filtering functions over transaction, used to build partial transaction presented to oracle. */ private val filterFuns: FilterFuns, private val oracle: Party, private val fixOf: FixOf, diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt index 3f8c40f9a7..ba8e9abde2 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt @@ -20,7 +20,7 @@ object UpdateBusinessDayFlow { // resolve itself when the flow session stuff is done. data class UpdateBusinessDayMessage(val date: LocalDate) - class Plugin: CordaPluginRegistry() { + class Plugin : CordaPluginRegistry() { override val servicePlugins: List> = listOf(Service::class.java) } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/utilities/HttpUtils.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/utilities/HttpUtils.kt index 9b0af8002d..b0b99ad7a0 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/utilities/HttpUtils.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/utilities/HttpUtils.kt @@ -9,21 +9,21 @@ import java.util.concurrent.TimeUnit */ private val client by lazy { OkHttpClient.Builder() - .connectTimeout(5, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS).build() + .connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS).build() } -fun putJson(url: URL, data: String) : Boolean { +fun putJson(url: URL, data: String): Boolean { val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data) return makeRequest(Request.Builder().url(url).put(body).build()) } -fun postJson(url: URL, data: String) : Boolean { +fun postJson(url: URL, data: String): Boolean { val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data) return makeRequest(Request.Builder().url(url).post(body).build()) } -fun uploadFile(url: URL, file: String) : Boolean { +fun uploadFile(url: URL, file: String): Boolean { val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("rates", "example.rates.txt", RequestBody.create(MediaType.parse("text/plain"), file)) diff --git a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/IRSTests.kt b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/IRSTests.kt index a23fe7acd3..603208f895 100644 --- a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/IRSTests.kt +++ b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/IRSTests.kt @@ -65,7 +65,7 @@ fun createDummyIRS(irsSelect: Int): InterestRateSwap.State { indexTenor = Tenor("3M") ) - val calculation = InterestRateSwap.Calculation ( + val calculation = InterestRateSwap.Calculation( // TODO: this seems to fail quite dramatically //expression = "fixedLeg.notional * fixedLeg.fixedRate", @@ -155,7 +155,7 @@ fun createDummyIRS(irsSelect: Int): InterestRateSwap.State { indexTenor = Tenor("3M") ) - val calculation = InterestRateSwap.Calculation ( + val calculation = InterestRateSwap.Calculation( // TODO: this seems to fail quite dramatically //expression = "fixedLeg.notional * fixedLeg.fixedRate", diff --git a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt index 52fdaa57f1..a837a22fc7 100644 --- a/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt +++ b/samples/irs-demo/src/test/kotlin/net/corda/irs/testing/NodeInterestRatesTest.kt @@ -56,8 +56,8 @@ class NodeInterestRatesTest { @Before fun setUp() { val dataSourceAndDatabase = configureDatabase(makeTestDataSourceProperties()) - dataSource=dataSourceAndDatabase.first - database=dataSourceAndDatabase.second + dataSource = dataSourceAndDatabase.first + database = dataSourceAndDatabase.second databaseTransaction(database) { oracle = NodeInterestRates.Oracle(MEGA_CORP, MEGA_CORP_KEY, clock).apply { knownFixes = TEST_DATA } } @@ -120,7 +120,7 @@ class NodeInterestRatesTest { databaseTransaction(database) { val tx = makeTX() val wtx1 = tx.toWireTransaction() - val ftx1 = FilteredTransaction.buildMerkleTransaction(wtx1, FilterFuns(filterOutputs = {true})) + val ftx1 = FilteredTransaction.buildMerkleTransaction(wtx1, FilterFuns(filterOutputs = { true })) assertFailsWith { oracle.sign(ftx1, wtx1.id) } tx.addCommand(Cash.Commands.Move(), ALICE_PUBKEY) val wtx2 = tx.toWireTransaction() diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt index 3466fe3a6a..0d301f7b2e 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt @@ -49,8 +49,8 @@ class NetworkMapVisualiser : Application() { } sealed class RunningPausedState { - class Running(val tickTimer: TimerTask): RunningPausedState() - class Paused(): RunningPausedState() + class Running(val tickTimer: TimerTask) : RunningPausedState() + class Paused() : RunningPausedState() val buttonLabel: RunPauseButtonLabel get() { @@ -71,7 +71,11 @@ class NetworkMapVisualiser : Application() { viewModel.view = view viewModel.presentationMode = "--presentation-mode" in parameters.raw buildScene(stage) - viewModel.displayStyle = if ("--circle" in parameters.raw) { Style.CIRCLE } else { viewModel.displayStyle } + viewModel.displayStyle = if ("--circle" in parameters.raw) { + Style.CIRCLE + } else { + viewModel.displayStyle + } val simulation = viewModel.simulation // Update the white-backgrounded label indicating what flow step it's up to. @@ -159,7 +163,7 @@ class NetworkMapVisualiser : Application() { } private fun bindTopbar() { - view.resetButton.setOnAction({reset()}) + view.resetButton.setOnAction({ reset() }) view.nextButton.setOnAction { if (!view.simulateInitialisationCheckbox.isSelected && !viewModel.simulation.networkInitialisationFinished.isDone) { skipNetworkInitialisation() diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserView.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserView.kt index 2d26b05bdd..9c90c46040 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserView.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserView.kt @@ -62,7 +62,7 @@ internal class VisualiserView() { NetworkMapVisualiser::class.java.getResourceAsStream("SourceSansPro-Regular.otf").use { Font.loadFont(it, 120.0) } - if(displayStyle == Style.MAP) { + if (displayStyle == Style.MAP) { mapImage.onZoom = EventHandler { event -> event.consume() mapImage.fitWidth = mapImage.fitWidth * event.zoomFactor @@ -169,7 +169,7 @@ internal class VisualiserView() { hideButton.translateXProperty().unbind() hideButton.translateXProperty().bind(splitter.dividers[0].positionProperty().multiply(splitter.widthProperty()).subtract(hideButton.widthProperty())) } - + fun scaleMap(displayStyle: Style) { when (displayStyle) { Style.MAP -> { diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt index ef50448c76..5117ac0784 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt @@ -1,8 +1,5 @@ package net.corda.netmap -import net.corda.core.utilities.ProgressTracker -import net.corda.simulation.IRSSimulation -import net.corda.testing.node.MockNetwork import javafx.animation.* import javafx.geometry.Pos import javafx.scene.control.Label @@ -10,6 +7,9 @@ import javafx.scene.layout.StackPane import javafx.scene.shape.Circle import javafx.scene.shape.Line import javafx.util.Duration +import net.corda.core.utilities.ProgressTracker +import net.corda.simulation.IRSSimulation +import net.corda.testing.node.MockNetwork import java.util.* class VisualiserViewModel { @@ -20,7 +20,7 @@ class VisualiserViewModel { return name.toLowerCase().capitalize() } } - + inner class NodeWidget(val node: MockNetwork.MockNode, val innerDot: Circle, val outerDot: Circle, val longPulseDot: Circle, val pulseAnim: Animation, val longPulseAnim: Animation, val nameLabel: Label, val statusLabel: Label) { @@ -89,11 +89,11 @@ class VisualiserViewModel { } fun nodeCircleCoords(type: NetworkMapVisualiser.NodeType, index: Int): Pair { - val stepRad: Double = when(type) { + val stepRad: Double = when (type) { NetworkMapVisualiser.NodeType.BANK -> 2 * Math.PI / bankCount NetworkMapVisualiser.NodeType.SERVICE -> (2 * Math.PI / serviceCount) } - val tangentRad: Double = stepRad * index + when(type) { + val tangentRad: Double = stepRad * index + when (type) { NetworkMapVisualiser.NodeType.BANK -> 0.0 NetworkMapVisualiser.NodeType.SERVICE -> Math.PI / 2 } @@ -170,7 +170,7 @@ class VisualiserViewModel { val widget = NodeWidget(forNode, innerDot, outerDot, longPulseOuterDot, pulseAnim, longPulseAnim, nameLabel, statusLabel) when (displayStyle) { - Style.CIRCLE -> widget.position(index, { node, index -> nodeCircleCoords(nodeType, index) } ) + Style.CIRCLE -> widget.position(index, { node, index -> nodeCircleCoords(nodeType, index) }) Style.MAP -> widget.position(index, { node, index -> nodeMapCoords(node) }) } return widget diff --git a/samples/network-visualiser/src/main/resources/net/corda/netmap/MainWindow.fxml b/samples/network-visualiser/src/main/resources/net/corda/netmap/MainWindow.fxml index f8f06e692b..fca22a9884 100644 --- a/samples/network-visualiser/src/main/resources/net/corda/netmap/MainWindow.fxml +++ b/samples/network-visualiser/src/main/resources/net/corda/netmap/MainWindow.fxml @@ -1,29 +1,26 @@ - - - - - - - - - - - - -