From 1a86ac481f70e1dcc2def30315b2e26156404a2e Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Tue, 11 Apr 2017 15:52:04 +0200 Subject: [PATCH] Minor: core: fix static analysis warnings. One actual bug was found this way, albeit a harmless one. --- core/build.gradle | 3 -- core/src/main/kotlin/net/corda/core/Utils.kt | 5 +-- .../net/corda/core/contracts/ContractsDSL.kt | 12 ------- .../net/corda/core/contracts/FinanceTypes.kt | 6 ++-- .../net/corda/core/contracts/Structures.kt | 21 +++---------- .../core/contracts/TransactionVerification.kt | 3 -- .../net/corda/core/contracts/clauses/AllOf.kt | 2 +- .../core/contracts/clauses/ClauseVerifier.kt | 2 +- .../corda/core/contracts/clauses/FilterOn.kt | 4 +-- .../corda/core/contracts/clauses/FirstOf.kt | 2 +- .../kotlin/net/corda/core/crypto/Crypto.kt | 2 +- .../net/corda/core/crypto/CryptoUtilities.kt | 9 +++--- .../net/corda/core/crypto/EdDSAKeyFactory.kt | 4 +-- .../kotlin/net/corda/core/crypto/Party.kt | 2 +- .../net/corda/core/flows/FlowStateMachine.kt | 3 +- .../corda/core/node/services/ServiceInfo.kt | 2 +- .../net/corda/core/schemas/PersistentTypes.kt | 9 ++---- .../corda/core/serialization/ByteArrays.kt | 4 +-- .../core/serialization/CordaClassResolver.kt | 12 +++---- .../net/corda/core/serialization/Kryo.kt | 21 ++----------- .../core/serialization/SerializationToken.kt | 1 - .../core/transactions/TransactionBuilder.kt | 2 +- .../net/corda/core/utilities/ApiUtils.kt | 31 ------------------- .../corda/core/utilities/ProgressTracker.kt | 14 --------- .../net/corda/flows/TwoPartyDealFlow.kt | 11 ------- .../kotlin/net/corda/core/FinanceTypesTest.kt | 2 +- .../contracts/TransactionEncumbranceTests.kt | 4 +-- .../kotlin/net/corda/core/flows/TxKeyFlow.kt | 2 +- .../core/node/AttachmentClassLoaderTests.kt | 3 +- .../DBTransactionMappingStorage.kt | 2 +- 30 files changed, 44 insertions(+), 156 deletions(-) delete mode 100644 core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt diff --git a/core/build.gradle b/core/build.gradle index bdf5f70dde..70723cd41d 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -80,9 +80,6 @@ dependencies { // JPA 2.1 annotations. compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final" - // RS API: Response type and codes for ApiUtils. - compile "javax.ws.rs:javax.ws.rs-api:2.0.1" - // Requery: SQL based query & persistence for Kotlin compile "io.requery:requery-kotlin:$requery_version" } diff --git a/core/src/main/kotlin/net/corda/core/Utils.kt b/core/src/main/kotlin/net/corda/core/Utils.kt index 5a99ae8ae6..db74a7e5a1 100644 --- a/core/src/main/kotlin/net/corda/core/Utils.kt +++ b/core/src/main/kotlin/net/corda/core/Utils.kt @@ -105,7 +105,7 @@ infix fun ListenableFuture.then(body: () -> Unit): ListenableFuture = infix fun ListenableFuture.success(body: (T) -> Unit): ListenableFuture = apply { success(RunOnCallerThread, body) } infix fun ListenableFuture.failure(body: (Throwable) -> Unit): ListenableFuture = apply { failure(RunOnCallerThread, body) } @Suppress("UNCHECKED_CAST") // We need the awkward cast because otherwise F cannot be nullable, even though it's safe. -infix fun ListenableFuture.map(mapper: (F) -> T): ListenableFuture = Futures.transform(this, Function { (mapper as (F?) -> T)(it) }) +infix fun ListenableFuture.map(mapper: (F) -> T): ListenableFuture = Futures.transform(this, { (mapper as (F?) -> T)(it) }) infix fun ListenableFuture.flatMap(mapper: (F) -> ListenableFuture): ListenableFuture = Futures.transformAsync(this) { mapper(it!!) } /** Executes the given block and sets the future to either the result, or any exception that was thrown. */ @@ -156,7 +156,7 @@ fun Path.writeLines(lines: Iterable, charset: Charset = UTF_8, var fun InputStream.copyTo(target: Path, vararg options: CopyOption): Long = Files.copy(this, target, *options) // Simple infix function to add back null safety that the JDK lacks: timeA until timeB -infix fun Temporal.until(endExclusive: Temporal) = Duration.between(this, endExclusive) +infix fun Temporal.until(endExclusive: Temporal): Duration = Duration.between(this, endExclusive) /** Returns the index of the given item or throws [IllegalArgumentException] if not found. */ fun List.indexOfOrThrow(item: T): Int { @@ -349,6 +349,7 @@ data class InputStreamAndHash(val inputStream: InputStream, val sha256: SecureHa val Throwable.rootCause: Throwable get() = Throwables.getRootCause(this) /** Representation of an operation that may have thrown an error. */ +@Suppress("DataClassPrivateConstructor") @CordaSerializable data class ErrorOr private constructor(val value: A?, val error: Throwable?) { // The ErrorOr holds a value iff error == null 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 b08e7100ac..f39e355090 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt @@ -103,18 +103,6 @@ inline fun Collection fun Collection>.requireSingleCommand(klass: Class) = mapNotNull { @Suppress("UNCHECKED_CAST") if (klass.isInstance(it.value)) it as AuthenticatedObject else null }.single() -/** - * Simple functionality for verifying a move command. Verifies that each input has a signature from its owning key. - * - * @param T the type of the move command. - */ -@Throws(IllegalArgumentException::class) -// TODO: Can we have a common Move command for all contracts and avoid the reified type parameter here? -inline fun verifyMoveCommand(inputs: List, - tx: TransactionForContract) - : MoveCommand - = verifyMoveCommand(inputs, tx.commands) - /** * Simple functionality for verifying a move command. Verifies that each input has a signature from its owning key. * 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 ee27e53e14..9ccff91150 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/FinanceTypes.kt @@ -267,7 +267,7 @@ fun Iterable>.sumOrZero(token: T) = if (iterator().hasNext() * @see SourceAndAmount.apply which processes a list of SourceAndAmount objects * and calculates the resulting Amount distribution as a new list of SourceAndAmount objects. */ -data class SourceAndAmount(val source: P, val amount: Amount, val ref: Any? = null) +data class SourceAndAmount(val source: P, val amount: Amount, val ref: Any? = null) /** * This class represents a possibly negative transfer of tokens from one vault state to another, possibly at a future date. @@ -516,7 +516,7 @@ data class Tenor(val name: String) { val adjustedMaturityDate = calendar.applyRollConvention(maturityDate, DateRollConvention.ModifiedFollowing) val daysToMaturity = calculateDaysBetween(startDate, adjustedMaturityDate, DayCountBasisYear.Y360, DayCountBasisDay.DActual) - return daysToMaturity.toInt() + return daysToMaturity } override fun toString(): String = name @@ -645,7 +645,7 @@ open class BusinessCalendar private constructor(val holidayDates: List { val multilateralNetState: T } -interface NettableState, T : Any> : BilateralNettableState, +interface NettableState, out T : Any> : BilateralNettableState, MultilateralNettableState /** @@ -145,26 +145,13 @@ data class TransactionState @JvmOverloads constructor( * Note that an encumbered state that is being consumed must have its encumbrance consumed in the same transaction, * otherwise the transaction is not valid. */ - val encumbrance: Int? = null) { - - /** - * Copies the underlying state, replacing the notary field with the new value. - * To replace the notary, we need an approval (signature) from _all_ participants of the [ContractState]. - */ - fun withNotary(newNotary: Party) = TransactionState(this.data, newNotary, encumbrance) -} + val encumbrance: Int? = null) /** 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) -/** - * Marker interface for data classes that represent the issuance state for a contract. These are intended as templates - * from which the state object is initialised. - */ -interface IssuanceDefinition - /** * Definition for an issued product, which can be cash, a cash-like thing, assets, or generally anything else that's * quantifiable with integer quantities. @@ -243,7 +230,7 @@ interface LinearState : ContractState { * Standard clause to verify the LinearState safety properties. */ @CordaSerializable - class ClauseVerifier : Clause() { + class ClauseVerifier : Clause() { override fun verify(tx: TransactionForContract, inputs: List, outputs: List, @@ -360,7 +347,7 @@ inline fun Iterable>.filt data class PartyAndReference(val party: AnonymousParty, val reference: OpaqueBytes) { constructor(party: Party, reference: OpaqueBytes) : this(party.toAnonymous(), reference) - override fun toString() = "${party}$reference" + override fun toString() = "$party$reference" } /** Marker interface for classes that represent commands */ 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 be8fa723f8..86ca7282a3 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerification.kt @@ -95,9 +95,6 @@ class AttachmentResolutionException(val hash: SecureHash) : FlowException() { override fun toString(): String = "Attachment resolution failure for $hash" } -@CordaSerializable -class TransactionConflictException(val conflictRef: StateRef, val tx1: LedgerTransaction, val tx2: LedgerTransaction) : Exception() - sealed class TransactionVerificationException(val tx: LedgerTransaction, cause: Throwable?) : FlowException(cause) { class ContractRejection(tx: LedgerTransaction, val contract: Contract, cause: Throwable?) : TransactionVerificationException(tx, cause) class MoreThanOneNotary(tx: LedgerTransaction) : TransactionVerificationException(tx, null) diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/AllOf.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/AllOf.kt index 3eeda50ec7..6fcc9df40b 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/AllOf.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/AllOf.kt @@ -19,7 +19,7 @@ open class AllOf(firstClause: Claus override fun matchedClauses(commands: List>): List> { clauses.forEach { clause -> - check(clause.matches(commands)) { "Failed to match clause ${clause}" } + check(clause.matches(commands)) { "Failed to match clause $clause" } } return clauses } 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 c9991a5e22..30fadda3ed 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 @@ -20,7 +20,7 @@ fun verifyClause(tx: TransactionForContract, commands: List>) { if (Clause.log.isTraceEnabled) { clause.getExecutionPath(commands).forEach { - Clause.log.trace("Tx ${tx.origHash} clause: ${clause}") + Clause.log.trace("Tx ${tx.origHash} clause: $clause") } } val matchedCommands = clause.verify(tx, tx.inputs, tx.outputs, commands, null) diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/FilterOn.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/FilterOn.kt index 55bb5b3053..e34f313443 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/FilterOn.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/FilterOn.kt @@ -8,8 +8,8 @@ import net.corda.core.contracts.TransactionForContract /** * Filter the states that are passed through to the wrapped clause, to restrict them to a specific type. */ -class FilterOn(val clause: Clause, - val filterStates: (List) -> List) : Clause() { +class FilterOn(val clause: Clause, + val filterStates: (List) -> List) : Clause() { override val requiredCommands: Set> = clause.requiredCommands diff --git a/core/src/main/kotlin/net/corda/core/contracts/clauses/FirstOf.kt b/core/src/main/kotlin/net/corda/core/contracts/clauses/FirstOf.kt index bac08f3f4d..43a495b026 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/clauses/FirstOf.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/clauses/FirstOf.kt @@ -10,7 +10,7 @@ import java.util.* /** * Compose a number of clauses, such that the first match is run, and it errors if none is run. */ -class FirstOf(val firstClause: Clause, vararg remainingClauses: Clause) : CompositeClause() { +class FirstOf(firstClause: Clause, vararg remainingClauses: Clause) : CompositeClause() { companion object { val logger = loggerFor>() } diff --git a/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt b/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt index 2d42d958b7..d43bb621a0 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt @@ -122,7 +122,7 @@ object Crypto { * @return a currently supported SignatureScheme. * @throws IllegalArgumentException if the requested signature scheme is not supported. */ - private fun findSignatureScheme(schemeCodeName: String): SignatureScheme = supportedSignatureSchemes[schemeCodeName] ?: throw IllegalArgumentException("Unsupported key/algorithm for metadata schemeCodeName: ${schemeCodeName}") + private fun findSignatureScheme(schemeCodeName: String): SignatureScheme = supportedSignatureSchemes[schemeCodeName] ?: throw IllegalArgumentException("Unsupported key/algorithm for metadata schemeCodeName: $schemeCodeName") /** * Retrieve the corresponding [SignatureScheme] based on the type of the input [KeyPair]. diff --git a/core/src/main/kotlin/net/corda/core/crypto/CryptoUtilities.kt b/core/src/main/kotlin/net/corda/core/crypto/CryptoUtilities.kt index 93456fcf2e..7e4e9d8983 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/CryptoUtilities.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/CryptoUtilities.kt @@ -10,6 +10,7 @@ import net.i2p.crypto.eddsa.EdDSAEngine import net.i2p.crypto.eddsa.EdDSAPrivateKey import net.i2p.crypto.eddsa.EdDSAPublicKey import net.i2p.crypto.eddsa.KeyPairGenerator +import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec @@ -72,7 +73,7 @@ fun PrivateKey.signWithECDSA(bytesToSign: ByteArray, publicKey: PublicKey): Digi return DigitalSignature.WithKey(publicKey, signWithECDSA(bytesToSign).bytes) } -val ed25519Curve = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512) +val ed25519Curve: EdDSANamedCurveSpec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512) // TODO We use for both CompositeKeys and EdDSAPublicKey custom Kryo serializers and deserializers. We need to specify encoding. // TODO: follow the crypto-conditions ASN.1 spec, some changes are needed to be compatible with the condition @@ -106,7 +107,7 @@ fun PublicKey.verifyWithECDSA(content: ByteArray, signature: DigitalSignature) { val verifier = EdDSAEngine() verifier.initVerify(pubKey) verifier.update(content) - if (verifier.verify(signature.bytes) == false) + if (!verifier.verify(signature.bytes)) throw SignatureException("Signature did not match") } @@ -138,9 +139,9 @@ fun PublicKey.containsAny(otherKeys: Iterable): Boolean { fun Iterable.byKeys() = map { it.by }.toSet() // Allow Kotlin destructuring: val (private, public) = keyPair -operator fun KeyPair.component1() = this.private +operator fun KeyPair.component1(): PrivateKey = this.private -operator fun KeyPair.component2() = this.public +operator fun KeyPair.component2(): PublicKey = this.public /** A simple wrapper that will make it easier to swap out the EC algorithm we use in future */ fun generateKeyPair(): KeyPair = KeyPairGenerator().generateKeyPair() diff --git a/core/src/main/kotlin/net/corda/core/crypto/EdDSAKeyFactory.kt b/core/src/main/kotlin/net/corda/core/crypto/EdDSAKeyFactory.kt index e20ec71fd9..252f7c7f1a 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/EdDSAKeyFactory.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/EdDSAKeyFactory.kt @@ -7,6 +7,4 @@ import java.security.KeyFactory * This is required as a [SignatureScheme] requires a [java.security.KeyFactory] property, but i2p has * its own KeyFactory for EdDSA, thus this actually a Proxy Pattern over i2p's KeyFactory. */ -class EdDSAKeyFactory : KeyFactory { - constructor() : super(net.i2p.crypto.eddsa.KeyFactory(), null, "EDDSA_ED25519_SHA512") -} +class EdDSAKeyFactory : KeyFactory(net.i2p.crypto.eddsa.KeyFactory(), null, "EDDSA_ED25519_SHA512") diff --git a/core/src/main/kotlin/net/corda/core/crypto/Party.kt b/core/src/main/kotlin/net/corda/core/crypto/Party.kt index 1e65cda82b..db0c34769d 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/Party.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/Party.kt @@ -24,7 +24,7 @@ import java.security.PublicKey */ class Party(val name: String, owningKey: PublicKey) : AbstractParty(owningKey) { override fun toAnonymous(): AnonymousParty = AnonymousParty(owningKey) - override fun toString() = "${owningKey.toBase58String()} (${name})" + override fun toString() = "${owningKey.toBase58String()} ($name)" override fun nameOrNull(): String? = name override fun ref(bytes: OpaqueBytes): PartyAndReference = PartyAndReference(this.toAnonymous(), bytes) diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowStateMachine.kt b/core/src/main/kotlin/net/corda/core/flows/FlowStateMachine.kt index 275c86c276..13eac83fd7 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowStateMachine.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowStateMachine.kt @@ -16,10 +16,9 @@ import java.util.* * has at least one flow, but that flow may also invoke sub-flows: they all share the same run id. */ @CordaSerializable -data class StateMachineRunId private constructor(val uuid: UUID) { +data class StateMachineRunId(val uuid: UUID) { companion object { fun createRandom(): StateMachineRunId = StateMachineRunId(UUID.randomUUID()) - fun wrap(uuid: UUID): StateMachineRunId = StateMachineRunId(uuid) } override fun toString(): String = "[$uuid]" diff --git a/core/src/main/kotlin/net/corda/core/node/services/ServiceInfo.kt b/core/src/main/kotlin/net/corda/core/node/services/ServiceInfo.kt index 94774a40f2..ded1d04530 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/ServiceInfo.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/ServiceInfo.kt @@ -14,7 +14,7 @@ data class ServiceInfo(val type: ServiceType, val name: String? = null) { companion object { fun parse(encoded: String): ServiceInfo { val parts = encoded.split("|") - require(parts.size > 0 && parts.size <= 2) { "Invalid number of elements found" } + require(parts.size in 1..2) { "Invalid number of elements found" } val type = ServiceType.parse(parts[0]) val name = parts.getOrNull(1) return ServiceInfo(type, name) diff --git a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt index 7288f9fdcb..ed401c2f39 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt @@ -57,15 +57,10 @@ abstract class MappedSchema(schemaFamily: Class<*>, @Embeddable data class PersistentStateRef( @Column(name = "transaction_id", length = 64) - var txId: String?, + var txId: String? = null, @Column(name = "output_index") - var index: Int? + var index: Int? = null ) : Serializable { constructor(stateRef: StateRef) : this(stateRef.txhash.bytes.toHexString(), stateRef.index) - /* - JPA Query requirement: - @Entity classes should have a default (non-arg) constructor to instantiate the objects when retrieving them from the database. - */ - constructor() : this(null, null) } diff --git a/core/src/main/kotlin/net/corda/core/serialization/ByteArrays.kt b/core/src/main/kotlin/net/corda/core/serialization/ByteArrays.kt index e08325ef58..9c36c9d19b 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/ByteArrays.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/ByteArrays.kt @@ -35,5 +35,5 @@ open class OpaqueBytes(val bytes: ByteArray) { } fun ByteArray.opaque(): OpaqueBytes = OpaqueBytes(this) -fun ByteArray.toHexString() = BaseEncoding.base16().encode(this) -fun String.parseAsHex() = BaseEncoding.base16().decode(this) +fun ByteArray.toHexString(): String = BaseEncoding.base16().encode(this) +fun String.parseAsHex(): ByteArray = BaseEncoding.base16().decode(this) diff --git a/core/src/main/kotlin/net/corda/core/serialization/CordaClassResolver.kt b/core/src/main/kotlin/net/corda/core/serialization/CordaClassResolver.kt index 078f065ac7..821b7e784f 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/CordaClassResolver.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/CordaClassResolver.kt @@ -26,10 +26,6 @@ fun makeNoWhitelistClassResolver(): ClassResolver { } class CordaClassResolver(val whitelist: ClassWhitelist) : DefaultClassResolver() { - companion object { - private val logger = loggerFor() - } - /** Returns the registration for the specified class, or null if the class is not registered. */ override fun getRegistration(type: Class<*>): Registration? { return super.getRegistration(type) ?: checkClass(type) @@ -147,10 +143,14 @@ class GlobalTransientClassWhiteList(val delegate: ClassWhitelist) : MutableClass } } + /** * This class is not currently used, but can be installed to log a large number of missing entries from the whitelist * and was used to track down the initial set. + * + * @suppress */ +@Suppress("unused") class LoggingWhitelist(val delegate: ClassWhitelist, val global: Boolean = true) : MutableClassWhitelist { companion object { val log = loggerFor() @@ -178,9 +178,7 @@ class LoggingWhitelist(val delegate: ClassWhitelist, val global: Boolean = true) alreadySeen += type.name val className = Util.className(type) log.warn("Dynamically whitelisted class $className") - if (journalWriter != null) { - journalWriter.println(className) - } + journalWriter?.println(className) } return true } 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 a9aad7a0b5..0a40e2a7cc 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/Kryo.kt @@ -72,10 +72,12 @@ fun p2PKryo(): KryoPool = kryoPool // Same again, but this has whitelisting turned off for internal storage use only. fun storageKryo(): KryoPool = internalKryoPool + /** * A type safe wrapper around a byte array that contains a serialised object. You can call [SerializedBytes.deserialize] * to get the original object back. */ +@Suppress("unused") // Type parameter is just for documentation purposes. class SerializedBytes(bytes: ByteArray, val internalOnly: Boolean = false) : OpaqueBytes(bytes) { // It's OK to use lazy here because SerializedBytes is configured to use the ImmutableClassSerializer. val hash: SecureHash by lazy { bytes.sha256() } @@ -542,25 +544,6 @@ fun Kryo.withAttachmentStorage(attachmentStorage: AttachmentStorage?, block: } } -object OrderedSerializer : Serializer>() { - override fun write(kryo: Kryo, output: Output, obj: HashMap) { - //Change a HashMap to LinkedHashMap. - val linkedMap = LinkedHashMap() - val sorted = obj.toList().sortedBy { it.first.hashCode() } - for ((k, v) in sorted) { - linkedMap.put(k, v) - } - kryo.writeClassAndObject(output, linkedMap) - } - - //It will be deserialized as a LinkedHashMap. - @Suppress("UNCHECKED_CAST") - override fun read(kryo: Kryo, input: Input, type: Class>): HashMap { - val hm = kryo.readClassAndObject(input) as HashMap - return hm - } -} - /** For serialising a MetaData object. */ @ThreadSafe object MetaDataSerializer : Serializer() { diff --git a/core/src/main/kotlin/net/corda/core/serialization/SerializationToken.kt b/core/src/main/kotlin/net/corda/core/serialization/SerializationToken.kt index 515651c4c3..9e6fab1cbc 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/SerializationToken.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/SerializationToken.kt @@ -103,7 +103,6 @@ class SerializeAsTokenContext(toBeTokenized: Any, kryoPool: KryoPool) { */ @CordaSerializable data class SingletonSerializationToken private constructor(private val className: String) : SerializationToken { - constructor(toBeTokenized: SerializeAsToken) : this(toBeTokenized.javaClass.name) override fun fromToken(context: SerializeAsTokenContext): Any = context.tokenToTokenized[this] ?: 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 4db371d3a5..8f99c0c358 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/TransactionBuilder.kt @@ -147,7 +147,7 @@ open class TransactionBuilder( open fun addInputState(stateAndRef: StateAndRef<*>) { check(currentSigs.isEmpty()) val notary = stateAndRef.state.notary - require(notary == this.notary) { "Input state requires notary \"${notary}\" which does not match the transaction notary \"${this.notary}\"." } + require(notary == this.notary) { "Input state requires notary \"$notary\" which does not match the transaction notary \"${this.notary}\"." } signers.add(notary.owningKey) inputs.add(stateAndRef.ref) } diff --git a/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt deleted file mode 100644 index 94663d3634..0000000000 --- a/core/src/main/kotlin/net/corda/core/utilities/ApiUtils.kt +++ /dev/null @@ -1,31 +0,0 @@ -package net.corda.core.utilities - -import net.corda.core.ErrorOr -import net.corda.core.crypto.Party -import net.corda.core.crypto.parsePublicKeyBase58 -import net.corda.core.messaging.CordaRPCOps -import javax.ws.rs.core.Response - -/** - * Utility functions to reduce boilerplate when developing HTTP APIs - */ -class ApiUtils(val rpc: CordaRPCOps) { - private val defaultNotFound = { msg: String -> Response.status(Response.Status.NOT_FOUND).entity(msg).build() } - - /** - * Get a party and then execute the passed function with the party public key as a parameter. - * Usage: withParty(key) { doSomethingWith(it) } - */ - fun withParty(partyKeyStr: String, notFound: (String) -> Response = defaultNotFound, found: (Party) -> Response): Response { - val party = try { - val partyKey = parsePublicKeyBase58(partyKeyStr) - ErrorOr(rpc.partyFromKey(partyKey)) - } catch (e: IllegalArgumentException) { - ErrorOr.of(Exception("Invalid base58 key passed for party key $e")) - } - return party.bind { if (it == null) ErrorOr.of(Exception("Unknown party")) else ErrorOr(found(it)) }.match( - onValue = { it }, - onError = { notFound(it.toString()) } - ) - } -} 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 616f988708..9074af2a28 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt @@ -57,20 +57,6 @@ class ProgressTracker(vararg steps: Step) { open fun childProgressTracker(): ProgressTracker? = null } - // TODO: There's no actual way to create these steps anymore! - /** This class makes it easier to relabel a step on the fly, to provide transient information. */ - open inner class RelabelableStep(currentLabel: String) : Step(currentLabel) { - override val changes: BehaviorSubject = BehaviorSubject.create() - - var currentLabel: String = currentLabel - set(value) { - field = value - changes.onNext(ProgressTracker.Change.Rendering(this@ProgressTracker, this@RelabelableStep)) - } - - override val label: String get() = currentLabel - } - // Sentinel objects. Overrides equals() to survive process restarts and serialization. object UNSTARTED : Step("Unstarted") { override fun equals(other: Any?) = other is UNSTARTED diff --git a/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt b/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt index 88f72d45d3..3adbe4551e 100644 --- a/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/TwoPartyDealFlow.kt @@ -31,17 +31,6 @@ import java.security.PublicKey * */ object TwoPartyDealFlow { - - @CordaSerializable - class DealMismatchException(val expectedDeal: ContractState, val actualDeal: ContractState) : Exception() { - override fun toString() = "The submitted deal didn't match the expected: $expectedDeal vs $actualDeal" - } - - @CordaSerializable - class DealRefMismatchException(val expectedDeal: StateRef, val actualDeal: StateRef) : Exception() { - override fun toString() = "The submitted deal didn't match the expected: $expectedDeal vs $actualDeal" - } - // This object is serialised to the network and is the first flow message the seller sends to the buyer. @CordaSerializable data class Handshake(val payload: T, val publicKey: PublicKey) diff --git a/core/src/test/kotlin/net/corda/core/FinanceTypesTest.kt b/core/src/test/kotlin/net/corda/core/FinanceTypesTest.kt index 5315aa05b0..3e1bf41c16 100644 --- a/core/src/test/kotlin/net/corda/core/FinanceTypesTest.kt +++ b/core/src/test/kotlin/net/corda/core/FinanceTypesTest.kt @@ -19,7 +19,7 @@ class FinanceTypesTest { @Test fun `valid tenor tests`() { val exampleTenors = ("ON,1D,2D,3D,4D,5D,6D,7D,1W,2W,3W,1M,3M,6M,1Y,2Y,3Y,5Y,10Y,12Y,20Y").split(",") - exampleTenors.all { Tenor(it).name.length > 0 } // Slightly obtuse way of ensuring no exception thrown in construction. + exampleTenors.all { Tenor(it).name.isNotEmpty() } // Slightly obtuse way of ensuring no exception thrown in construction. } @Test diff --git a/core/src/test/kotlin/net/corda/core/contracts/TransactionEncumbranceTests.kt b/core/src/test/kotlin/net/corda/core/contracts/TransactionEncumbranceTests.kt index a1031473eb..a00380e7df 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/TransactionEncumbranceTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/TransactionEncumbranceTests.kt @@ -23,8 +23,8 @@ class TransactionEncumbranceTests { ) val stateWithNewOwner = state.copy(owner = DUMMY_PUBKEY_2) - val FOUR_PM = Instant.parse("2015-04-17T16:00:00.00Z") - val FIVE_PM = FOUR_PM.plus(1, ChronoUnit.HOURS) + val FOUR_PM: Instant = Instant.parse("2015-04-17T16:00:00.00Z") + val FIVE_PM: Instant = FOUR_PM.plus(1, ChronoUnit.HOURS) val timeLock = DummyTimeLock.State(FIVE_PM) class DummyTimeLock : Contract { diff --git a/core/src/test/kotlin/net/corda/core/flows/TxKeyFlow.kt b/core/src/test/kotlin/net/corda/core/flows/TxKeyFlow.kt index 2bca0400d6..603369ac9a 100644 --- a/core/src/test/kotlin/net/corda/core/flows/TxKeyFlow.kt +++ b/core/src/test/kotlin/net/corda/core/flows/TxKeyFlow.kt @@ -51,7 +51,7 @@ object TxKeyFlow { @Suspendable override fun call(): PublicKey { - progressTracker.currentStep == SENDING_KEY + progressTracker.currentStep = SENDING_KEY return TxKeyFlowUtilities.provideKey(this, otherSide) } } 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 95516e58b5..abd9aac401 100644 --- a/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt +++ b/core/src/test/kotlin/net/corda/core/node/AttachmentClassLoaderTests.kt @@ -16,6 +16,7 @@ import org.junit.Before import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream +import java.net.URL import java.net.URLClassLoader import java.security.PublicKey import java.util.jar.JarOutputStream @@ -33,7 +34,7 @@ val ATTACHMENT_TEST_PROGRAM_ID = AttachmentClassLoaderTests.AttachmentDummyContr class AttachmentClassLoaderTests { companion object { - val ISOLATED_CONTRACTS_JAR_PATH = AttachmentClassLoaderTests::class.java.getResource("isolated.jar") + val ISOLATED_CONTRACTS_JAR_PATH: URL = AttachmentClassLoaderTests::class.java.getResource("isolated.jar") } class AttachmentDummyContract : Contract { diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt index af4472d210..1094ff8135 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt @@ -31,7 +31,7 @@ class DBTransactionMappingStorage : StateMachineRecordedTransactionMappingStorag private class TransactionMappingsMap : AbstractJDBCHashMap(Table, loadOnInit = false) { override fun keyFromRow(row: ResultRow): SecureHash = row[table.txId] - override fun valueFromRow(row: ResultRow): StateMachineRunId = StateMachineRunId.wrap(row[table.stateMachineRunId]) + override fun valueFromRow(row: ResultRow): StateMachineRunId = StateMachineRunId(row[table.stateMachineRunId]) override fun addKeyToInsert(insert: InsertStatement, entry: Map.Entry, finalizables: MutableList<() -> Unit>) { insert[table.txId] = entry.key