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

@ -324,8 +324,8 @@ class CordaRPCClientImpl(private val session: ClientSession,
val c = synchronized(this) { consumer }
if (c != null) {
rpcLog.warn("A hot observable returned from an RPC ($rpcName) was never subscribed to or explicitly closed. " +
"This wastes server-side resources because it was queueing observations for retrieval. " +
"It is being closed now, but please adjust your code to cast the observable to AutoCloseable and then close it explicitly.", rpcLocation)
"This wastes server-side resources because it was queueing observations for retrieval. " +
"It is being closed now, but please adjust your code to cast the observable to AutoCloseable and then close it explicitly.", rpcLocation)
c.close()
}
}

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

@ -9,7 +9,7 @@ fun generateCurrency(): Generator<Currency> {
}
fun <T : Any> generateAmount(min: Long, max: Long, tokenGenerator: Generator<T>): Generator<Amount<T>> {
return Generator.longRange(min, max).combine(tokenGenerator) { quantity, token -> Amount(quantity, token) }
return Generator.longRange(min, max).combine(tokenGenerator) { quantity, token -> Amount(quantity, token) }
}
fun generateCurrencyAmount(min: Long, max: Long): Generator<Amount<Currency>> {

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 {
@ -23,7 +22,7 @@ class LeftOuterJoinedMapTest {
dogs = FXCollections.observableArrayList<Dog>(Dog("Scruffy", owner = "Bob"))
joinedList = people.leftOuterJoin(dogs, Person::name, Dog::owner) { person, dogs -> Pair(person, dogs) }
// We replay the nested observable as well
replayedList = ReplayedList(joinedList.map { Pair(it.first, ReplayedList(it.second)) })
replayedList = ReplayedList(joinedList.map { Pair(it.first, ReplayedList(it.second)) })
}
// TODO perhaps these are too brittle because they test indices that are not stable. Use Expect dsl?

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

@ -34,7 +34,7 @@ import kotlin.concurrent.withLock
import kotlin.reflect.KProperty
val Int.days: Duration get() = Duration.ofDays(this.toLong())
@Suppress("unused") // It's here for completeness
@Suppress("unused") // It's here for completeness
val Int.hours: Duration get() = Duration.ofHours(this.toLong())
val Int.minutes: Duration get() = Duration.ofMinutes(this.toLong())
val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong())
@ -51,6 +51,7 @@ fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else
/** Like the + operator but throws an exception in case of integer overflow. */
infix fun Int.checkedAdd(b: Int) = Math.addExact(this, b)
/** Like the + operator but throws an exception in case of integer overflow. */
@Suppress("unused")
infix fun Long.checkedAdd(b: Long) = Math.addExact(this, b)
@ -125,6 +126,7 @@ fun <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")
@ -63,17 +65,17 @@ inline fun <R> requireThat(body: Requirements.() -> R) = Requirements.body()
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.select(signer: CompositeKey? = null,
party: Party? = null) =
filter { it.value is T }.
filter { if (signer == null) true else signer in it.signers }.
filter { if (party == null) true else party in it.signingParties }.
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
filter { if (signer == null) true else signer in it.signers }.
filter { if (party == null) true else party in it.signingParties }.
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
/** Filters the command list by type, parties and public keys all at once. */
inline fun <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 (parties == null) true else it.signingParties.containsAll(parties) }.
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
filter { if (signers == null) true else it.signers.containsAll(signers) }.
filter { if (parties == null) true else it.signingParties.containsAll(parties) }.
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.requireSingleCommand() = try {
select<T>().single()

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

@ -61,7 +61,7 @@ data class Amount<T>(val quantity: Long, val token: T) : Comparable<Amount<T>> {
operator fun times(other: Long): Amount<T> = Amount(Math.multiplyExact(quantity, other), token)
operator fun div(other: Int): Amount<T> = Amount(quantity / other, token)
operator fun times(other: Int): Amount<T> = Amount(Math.multiplyExact(quantity, other.toLong()), token)
override fun toString(): String = (BigDecimal(quantity).divide(BigDecimal(100))).setScale(2).toPlainString() + " " + token
override fun compareTo(other: Amount<T>): Int {
@ -267,7 +267,7 @@ enum class Frequency(val annualCompoundCount: Int) {
}
@Suppress("unused") // This utility may be useful in future. TODO: Review before API stability guarantees in place.
@Suppress("unused") // This utility may be useful in future. TODO: Review before API stability guarantees in place.
fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = accordingToCalendar.isWorkingDay(this)
// TODO: Make Calendar data come from an oracle
@ -379,7 +379,7 @@ open class BusinessCalendar private constructor(val holidayDates: List<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,13 +462,14 @@ 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
= UniqueIdentifier(null, UUID.fromString(name))
fun fromString(name: String): UniqueIdentifier
= UniqueIdentifier(null, UUID.fromString(name))
}
override fun compareTo(other: UniqueIdentifier): Int = id.compareTo(other.id)

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

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

@ -10,7 +10,7 @@ abstract class GroupClauseVerifier<S : ContractState, C : CommandData, K : Any>(
abstract fun groupStates(tx: TransactionForContract): List<TransactionForContract.InOutGroup<S, K>>
override fun getExecutionPath(commands: List<AuthenticatedObject<C>>): List<Clause<*, *, *>>
= clause.getExecutionPath(commands)
= clause.getExecutionPath(commands)
override fun verify(tx: TransactionForContract,
inputs: List<ContractState>,

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

@ -17,7 +17,7 @@ data class WorldCoordinate(val latitude: Double, val longitude: Double) {
* to infinity. Google Maps, for example, uses a square map image, and square maps yield latitude extents
* of 85.0511 to -85.0511 = arctan(sinh(π)).
*/
@Suppress("unused") // Used from the visualiser GUI.
@Suppress("unused") // Used from the visualiser GUI.
fun project(screenWidth: Double, screenHeight: Double, topLatitude: Double, bottomLatitude: Double,
leftLongitude: Double, rightLongitude: Double): Pair<Double, Double> {
require(latitude in bottomLatitude..topLatitude)

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

@ -215,7 +215,7 @@ abstract class AbstractStateReplacementFlow<T> {
/** Thrown when a participant refuses the proposed state replacement */
class StateReplacementRefused(val identity: Party, val state: StateRef, val detail: String?) {
override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided")
override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided")
}
class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error")
class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error")

View File

@ -34,7 +34,7 @@ object NotaryChangeFlow : AbstractStateReplacementFlow<Party>() {
: AbstractStateReplacementFlow.Instigator<T, Party>(originalState, newNotary, progressTracker) {
override fun assembleProposal(stateRef: StateRef, modification: Party, stx: SignedTransaction): AbstractStateReplacementFlow.Proposal<Party>
= Proposal(stateRef, modification, stx)
= Proposal(stateRef, modification, stx)
override fun assembleTx(): Pair<SignedTransaction, List<CompositeKey>> {
val state = originalState.state

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

@ -275,7 +275,7 @@ object TwoPartyDealFlow {
override val progressTracker: ProgressTracker = Primary.tracker()) : Primary() {
override val notaryNode: NodeInfo get() =
serviceHub.networkMapCache.notaryNodes.filter { it.notaryIdentity == payload.notary }.single()
serviceHub.networkMapCache.notaryNodes.filter { it.notaryIdentity == payload.notary }.single()
}
/**

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

@ -10,7 +10,7 @@ class FlowLogicRefTest {
data class ParamType1(val value: Int)
data class ParamType2(val value: String)
@Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection.
@Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection.
class KotlinFlowLogic(A: ParamType1, b: ParamType2) : FlowLogic<Unit>() {
constructor() : this(ParamType1(1), ParamType2("2"))

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.*;
/**
@ -173,10 +161,10 @@ public class JavaCommercialPaper implements Contract {
@NotNull
@Override
public Set<Commands> verify(@NotNull TransactionForContract tx,
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
AuthenticatedObject<Commands.Move> cmd = requireSingleCommand(tx.getCommands(), Commands.Move.class);
// There should be only a single input due to aggregation above
State input = single(inputs);
@ -204,10 +192,10 @@ public class JavaCommercialPaper implements Contract {
@NotNull
@Override
public Set<Commands> verify(@NotNull TransactionForContract tx,
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
AuthenticatedObject<Commands.Redeem> cmd = requireSingleCommand(tx.getCommands(), Commands.Redeem.class);
// There should be only a single input due to aggregation above
@ -246,10 +234,10 @@ public class JavaCommercialPaper implements Contract {
@NotNull
@Override
public Set<Commands> verify(@NotNull TransactionForContract tx,
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
@NotNull List<? extends State> inputs,
@NotNull List<? extends State> outputs,
@NotNull List<? extends AuthenticatedObject<? extends Commands>> commands,
@NotNull State groupingKey) {
AuthenticatedObject<Commands.Issue> cmd = requireSingleCommand(tx.getCommands(), Commands.Issue.class);
State output = single(outputs);
Timestamp timestampCommand = tx.getTimestamp();
@ -274,17 +262,23 @@ public class JavaCommercialPaper implements Contract {
public interface Commands extends CommandData {
class Move implements Commands {
@Override
public boolean equals(Object obj) { return obj instanceof Move; }
public boolean equals(Object obj) {
return obj instanceof Move;
}
}
class Redeem implements Commands {
@Override
public boolean equals(Object obj) { return obj instanceof Redeem; }
public boolean equals(Object obj) {
return obj instanceof Redeem;
}
}
class Issue implements Commands {
@Override
public boolean equals(Object obj) { return obj instanceof Issue; }
public boolean equals(Object obj) {
return obj instanceof Issue;
}
}
}

View File

@ -51,8 +51,8 @@ class CommercialPaper : Contract {
override val legalContractReference: SecureHash = SecureHash.sha256("https://en.wikipedia.org/wiki/Commercial_paper")
data class Terms(
val asset: Issued<Currency>,
val maturityDate: Instant
val asset: Issued<Currency>,
val maturityDate: Instant
)
override fun verify(tx: TransactionForContract) = verifyClause(tx, Clauses.Group(), tx.commands.select<Commands>())
@ -103,10 +103,10 @@ class CommercialPaper : Contract {
interface Clauses {
class Group : GroupClauseVerifier<State, Commands, Issued<Terms>>(
AnyComposition(
Redeem(),
Move(),
Issue())) {
AnyComposition(
Redeem(),
Move(),
Issue())) {
override fun groupStates(tx: TransactionForContract): List<TransactionForContract.InOutGroup<State, Issued<Terms>>>
= tx.groupStates<State, Issued<Terms>> { it.token }
}
@ -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

@ -86,7 +86,7 @@ class Cash : OnLedgerAsset<Currency, Cash.Commands, Cash.State>() {
override val encumbrance: Int? = null
) : FungibleAsset<Currency>, QueryableState {
constructor(deposit: PartyAndReference, amount: Amount<Currency>, owner: CompositeKey)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
override val exitKeys = setOf(owner, amount.token.issuer.party.owningKey)
override val contract = CASH_PROGRAM_ID
@ -160,13 +160,14 @@ class Cash : OnLedgerAsset<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))
= 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()
override fun verify(tx: TransactionForContract)
= verifyClause(tx, Clauses.Group(), extractCommands(tx.commands))
= verifyClause(tx, Clauses.Group(), extractCommands(tx.commands))
}
// Small DSL extensions.

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
@ -98,14 +97,14 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.Commands, C
override val owner: CompositeKey
) : FungibleAsset<Commodity> {
constructor(deposit: PartyAndReference, amount: Amount<Commodity>, owner: CompositeKey)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
override val contract = COMMODITY_PROGRAM_ID
override val exitKeys = Collections.singleton(owner)
override val participants = listOf(owner)
override fun move(newAmount: Amount<Issued<Commodity>>, newOwner: CompositeKey): FungibleAsset<Commodity>
= copy(amount = amount.copy(newAmount.quantity, amount.token), owner = newOwner)
= copy(amount = amount.copy(newAmount.quantity, amount.token), owner = newOwner)
override fun toString() = "Commodity($amount at ${amount.token.issuer} owned by $owner)"
@ -135,8 +134,10 @@ class CommodityContract : OnLedgerAsset<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,15 +203,16 @@ 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>>())
= verify(inputs.filterIsInstance<State<P>>(), outputs.filterIsInstance<State<P>>())
private fun verify(inputs: List<State<P>>,
outputs: List<State<P>>): Set<C> {
outputs: List<State<P>>): Set<C> {
requireThat {
"all inputs are in the normal state " by inputs.all { it.lifecycle == Lifecycle.NORMAL }
"all outputs are in the normal state " by outputs.all { it.lifecycle == Lifecycle.NORMAL }
@ -373,9 +374,9 @@ class Obligation<P> : Contract {
*/
@VisibleForTesting
private fun verifySetLifecycleCommand(inputs: List<FungibleAsset<Terms<P>>>,
outputs: List<FungibleAsset<Terms<P>>>,
tx: TransactionForContract,
setLifecycleCommand: AuthenticatedObject<Commands.SetLifecycle>) {
outputs: List<FungibleAsset<Terms<P>>>,
tx: TransactionForContract,
setLifecycleCommand: AuthenticatedObject<Commands.SetLifecycle>) {
// Default must not change anything except lifecycle, so number of inputs and outputs must match
// exactly.
require(inputs.size == outputs.size) { "Number of inputs and outputs must match" }
@ -704,6 +705,7 @@ infix fun <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>
@ -40,7 +40,7 @@ abstract class OnLedgerAsset<T : Any, C: CommandData, S : FungibleAsset<T>> : Co
*/
fun generateExit(tx: TransactionBuilder, amountIssued: Amount<Issued<T>>,
assetStates: List<StateAndRef<S>>): CompositeKey
= conserveClause.generateExit(tx, amountIssued, assetStates,
= conserveClause.generateExit(tx, amountIssued, assetStates,
deriveState = { state, amount, owner -> deriveState(state, amount, owner) },
generateMoveCommand = { -> generateMoveCommand() },
generateExitCommand = { amount -> generateExitCommand(amount) }

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))
@ -128,7 +129,7 @@ sealed class PortAllocation {
* @param isDebug Indicates whether the spawned nodes should start in jdwt debug mode.
* @param dsl The dsl itself.
* @return The value returned in the [dsl] closure.
*/
*/
fun <A> driver(
driverDirectory: Path = Paths.get("build", getTimestampAsDirectoryName()),
portAllocation: PortAllocation = PortAllocation.Incremental(10000),
@ -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()
@ -67,7 +68,7 @@ class CordaRPCOpsImpl(
override fun addVaultTransactionNote(txnId: SecureHash, txnNote: String) {
return databaseTransaction(database) {
services.vaultService.addNoteToTransaction(txnId, txnNote)
services.vaultService.addNoteToTransaction(txnId, txnNote)
}
}

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

@ -53,14 +53,14 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration {
val notaryNodeAddress: HostAndPort? by config.getOrElse { null }
val notaryClusterAddresses: List<HostAndPort> = config.getListOrElse<String>("notaryClusterAddresses") { emptyList<String>() }.map { HostAndPort.fromString(it) }
val rpcUsers: List<User> =
config.getListOrElse<Config>("rpcUsers") { emptyList() }
.map {
val username = it.getString("user")
require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" }
val password = it.getString("password")
val permissions = it.getListOrElse<String>("permissions") { emptyList() }.toSet()
User(username, password, permissions)
}
config.getListOrElse<Config>("rpcUsers") { emptyList() }
.map {
val username = it.getString("user")
require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" }
val password = it.getString("password")
val permissions = it.getListOrElse<String>("permissions") { emptyList() }.toSet()
User(username, password, permissions)
}
fun createNode(): Node {
// This is a sanity feature do not remove.
@ -74,7 +74,7 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration {
}
if (networkMapAddress == null) advertisedServices.add(ServiceInfo(NetworkMapService.type))
val networkMapMessageAddress: SingleMessageRecipient? = if (networkMapAddress == null) null else NodeMessagingClient.makeNetworkMapAddress(networkMapAddress!!)
return Node(this, networkMapMessageAddress, advertisedServices, if(useTestClock == true) TestClock() else NodeClock())
return Node(this, networkMapMessageAddress, advertisedServices, if (useTestClock == true) TestClock() else NodeClock())
}
}

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)"
}
@ -117,10 +117,10 @@ abstract class ArtemisMessagingComponent() : SingletonSerializeAsToken() {
*/
fun checkStorePasswords() {
config.keyStorePath.read {
KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray())
KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray())
}
config.trustStorePath.read {
KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray())
KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray())
}
}

View File

@ -104,13 +104,13 @@ class NodeMessagingClient(override val config: NodeConfiguration,
}
private val processedMessages: MutableSet<UUID> = Collections.synchronizedSet(
object : AbstractJDBCHashSet<UUID, Table>(Table, loadOnInit = true) {
override fun elementFromRow(row: ResultRow): UUID = row[table.uuid]
object : AbstractJDBCHashSet<UUID, Table>(Table, loadOnInit = true) {
override fun elementFromRow(row: ResultRow): UUID = row[table.uuid]
override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) {
insert[table.uuid] = entry
}
})
override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) {
insert[table.uuid] = entry
}
})
fun start(rpcOps: RPCOps, userService: RPCUserService) {
state.locked {

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

@ -164,10 +164,10 @@ object JsonSupport {
}
object PublicKeySerializer : JsonSerializer<EdDSAPublicKey>() {
override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) {
check(obj.params == ed25519Curve)
generator.writeString(obj.toBase58String())
}
override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) {
check(obj.params == ed25519Curve)
generator.writeString(obj.toBase58String())
}
}
object PublicKeyDeserializer : JsonDeserializer<EdDSAPublicKey>() {

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
@ -107,7 +107,7 @@ class CertificateSigner(val config: NodeConfiguration, val certService: Certific
requestIdStore.writeLines(listOf(requestId))
requestId
} else {
requestIdStore.readLines { it.findFirst().get() }
requestIdStore.readLines { it.findFirst().get() }
}
}
}

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

@ -305,9 +305,9 @@ class TwoPartyTradeFlowTests {
// Bob answers with the transactions that are now all verifiable, as Alice bottomed out.
// Bob's transactions are valid, so she commits to the database
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[0].id]!!)),
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[2].id]!!)),
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[1].id]!!)),
// Now she verifies the transaction is contract-valid (not signature valid) which means
// looking up the states again.
@ -413,7 +413,7 @@ class TwoPartyTradeFlowTests {
val sellerId: StateMachineRunId
)
private fun runBuyerAndSeller(assetToSell: StateAndRef<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 }
@ -488,7 +488,7 @@ class TwoPartyTradeFlowTests {
if (!withError)
command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Issue() }
else
// Put a broken command on so at least a signature is created
// Put a broken command on so at least a signature is created
command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Move() }
timestamp(TEST_TX_TIME)
if (withError) {

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

@ -11,7 +11,7 @@ import org.graphstream.graph.Node
import org.graphstream.graph.implementations.SingleGraph
import kotlin.reflect.memberProperties
@Suppress("unused") // TODO: Re-evaluate by EOY2016 if this code is still useful and if not, delete.
@Suppress("unused") // TODO: Re-evaluate by EOY2016 if this code is still useful and if not, delete.
class GraphVisualiser(val dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>) {
companion object {
val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText()

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

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