Run the IntelliJ reformatter across the Kotlin code. Did not reformat JS/web code.

This commit is contained in:
Mike Hearn 2016-11-30 14:40:34 +00:00
parent 4a9f5cafc1
commit 7b40be8361
149 changed files with 763 additions and 618 deletions

View File

@ -84,4 +84,4 @@ class CordaRPCClientTest {
}
println("Result: ${flowHandle.returnValue.toBlocking().first()}")
}
}
}

View File

@ -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. */

View File

@ -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) }
}
}

View File

@ -22,7 +22,7 @@ import javafx.collections.ObservableListBase
*/
class ChosenList<E>(
private val chosenListObservable: ObservableValue<out ObservableList<out E>>
): ObservableListBase<E>() {
) : ObservableListBase<E>() {
private var currentList = chosenListObservable.value

View File

@ -41,6 +41,7 @@ class ConcatenatedList<A>(sourceList: ObservableList<ObservableList<A>>) : Trans
internal val indexMap = HashMap<WrappedObservableList<out A>, Pair<Int, ListChangeListener<A>>>()
@VisibleForTesting
internal val nestedIndexOffsets = ArrayList<Int>(sourceList.size)
init {
var offset = 0
sourceList.forEachIndexed { index, observableList ->
@ -78,7 +79,7 @@ class ConcatenatedList<A>(sourceList: ObservableList<ObservableList<A>>) : 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<A>(sourceList: ObservableList<ObservableList<A>>) : 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<A>(sourceList: ObservableList<ObservableList<A>>) : 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<A>(sourceList: ObservableList<ObservableList<A>>) : 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<A>(sourceList: ObservableList<ObservableList<A>>) : 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

View File

@ -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<A>(val sourceList: ObservableList<out ObservableValue<out A>
class WrappedObservableValue<A>(
val observableValue: ObservableValue<A>
)
val indexMap = HashMap<WrappedObservableValue<out A>, Pair<Int, ChangeListener<A>>>()
init {
sourceList.forEachIndexed { index, observableValue ->
val wrappedObservableValue = WrappedObservableValue(observableValue)

View File

@ -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

View File

@ -48,18 +48,22 @@ fun <A, B> ObservableList<out A>.map(cached: Boolean = true, function: (A) -> B)
* val aliceHeightPlus2 = ::sumHeight.lift(aliceHeight, 2L.lift())
*/
fun <A> A.lift(): ObservableValue<A> = ReadOnlyObjectWrapper(this)
fun <A, R> ((A) -> R).lift(
arg0: ObservableValue<A>
): ObservableValue<R> = EasyBind.map(arg0, this)
fun <A, B, R> ((A, B) -> R).lift(
arg0: ObservableValue<A>,
arg1: ObservableValue<B>
): ObservableValue<R> = EasyBind.combine(arg0, arg1, this)
fun <A, B, C, R> ((A, B, C) -> R).lift(
arg0: ObservableValue<A>,
arg1: ObservableValue<B>,
arg2: ObservableValue<C>
): ObservableValue<R> = EasyBind.combine(arg0, arg1, arg2, this)
fun <A, B, C, D, R> ((A, B, C, D) -> R).lift(
arg0: ObservableValue<A>,
arg1: ObservableValue<B>,
@ -74,6 +78,7 @@ fun <A, B, C, D, R> ((A, B, C, D) -> R).lift(
*/
fun <A, B> ObservableValue<out A>.bind(function: (A) -> ObservableValue<B>): ObservableValue<B> =
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 <A : Any, B : Any, K : Any> ObservableList<A>.leftOuterJoin(
fun <A> ObservableList<A>.getValueAt(index: Int): ObservableValue<A?> {
return Bindings.valueAt(this, index)
}
fun <A> ObservableList<A>.first(): ObservableValue<A?> {
return getValueAt(0)
}
fun <A> ObservableList<A>.last(): ObservableValue<A?> {
return Bindings.createObjectBinding({
if (size > 0) {

View File

@ -25,7 +25,7 @@ class ReplayedList<A>(sourceList: ObservableList<A>) : TransformationList<A, A>(
val permutation = IntArray(to, { c.getPermutation(it) })
val permutedSubList = ArrayList<A?>(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<A>(sourceList: ObservableList<A>) : TransformationList<A, A>(
}
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<A>(sourceList: ObservableList<A>) : TransformationList<A, A>(
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)

View File

@ -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<out A : Any>(val generate: (SplittableRandom) -> ErrorOr<A>) {
// Applicative
fun <B : Any> product(other: Generator<(A) -> B>) =
Generator { generate(it).combine(other.generate(it)) { a, f -> f(a) } }
fun <B : Any, R : Any> combine(other1: Generator<B>, function: (A, B) -> R) =
product<R>(other1.product(pure({ b -> { a -> function(a, b) } })))
fun <B : Any, C : Any, R : Any> combine(other1: Generator<B>, other2: Generator<C>, function: (A, B, C) -> R) =
product<R>(other1.product(other2.product(pure({ c -> { b -> { a -> function(a, b, c) } } }))))
fun <B : Any, C : Any, D : Any, R : Any> combine(other1: Generator<B>, other2: Generator<C>, other3: Generator<D>, function: (A, B, C, D) -> R) =
product<R>(other1.product(other2.product(other3.product(pure({ d -> { c -> { b -> { a -> function(a, b, c, d) } } } })))))
fun <B : Any, C : Any, D : Any, E : Any, R : Any> combine(other1: Generator<B>, other2: Generator<C>, other3: Generator<D>, other4: Generator<E>, function: (A, B, C, D, E) -> R) =
product<R>(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 <A : Any> Generator.Companion.frequency(vararg generators: Pair<Double, Gene
fun <A : Any> Generator<A>.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<ByteArray> = 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<Int> = 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<Long> = 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<Double> = Generator.success {
from + it.nextDouble() * (to - from)
@ -137,7 +145,7 @@ fun Generator.Companion.doubleRange(from: Double, to: Double): Generator<Double>
fun <A : Any> Generator.Companion.replicate(number: Int, generator: Generator<A>): Generator<List<A>> {
val generators = mutableListOf<Generator<A>>()
for (i in 1 .. number) {
for (i in 1..number) {
generators.add(generator)
}
return sequence(generators)
@ -168,10 +176,10 @@ fun <A : Any> Generator.Companion.replicatePoisson(meanSize: Double, generator:
fun <A : Any> Generator.Companion.pickOne(list: List<A>) = Generator.intRange(0, list.size - 1).map { list[it] }
fun <A : Any> Generator.Companion.pickN(number: Int, list: List<A>) = Generator<List<A>> {
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 <A : Any> Generator.Companion.pickN(number: Int, list: List<A>) = Generator<
fun <A> Generator.Companion.sampleBernoulli(maxRatio: Double = 1.0, vararg collection: A) =
sampleBernoulli(listOf(collection), maxRatio)
fun <A> Generator.Companion.sampleBernoulli(collection: Collection<A>, maxRatio: Double = 1.0): Generator<List<A>> =
intRange(0, (maxRatio * collection.size).toInt()).bind { howMany ->
replicate(collection.size, Generator.doubleRange(0.0, 1.0)).map { chances ->

View File

@ -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<Currency>, to: Currency) =
Amount(exchangeDouble(amount, to).toLong(), to)
fun ExchangeRate.exchangeDouble(amount: Amount<Currency>, to: Currency) =
rate(amount.token, to) * amount.quantity

View File

@ -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<ObservableValue<InputResolution>>) {
val id = transaction.id
sealed class InputResolution(val stateRef: StateRef) {
class Unresolved(stateRef: StateRef) : InputResolution(stateRef)
class Resolved(val stateAndRef: StateAndRef<ContractState>) : 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)"
}

View File

@ -106,7 +106,7 @@ object Models {
private val dependencyGraph = HashMap<KClass<*>, MutableSet<KClass<*>>>()
fun <M : Any> initModel(klass: KClass<M>) = modelStore.getOrPut(klass) { klass.java.newInstance() }
fun <M : Any> get(klass: KClass<M>, origin: KClass<*>) : M {
fun <M : Any> get(klass: KClass<M>, origin: KClass<*>): M {
dependencyGraph.getOrPut(origin) { mutableSetOf<KClass<*>>() }.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 <reified M : Any> get(origin: KClass<*>) : M = get(M::class, origin)
inline fun <reified M : Any> get(origin: KClass<*>): M = get(M::class, origin)
}
sealed class TrackedDelegate<M : Any>(val klass: KClass<M>) {
init { Models.initModel(klass) }
init {
Models.initModel(klass)
}
class ObservableDelegate<M : Any, T> (klass: KClass<M>, val observableProperty: (M) -> Observable<T>) : TrackedDelegate<M>(klass) {
class ObservableDelegate<M : Any, T>(klass: KClass<M>, val observableProperty: (M) -> Observable<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): Observable<T> {
return observableProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class ObserverDelegate<M : Any, T> (klass: KClass<M>, val observerProperty: (M) -> Observer<T>) : TrackedDelegate<M>(klass) {
class ObserverDelegate<M : Any, T>(klass: KClass<M>, val observerProperty: (M) -> Observer<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): Observer<T> {
return observerProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class SubjectDelegate<M : Any, T> (klass: KClass<M>, val subjectProperty: (M) -> Subject<T, T>) : TrackedDelegate<M>(klass) {
class SubjectDelegate<M : Any, T>(klass: KClass<M>, val subjectProperty: (M) -> Subject<T, T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): Subject<T, T> {
return subjectProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class EventStreamDelegate<M : Any, T> (klass: KClass<M>, val eventStreamProperty: (M) -> org.reactfx.EventStream<T>) : TrackedDelegate<M>(klass) {
class EventStreamDelegate<M : Any, T>(klass: KClass<M>, val eventStreamProperty: (M) -> org.reactfx.EventStream<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): org.reactfx.EventStream<T> {
return eventStreamProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class EventSinkDelegate<M : Any, T> (klass: KClass<M>, val eventSinkProperty: (M) -> org.reactfx.EventSink<T>) : TrackedDelegate<M>(klass) {
class EventSinkDelegate<M : Any, T>(klass: KClass<M>, val eventSinkProperty: (M) -> org.reactfx.EventSink<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): org.reactfx.EventSink<T> {
return eventSinkProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class ObservableValueDelegate<M : Any, T>(klass: KClass<M>, val observableValueProperty: (M) -> ObservableValue<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableValue<T> {
return observableValueProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class WritableValueDelegate<M : Any, T>(klass: KClass<M>, val writableValueProperty: (M) -> WritableValue<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): WritableValue<T> {
return writableValueProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class ObservableListDelegate<M : Any, T>(klass: KClass<M>, val observableListProperty: (M) -> ObservableList<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableList<T> {
return observableListProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class ObservableListReadOnlyDelegate<M : Any, out T>(klass: KClass<M>, val observableListReadOnlyProperty: (M) -> ObservableList<out T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): ObservableList<out T> {
return observableListReadOnlyProperty(Models.get(klass, thisRef.javaClass.kotlin))
}
}
class ObjectPropertyDelegate<M : Any, T>(klass: KClass<M>, val objectPropertyProperty: (M) -> ObjectProperty<T>) : TrackedDelegate<M>(klass) {
operator fun getValue(thisRef: Any, property: KProperty<*>): ObjectProperty<T> {
return objectPropertyProperty(Models.get(klass, thisRef.javaClass.kotlin))

View File

@ -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"

View File

@ -24,7 +24,7 @@ class ConcatenatedListTest {
fun <A> ConcatenatedList<A>.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)
}

View File

@ -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 {

View File

@ -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);

View File

@ -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 <A> ListenableFuture<A>.toObservable(): Observable<A> {
/** 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 <R> Path.readLines(charset: Charset = UTF_8, block: (Stream<String>) -> R): R = Files.lines(this, charset).use(block)
fun Path.writeLines(lines: Iterable<CharSequence>, charset: Charset = UTF_8, vararg options: OpenOption): Path = Files.write(this, lines, charset, *options)
@ -233,6 +236,7 @@ class ThreadBox<out T>(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<out A> private constructor(val value: A?, val error: Throwabl
companion object {
/** Runs the given lambda and wraps the result. */
inline fun <T : Any> catch(body: () -> T): ErrorOr<T> = try { ErrorOr(body()) } catch (t: Throwable) { ErrorOr.of(t) }
inline fun <T : Any> catch(body: () -> T): ErrorOr<T> = try {
ErrorOr(body())
} catch (t: Throwable) {
ErrorOr.of(t)
}
fun of(t: Throwable) = ErrorOr(null, t)
}

View File

@ -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")
@ -71,7 +73,7 @@ inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.select(signers: Collection<CompositeKey>?,
parties: Collection<Party>?) =
filter { it.value is T }.
filter { if (signers == null) true else it.signers.containsAll(signers)}.
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) }

View File

@ -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].
*/

View File

@ -379,7 +379,7 @@ open class BusinessCalendar private constructor(val holidayDates: List<LocalDate
*/
fun moveBusinessDays(date: LocalDate, direction: DateRollDirection, i: Int): LocalDate {
require(i >= 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,12 +462,13 @@ data class Commodity(val commodityCode: String,
*/
data class UniqueIdentifier(val externalId: String? = null, val id: UUID = UUID.randomUUID()) : Comparable<UniqueIdentifier> {
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
fun fromString(name: String): UniqueIdentifier
= UniqueIdentifier(null, UUID.fromString(name))
}

View File

@ -46,7 +46,9 @@ interface FungibleAsset<T> : OwnableState {
* A command stating that money has been withdrawn from the shared ledger and is now accounted for
* in some other way.
*/
interface Exit<T> : Commands { val amount: Amount<Issued<T>> }
interface Exit<T> : Commands {
val amount: Amount<Issued<T>>
}
}
}

View File

@ -26,7 +26,7 @@ interface NamedByHash {
/**
* Interface for state objects that support being netted with other state objects.
*/
interface BilateralNettableState<N: BilateralNettableState<N>> {
interface BilateralNettableState<N : BilateralNettableState<N>> {
/**
* 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<N: BilateralNettableState<N>> {
/**
* Interface for state objects that support being netted with other state objects.
*/
interface MultilateralNettableState<out T: Any> {
interface MultilateralNettableState<out T : Any> {
/**
* 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<out T: Any> {
val multilateralNetState: T
}
interface NettableState<N: BilateralNettableState<N>, T: Any>: BilateralNettableState<N>,
interface NettableState<N : BilateralNettableState<N>, T : Any> : BilateralNettableState<N>,
MultilateralNettableState<T>
/**
@ -154,6 +154,7 @@ data class TransactionState<out T : ContractState>(
/** Wraps the [ContractState] in a [TransactionState] object */
infix fun <T : ContractState> T.`with notary`(newNotary: Party) = withNotary(newNotary)
infix fun <T : ContractState> 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
}

View File

@ -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(

View File

@ -88,6 +88,7 @@ data class TransactionForContract(val inputs: List<ContractState>,
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<CompositeKey>) : 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

View File

@ -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,7 +15,7 @@ import net.corda.core.contracts.*
* @param commands commands extracted from the transaction, which are relevant to the
* clauses.
*/
fun <C: CommandData> verifyClause(tx: TransactionForContract,
fun <C : CommandData> verifyClause(tx: TransactionForContract,
clause: Clause<ContractState, C, Unit>,
commands: List<AuthenticatedObject<C>>) {
if (Clause.log.isTraceEnabled) {

View File

@ -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<in S : ContractState, C: CommandData, in K : Any>: Clause<S, C, K>() {
abstract class CompositeClause<in S : ContractState, C : CommandData, in K : Any> : Clause<S, C, K>() {
/** List of clauses under this composite clause */
abstract val clauses: List<Clause<S, C, K>>
override fun getExecutionPath(commands: List<AuthenticatedObject<C>>): List<Clause<*, *, *>>
= matchedClauses(commands).flatMap { it.getExecutionPath(commands) }
/** Determine which clauses are matched by the supplied commands */
abstract fun matchedClauses(commands: List<AuthenticatedObject<C>>): List<Clause<S, C, K>>
}

View File

@ -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<SecureHash>()
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)
}

View File

@ -52,7 +52,7 @@ class FlowLogicRefFactory(private val flowWhitelist: Map<String, Set<String>>) :
fun createKotlin(flowLogicClassName: String, args: Map<String, Any?>, attachments: List<SecureHash> = 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)

View File

@ -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.

View File

@ -201,13 +201,12 @@ class ImmutableClassSerializer<T : Any>(val klass: KClass<T>) : Serializer<T>()
}
}
inline fun <T> Kryo.useClassLoader(cl: ClassLoader, body: () -> T) : T {
inline fun <T> 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<Kryo>() {
override fun write(kryo: Kryo, output: Output, obj: Kryo) {
}
override fun read(kryo: Kryo, input: Input, type: Class<Kryo>): 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>): Any {
return if (kryo.references) {
super.read(kryo, input, type)
}
else {
} else {
ObjectInputStream(input).use(ObjectInputStream::readObject)
}
}
@ -455,7 +453,7 @@ object OrderedSerializer : Serializer<HashMap<Any, Any>>() {
val linkedMap = LinkedHashMap<Any, Any>()
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)
}

View File

@ -27,13 +27,13 @@ fun <A> Generator<A>.generateList(random: SourceOfRandomness, status: Generation
return arrayGenerator.generate(random, status) as List<A>
}
class PrivateKeyGenerator: Generator<PrivateKey>(PrivateKey::class.java) {
class PrivateKeyGenerator : Generator<PrivateKey>(PrivateKey::class.java) {
override fun generate(random: SourceOfRandomness, status: GenerationStatus): PrivateKey {
return entropyToKeyPair(random.nextBigInteger(32)).private
}
}
class PublicKeyGenerator: Generator<PublicKey>(PublicKey::class.java) {
class PublicKeyGenerator : Generator<PublicKey>(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>(CompositeKey::class.java)
}
}
class PartyGenerator: Generator<Party>(Party::class.java) {
class PartyGenerator : Generator<Party>(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>(PartyAndReference::class.java) {
class PartyAndReferenceGenerator : Generator<PartyAndReference>(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>(SecureHash::class.java) {
class SecureHashGenerator : Generator<SecureHash>(SecureHash::class.java) {
override fun generate(random: SourceOfRandomness, status: GenerationStatus): SecureHash {
return SecureHash.Companion.sha256(random.nextBytes(16))
}
}
class StateRefGenerator: Generator<StateRef>(StateRef::class.java) {
class StateRefGenerator : Generator<StateRef>(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>(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)]
}

View File

@ -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 <T : ContractState> outRef(index: Int) = StateAndRef(outputs[index] as TransactionState<T>, StateRef(id, index))

View File

@ -32,7 +32,7 @@ fun WireTransaction.calculateLeavesHashes(): List<SecureHash> {
fun SecureHash.hashConcat(other: SecureHash) = (this.bytes + other.bytes).sha256()
fun <T: Any> serializedHash(x: T): SecureHash {
fun <T : Any> serializedHash(x: T): SecureHash {
val kryo = extendKryoHash(createKryo()) //Dealing with HashMaps inside states.
return x.serialize(kryo).hash
}
@ -47,12 +47,12 @@ fun <T: Any> 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<SecureHash>,
val commands: List<Command>
) {
fun getFilteredHashes(): List<SecureHash>{
fun getFilteredHashes(): List<SecureHash> {
val resultHashes = ArrayList<SecureHash>()
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 <T: Any> genericFilter(elem: T): Boolean {
fun <T : Any> genericFilter(elem: T): Boolean {
return when (elem) {
is StateRef -> filterInputs(elem)
is TransactionState<*> -> filterOutputs(elem)

View File

@ -110,11 +110,13 @@ data class SignedTransaction(val txBits: SerializedBytes<WireTransaction>,
/** 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<DigitalSignature.WithKey>) = 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<DigitalSignature.WithKey>) = withAdditionalSignatures(sigList)

View File

@ -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" }

View File

@ -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<WireTransaction>? = null

View File

@ -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")
}

View File

@ -13,8 +13,13 @@ import kotlin.reflect.KClass
// logging at that level is enabled.
inline fun <reified T : Any> 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 {

View File

@ -109,7 +109,9 @@ object NonEmptySetSerializer : Serializer<NonEmptySet<Any>>() {
// 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
}
}

View File

@ -80,7 +80,9 @@ class ProgressTracker(vararg steps: Step) {
// This field won't be serialized.
private val _changes by TransientProperty { PublishSubject.create<Change>() }
private data class Child(val tracker: ProgressTracker, @Transient val subscription: Subscription?)
private val childProgressTrackers = HashMap<Step, Child>()
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

View File

@ -1,4 +1,5 @@
@file:JvmName("TestConstants")
package net.corda.core.utilities
import net.corda.core.crypto.*

View File

@ -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()
}

View File

@ -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 {

View File

@ -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)

View File

@ -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

View File

@ -18,7 +18,7 @@ internal fun matchedClause(counter: AtomicInteger? = null) = object : Clause<Con
/** A clause that can never be matched */
internal fun unmatchedClause(counter: AtomicInteger? = null) = object : Clause<ContractState, CommandData, Unit>() {
override val requiredCommands: Set<Class<out CommandData>> = setOf(object: CommandData {}.javaClass)
override val requiredCommands: Set<Class<out CommandData>> = setOf(object : CommandData {}.javaClass)
override fun verify(tx: TransactionForContract,
inputs: List<ContractState>,
outputs: List<ContractState>,

View File

@ -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<MerkleTreeException> { PartialMerkleTree.build(mt, hashes.subList(0,1)) }
assertFailsWith<MerkleTreeException> { 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())

View File

@ -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

View File

@ -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()

View File

@ -35,6 +35,7 @@ class TransactionSerializationTests {
override fun withNewOwner(newOwner: CompositeKey) = Pair(Commands.Move(), copy(owner = newOwner))
}
interface Commands : CommandData {
class Move() : TypeOnlyCommandData(), Commands
}

View File

@ -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() }
}

View File

@ -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.

View File

@ -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.*;
/**
@ -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;
}
}
}

View File

@ -132,7 +132,7 @@ class CommercialPaper : Contract {
}
}
class Move: Clause<State, Commands, Issued<Terms>>() {
class Move : Clause<State, Commands, Issued<Terms>>() {
override val requiredCommands: Set<Class<out CommandData>> = setOf(Commands.Move::class.java)
override fun verify(tx: TransactionForContract,
@ -152,7 +152,7 @@ class CommercialPaper : Contract {
}
}
class Redeem(): Clause<State, Commands, Issued<Terms>>() {
class Redeem() : Clause<State, Commands, Issued<Terms>>() {
override val requiredCommands: Set<Class<out CommandData>> = setOf(Commands.Redeem::class.java)
override fun verify(tx: TransactionForContract,

View File

@ -161,6 +161,7 @@ class Cash : OnLedgerAsset<Currency, Cash.Commands, Cash.State>() {
override fun deriveState(txState: TransactionState<State>, amount: Amount<Issued<Currency>>, owner: CompositeKey)
= txState.copy(data = txState.data.copy(amount = amount, owner = owner))
override fun generateExitCommand(amount: Amount<Issued<Currency>>) = Commands.Exit(amount)
override fun generateIssueCommand() = Commands.Issue()
override fun generateMoveCommand() = Commands.Move()

View File

@ -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
@ -135,8 +134,10 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.Commands, C
*/
data class Exit(override val amount: Amount<Issued<Commodity>>) : Commands, FungibleAsset.Commands.Exit<Commodity>
}
override fun verify(tx: TransactionForContract)
= verifyClause(tx, Clauses.Group(), extractCommands(tx.commands))
override fun extractCommands(commands: Collection<AuthenticatedObject<CommandData>>): List<AuthenticatedObject<Commands>>
= commands.select<CommodityContract.Commands>()
@ -160,6 +161,7 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.Commands, C
override fun deriveState(txState: TransactionState<State>, amount: Amount<Issued<Commodity>>, owner: CompositeKey)
= txState.copy(data = txState.data.copy(amount = amount, owner = owner))
override fun generateExitCommand(amount: Amount<Issued<Commodity>>) = Commands.Exit(amount)
override fun generateIssueCommand() = Commands.Issue()
override fun generateMoveCommand() = Commands.Move()

View File

@ -81,7 +81,7 @@ class Obligation<P> : Contract {
/**
* Clause for supporting netting of obligations.
*/
class Net<C: CommandData, P> : NetClause<C, P>() {
class Net<C : CommandData, P> : NetClause<C, P>() {
val lifecycleClause = Clauses.VerifyLifecycle<ContractState, C, Unit, P>()
override fun toString(): String = "Net obligations"
@ -203,13 +203,14 @@ class Obligation<P> : Contract {
* any lifecycle change clause, which is the only clause that involve
* non-standard lifecycle states on input/output.
*/
class VerifyLifecycle<S: ContractState, C: CommandData, T: Any, P> : Clause<S, C, T>() {
class VerifyLifecycle<S : ContractState, C : CommandData, T : Any, P> : Clause<S, C, T>() {
override fun verify(tx: TransactionForContract,
inputs: List<S>,
outputs: List<S>,
commands: List<AuthenticatedObject<C>>,
groupingKey: T?): Set<C>
= verify(inputs.filterIsInstance<State<P>>(), outputs.filterIsInstance<State<P>>())
private fun verify(inputs: List<State<P>>,
outputs: List<State<P>>): Set<C> {
requireThat {
@ -704,6 +705,7 @@ infix fun <T> Obligation.State<T>.`owned by`(owner: CompositeKey) = copy(benefic
infix fun <T> Obligation.State<T>.`issued by`(party: Party) = copy(obligor = party)
// For Java users:
@Suppress("unused") fun <T> Obligation.State<T>.ownedBy(owner: CompositeKey) = copy(beneficiary = owner)
@Suppress("unused") fun <T> Obligation.State<T>.issuedBy(party: Party) = copy(obligor = party)
/** A randomly generated key. */

View File

@ -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<T : Any, C: CommandData, S : FungibleAsset<T>> : Contract {
abstract class OnLedgerAsset<T : Any, C : CommandData, S : FungibleAsset<T>> : Contract {
abstract fun extractCommands(commands: Collection<AuthenticatedObject<CommandData>>): Collection<AuthenticatedObject<C>>
abstract val conserveClause: AbstractConserveAmount<S, C, T>

View File

@ -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<in S: ContractState, C: CommandData, T: Any>(
abstract class AbstractIssue<in S : ContractState, C : CommandData, T : Any>(
val sum: List<S>.() -> Amount<Issued<T>>,
val sumOrZero: List<S>.(token: Issued<T>) -> Amount<Issued<T>>
) : Clause<S, C, Issued<T>>() {

View File

@ -42,7 +42,7 @@ data class MultilateralNetState<P>(
* Clause for netting contract states. Currently only supports obligation contract.
*/
// TODO: Make this usable for any nettable contract states
open class NetClause<C: CommandData, P> : Clause<ContractState, C, Unit>() {
open class NetClause<C : CommandData, P> : Clause<ContractState, C, Unit>() {
override val requiredCommands: Set<Class<out CommandData>> = setOf(Obligation.Commands.Net::class.java)
@Suppress("ConvertLambdaToReference")

View File

@ -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

View File

@ -63,7 +63,7 @@ class CommandGenerator : Generator<Command>(Command::class.java) {
}
}
class WiredTransactionGenerator: Generator<WireTransaction>(WireTransaction::class.java) {
class WiredTransactionGenerator : Generator<WireTransaction>(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>(WireTransaction::cla
}
}
class SignedTransactionGenerator: Generator<SignedTransaction>(SignedTransaction::class.java) {
class SignedTransactionGenerator : Generator<SignedTransaction>(SignedTransaction::class.java) {
override fun generate(random: SourceOfRandomness, status: GenerationStatus): SignedTransaction {
val wireTransaction = WiredTransactionGenerator().generate(random, status)
return SignedTransaction(

View File

@ -1,4 +1,5 @@
@file:JvmName("VaultFiller")
package net.corda.contracts.testing
import net.corda.contracts.asset.Cash

View File

@ -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.*;

View File

@ -665,6 +665,7 @@ class ObligationTests {
}
}
@Test
fun `exit multiple product obligations`() {
// Multi-product case.

View File

@ -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.Entry<String, String>>): Map<String, String> {
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<String>): Set<String> {
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

View File

@ -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> T attribute(Map.Entry<String, T> 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<Path> classpath = augmentClasspath((List<Path>) 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<Path> augmentClasspath(List<Path> classpath, String dirName) {
File dir = new File(dirName);
if(!dir.exists()) {
if (!dir.exists()) {
dir.mkdir();
}

View File

@ -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))
@ -233,6 +234,7 @@ open class DriverDSL(
val clients = LinkedList<NodeMessagingClient>()
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 <A> pickA(array: Array<A>): 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()

View File

@ -41,6 +41,7 @@ class CordaRPCOpsImpl(
Pair(vault.states.toList(), updates)
}
}
override fun verifiedTransactions(): Pair<List<SignedTransaction>, Observable<SignedTransaction>> {
return databaseTransaction(database) {
services.storageService.validatedTransactions.track()

View File

@ -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)
}

View File

@ -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()
}

View File

@ -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())
}
}

View File

@ -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<NodeSchedulerService>()
@ -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)
}
}

View File

@ -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)"
}

View File

@ -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<NodeRegistration>?, 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)"
}
/**

View File

@ -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.*

View File

@ -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

View File

@ -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

View File

@ -442,7 +442,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal,
interface SessionMessage
interface ExistingSessionMessage: SessionMessage {
interface ExistingSessionMessage : SessionMessage {
val recipientSessionId: Long
}

View File

@ -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<String> {
fun select(txnId: SecureHash): Iterable<String> {
return table.select { table.txnId.eq(txnId) }.map { row -> row[table.note] }.toSet().asIterable()
}
}

View File

@ -139,6 +139,7 @@ class StrandLocalTransactionManager(initWithDatabase: Database) : TransactionMan
// Composite columns for use with below Exposed helpers.
data class PartyColumns(val name: Column<String>, val owningKey: Column<CompositeKey>)
data class StateRefColumns(val txId: Column<SecureHash>, val index: Column<Int>)
data class TxnNoteColumns(val txId: Column<SecureHash>, val note: Column<String>)

View File

@ -58,7 +58,7 @@ fun bytesToBlob(value: SerializedBytes<*>, finalizables: MutableList<() -> Unit>
fun serializeToBlob(value: Any, finalizables: MutableList<() -> Unit>): Blob = bytesToBlob(value.serialize(), finalizables)
fun <T: Any> bytesFromBlob(blob: Blob): SerializedBytes<T> {
fun <T : Any> bytesFromBlob(blob: Blob): SerializedBytes<T> {
try {
return SerializedBytes(blob.getBytes(0, blob.length().toInt()))
} finally {
@ -194,10 +194,10 @@ abstract class AbstractJDBCHashSet<K : Any, out T : JDBCHashedTable>(protected v
*/
abstract class AbstractJDBCHashMap<K : Any, V : Any, out T : JDBCHashedTable>(val table: T,
val loadOnInit: Boolean = false,
val maxBuckets: Int = 256) : MutableMap<K, V>, AbstractMap<K,V>() {
val maxBuckets: Int = 256) : MutableMap<K, V>, AbstractMap<K, V>() {
companion object {
protected val log = loggerFor<AbstractJDBCHashMap<*,*,*>>()
protected val log = loggerFor<AbstractJDBCHashMap<*, *, *>>()
private const val INITIAL_CAPACITY: Int = 16
private const val LOAD_FACTOR: Float = 0.75f

View File

@ -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

View File

@ -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<Certificate>?
}

View File

@ -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) {

View File

@ -413,7 +413,7 @@ class TwoPartyTradeFlowTests {
val sellerId: StateMachineRunId
)
private fun runBuyerAndSeller(assetToSell: StateAndRef<OwnableState>) : RunResult {
private fun runBuyerAndSeller(assetToSell: StateAndRef<OwnableState>): RunResult {
val buyerFuture = bobNode.initiateSingleShotFlow(Seller::class) { otherParty ->
Buyer(otherParty, notaryNode.info.notaryIdentity, 1000.DOLLARS, CommercialPaper.State::class.java)
}.map { it.fsm }

View File

@ -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)

View File

@ -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<String>) {

View File

@ -1,4 +1,5 @@
@file:JvmName("IRSDemo")
package net.corda.irs
import com.google.common.net.HostAndPort

View File

@ -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)

View File

@ -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.")
}

View File

@ -52,6 +52,7 @@ open class Rate(val ratioUnit: RatioUnit? = null) {
* for equality.
*/
override fun hashCode() = ratioUnit?.hashCode() ?: 0
override fun toString() = ratioUnit.toString()
}

View File

@ -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<Class<*>> = listOf(Service::class.java)
}

View File

@ -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

View File

@ -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,

View File

@ -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<Class<*>> = listOf(Service::class.java)
}

View File

@ -13,17 +13,17 @@ private val client by lazy {
.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))

View File

@ -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",

View File

@ -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<IllegalArgumentException> { oracle.sign(ftx1, wtx1.id) }
tx.addCommand(Cash.Commands.Move(), ALICE_PUBKEY)
val wtx2 = tx.toWireTransaction()

Some files were not shown because too many files have changed in this diff Show More