Minor: fix various inspector warnings and delete some dead code.

This commit is contained in:
Mike Hearn 2016-08-08 16:19:28 +02:00
parent 2bc77ae095
commit 87047c8996
80 changed files with 210 additions and 288 deletions

View File

@ -24,7 +24,7 @@ import static kotlin.collections.CollectionsKt.*;
*/
public class JavaCommercialPaper extends ClauseVerifier {
//public static SecureHash JCP_PROGRAM_ID = SecureHash.sha256("java commercial paper (this should be a bytecode hash)");
public static Contract JCP_PROGRAM_ID = new JavaCommercialPaper();
private static final Contract JCP_PROGRAM_ID = new JavaCommercialPaper();
public static class State implements ContractState, ICommercialPaperState {
private PartyAndReference issuance;
@ -326,7 +326,7 @@ public class JavaCommercialPaper extends ClauseVerifier {
public Collection<AuthenticatedObject<CommandData>> extractCommands(@NotNull TransactionForContract tx) {
return tx.getCommands()
.stream()
.filter((AuthenticatedObject<CommandData> command) -> { return command.getValue() instanceof Commands; })
.filter((AuthenticatedObject<CommandData> command) -> command.getValue() instanceof Commands)
.collect(Collectors.toList());
}

View File

@ -205,7 +205,7 @@ class CommercialPaper : ClauseVerifier() {
@Throws(InsufficientBalanceException::class)
fun generateRedeem(tx: TransactionBuilder, paper: StateAndRef<State>, wallet: List<StateAndRef<Cash.State>>) {
// Add the cash movement using the states in our wallet.
val amount = paper.state.data.faceValue.let { amount -> Amount<Currency>(amount.quantity, amount.token.product) }
val amount = paper.state.data.faceValue.let { amount -> Amount(amount.quantity, amount.token.product) }
Cash().generateSpend(tx, amount, paper.state.data.owner, wallet)
tx.addInputState(paper)
tx.addCommand(CommercialPaper.Commands.Redeem(paper.state.notary), paper.state.data.owner)

View File

@ -55,7 +55,7 @@ class CommercialPaperLegacy : Contract {
override fun verify(tx: TransactionForContract) {
// Group by everything except owner: any modification to the CP at all is considered changing it fundamentally.
val groups = tx.groupStates() { it: State -> it.withoutOwner() }
val groups = tx.groupStates(State::withoutOwner)
// There are two possible things that can be done with this CP. The first is trading it. The second is redeeming
// it for cash on or after the maturity date.

View File

@ -79,7 +79,7 @@ class ReferenceRate(val oracle: String, val tenor: Tenor, val name: String) : Fl
}
// TODO: For further discussion.
operator fun Amount<Currency>.times(other: RatioUnit): Amount<Currency> = Amount<Currency>((BigDecimal(this.quantity).multiply(other.value)).longValueExact(), this.token)
operator fun Amount<Currency>.times(other: RatioUnit): Amount<Currency> = Amount((BigDecimal(this.quantity).multiply(other.value)).longValueExact(), this.token)
//operator fun Amount<Currency>.times(other: FixedRate): Amount<Currency> = Amount<Currency>((BigDecimal(this.pennies).multiply(other.value)).longValueExact(), this.currency)
//fun Amount<Currency>.times(other: InterestRateSwap.RatioUnit): Amount<Currency> = Amount<Currency>((BigDecimal(this.pennies).multiply(other.value)).longValueExact(), this.currency)

View File

@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount
import com.r3corda.contracts.clause.AbstractIssue
import com.r3corda.contracts.clause.NoZeroSizedOutputs
import com.r3corda.core.contracts.*
import com.r3corda.core.contracts.clauses.*
import com.r3corda.core.contracts.clauses.GroupClauseVerifier
import com.r3corda.core.contracts.clauses.MatchBehaviour
import com.r3corda.core.crypto.*
import com.r3corda.core.node.services.Wallet
import com.r3corda.core.utilities.Emoji
@ -81,7 +82,7 @@ class Cash : OnLedgerAsset<Currency, Cash.State>() {
override val owner: PublicKey
) : FungibleAsset<Currency> {
constructor(deposit: PartyAndReference, amount: Amount<Currency>, owner: PublicKey)
: this(Amount(amount.quantity, Issued<Currency>(deposit, amount.token)), owner)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
override val deposit = amount.token.issuer
override val exitKeys = setOf(deposit.party.owningKey)
@ -165,7 +166,7 @@ fun Iterable<ContractState>.sumCashOrNull(): Amount<Issued<Currency>>? = filterI
/** Sums the cash states in the list, returning zero of the given currency+issuer if there are none. */
fun Iterable<ContractState>.sumCashOrZero(currency: Issued<Currency>): Amount<Issued<Currency>> {
return filterIsInstance<Cash.State>().map { it.amount }.sumOrZero<Issued<Currency>>(currency)
return filterIsInstance<Cash.State>().map { it.amount }.sumOrZero(currency)
}
/**

View File

@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount
import com.r3corda.contracts.clause.AbstractIssue
import com.r3corda.contracts.clause.NoZeroSizedOutputs
import com.r3corda.core.contracts.*
import com.r3corda.core.contracts.clauses.*
import com.r3corda.core.contracts.clauses.GroupClauseVerifier
import com.r3corda.core.contracts.clauses.MatchBehaviour
import com.r3corda.core.crypto.Party
import com.r3corda.core.crypto.SecureHash
import com.r3corda.core.crypto.newSecureRandom
@ -107,7 +108,7 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.State>() {
override val owner: PublicKey
) : FungibleAsset<Commodity> {
constructor(deposit: PartyAndReference, amount: Amount<Commodity>, owner: PublicKey)
: this(Amount(amount.quantity, Issued<Commodity>(deposit, amount.token)), owner)
: this(Amount(amount.quantity, Issued(deposit, amount.token)), owner)
override val deposit = amount.token.issuer
override val contract = COMMODITY_PROGRAM_ID
@ -182,7 +183,7 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.State>() {
fun Iterable<ContractState>.sumCommodities() = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrThrow()
/** Sums the cash states in the list, returning null if there are none. */
fun Iterable<ContractState>.sumCommoditiesOrNull() = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrNull()
@Suppress("unused") fun Iterable<ContractState>.sumCommoditiesOrNull() = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrNull()
/** Sums the cash states in the list, returning zero of the given currency if there are none. */
fun Iterable<ContractState>.sumCommoditiesOrZero(currency: Issued<Commodity>) = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrZero<Issued<Commodity>>(currency)
fun Iterable<ContractState>.sumCommoditiesOrZero(currency: Issued<Commodity>) = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrZero(currency)

View File

@ -2,7 +2,6 @@ package com.r3corda.contracts.asset
import com.r3corda.core.contracts.*
import java.security.PublicKey
import java.util.*
class InsufficientBalanceException(val amountMissing: Amount<*>) : Exception() {
override fun toString() = "Insufficient balance, missing $amountMissing"

View File

@ -181,7 +181,7 @@ class Obligation<P> : ClauseVerifier() {
// Settle commands exclude all other commands, so we don't need to check for contracts moving at the same
// time.
"amounts paid must match recipients to settle" by inputs.map { it.owner }.containsAll(amountReceivedByOwner.keys)
"amount in settle command ${command.value.amount} matches settled total ${totalAmountSettled}" by (command.value.amount == totalAmountSettled)
"amount in settle command ${command.value.amount} matches settled total $totalAmountSettled" by (command.value.amount == totalAmountSettled)
"signatures are present from all obligors" by command.signers.containsAll(requiredSigners)
"there are no zero sized inputs" by inputs.none { it.amount.quantity == 0L }
"at obligor ${obligor.name} the obligations after settlement balance" by
@ -384,7 +384,7 @@ class Obligation<P> : ClauseVerifier() {
* A default command mutates inputs and produces identical outputs, except that the lifecycle changes.
*/
@VisibleForTesting
protected fun verifySetLifecycleCommand(inputs: List<FungibleAsset<Terms<P>>>,
private fun verifySetLifecycleCommand(inputs: List<FungibleAsset<Terms<P>>>,
outputs: List<FungibleAsset<Terms<P>>>,
tx: TransactionForContract,
setLifecycleCommand: AuthenticatedObject<Commands.SetLifecycle>) {
@ -439,7 +439,7 @@ class Obligation<P> : ClauseVerifier() {
"signer is in the state parties" by (signer in netState!!.partyKeys)
}
val out = states.reduce { stateA, stateB -> stateA.net(stateB) }
val out = states.reduce(State<P>::net)
if (out.quantity > 0L)
tx.addOutputState(out)
tx.addCommand(Commands.Net(NetType.PAYMENT), signer)
@ -456,11 +456,12 @@ class Obligation<P> : ClauseVerifier() {
* the responsibility of the caller to check that they do not exit funds held by others.
* @return the public key of the assets issuer, who must sign the transaction for it to be valid.
*/
@Suppress("unused")
fun generateExit(tx: TransactionBuilder, amountIssued: Amount<Issued<Terms<P>>>,
changeKey: PublicKey, assetStates: List<StateAndRef<Obligation.State<P>>>): PublicKey
= Clauses.ConserveAmount<P>().generateExit(tx, amountIssued, changeKey, assetStates,
deriveState = { state, amount, owner -> state.copy(data = state.data.move(amount, owner)) },
generateExitCommand = { amount -> Commands.Exit<P>(amount) }
generateExitCommand = { amount -> Commands.Exit(amount) }
)
/**
@ -525,7 +526,7 @@ class Obligation<P> : ClauseVerifier() {
Lifecycle.DEFAULTED -> Lifecycle.NORMAL
Lifecycle.NORMAL -> Lifecycle.DEFAULTED
}
require(states.all { it.lifecycle == existingLifecycle }) { "initial lifecycle must be ${existingLifecycle} for all input states" }
require(states.all { it.lifecycle == existingLifecycle }) { "initial lifecycle must be $existingLifecycle for all input states" }
// Produce a new set of states
val groups = statesAndRefs.groupBy { it.state.data.issuanceDef }
@ -713,8 +714,8 @@ infix fun <T> Obligation.State<T>.between(parties: Pair<Party, PublicKey>) = cop
infix fun <T> Obligation.State<T>.`owned by`(owner: PublicKey) = copy(beneficiary = owner)
infix fun <T> Obligation.State<T>.`issued by`(party: Party) = copy(obligor = party)
// For Java users:
fun <T> Obligation.State<T>.ownedBy(owner: PublicKey) = copy(beneficiary = owner)
fun <T> Obligation.State<T>.issuedBy(party: Party) = copy(obligor = party)
@Suppress("unused") fun <T> Obligation.State<T>.ownedBy(owner: PublicKey) = copy(beneficiary = owner)
@Suppress("unused") fun <T> Obligation.State<T>.issuedBy(party: Party) = copy(obligor = party)
val Issued<Currency>.OBLIGATION_DEF: Obligation.Terms<Currency>
get() = Obligation.Terms(nonEmptySetOf(Cash().legalContractReference), nonEmptySetOf(this), TEST_TX_TIME)

View File

@ -2,10 +2,9 @@ package com.r3corda.contracts.asset
import com.r3corda.contracts.clause.AbstractConserveAmount
import com.r3corda.core.contracts.*
import com.r3corda.core.contracts.clauses.*
import com.r3corda.core.crypto.*
import com.r3corda.core.contracts.clauses.ClauseVerifier
import com.r3corda.core.crypto.Party
import java.security.PublicKey
import java.util.*
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//

View File

@ -75,7 +75,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, Amount(amount.quantity, currency))
val takeChangeFrom = gathered.lastOrNull()
val change = if (takeChangeFrom != null && gatheredAmount > amount) {
Amount<Issued<T>>(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef)
Amount(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef)
} else {
null
}
@ -139,7 +139,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, amount)
val takeChangeFrom = gathered.firstOrNull()
val change = if (takeChangeFrom != null && gatheredAmount > amount) {
Amount<Issued<T>>(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef)
Amount(gatheredAmount.quantity - amount.quantity, takeChangeFrom.state.data.issuanceDef)
} else {
null
}
@ -175,7 +175,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
outputs: List<S>,
commands: Collection<AuthenticatedObject<CommandData>>,
token: Issued<T>): Set<CommandData> {
val inputAmount: Amount<Issued<T>> = inputs.sumFungibleOrNull<T>() ?: throw IllegalArgumentException("there is at least one asset input for group ${token}")
val inputAmount: Amount<Issued<T>> = inputs.sumFungibleOrNull<T>() ?: throw IllegalArgumentException("there is at least one asset input for group $token")
val deposit = token.issuer
val outputAmount: Amount<Issued<T>> = outputs.sumFungibleOrZero(token)

View File

@ -14,7 +14,7 @@ import com.r3corda.core.contracts.clauses.MatchBehaviour
* @param sumOrZero function to convert a list of states into an amount of the token, and returns zero if there are
* no states in the list. Takes in an instance of the token definition for constructing the zero amount if needed.
*/
abstract class AbstractIssue<S: ContractState, T: Any>(
abstract class AbstractIssue<in S: ContractState, T: Any>(
val sum: List<S>.() -> Amount<Issued<T>>,
val sumOrZero: List<S>.(token: Issued<T>) -> Amount<Issued<T>>
) : GroupClause<S, Issued<T>> {

View File

@ -51,6 +51,7 @@ open class NetClause<P> : SingleClause {
override val requiredCommands: Set<Class<out CommandData>>
get() = setOf(Obligation.Commands.Net::class.java)
@Suppress("ConvertLambdaToReference")
override fun verify(tx: TransactionForContract, commands: Collection<AuthenticatedObject<CommandData>>): Set<CommandData> {
val command = commands.requireSingleCommand<Obligation.Commands.Net>()
val groups = when (command.value.type) {

View File

@ -9,7 +9,7 @@ import com.r3corda.core.contracts.clauses.MatchBehaviour
* Clause for fungible asset contracts, which enforces that no output state should have
* a balance of zero.
*/
open class NoZeroSizedOutputs<S: FungibleAsset<T>, T: Any> : GroupClause<S, Issued<T>> {
open class NoZeroSizedOutputs<in S: FungibleAsset<T>, T: Any> : GroupClause<S, Issued<T>> {
override val ifMatched: MatchBehaviour
get() = MatchBehaviour.CONTINUE
override val ifNotMatched: MatchBehaviour

View File

@ -48,7 +48,7 @@ object TwoPartyTradeProtocol {
val TOPIC = "platform.trade"
class UnacceptablePriceException(val givenPrice: Amount<Currency>) : Exception()
class UnacceptablePriceException(val givenPrice: Amount<Currency>) : Exception("Unacceptable price: $givenPrice")
class AssetMismatchException(val expectedTypeName: String, val typeName: String) : Exception() {
override fun toString() = "The submitted asset didn't match the expected type: $expectedTypeName vs $typeName"
}

View File

@ -12,10 +12,10 @@ import static com.r3corda.core.testing.CoreTestUtils.*;
* This is an incomplete Java replica of CashTests.kt to show how to use the Java test DSL
*/
public class CashTestsJava {
private OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1});
private PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef);
private Cash.State inState = new Cash.State(issuedBy(DOLLARS(1000), defaultIssuer), getDUMMY_PUBKEY_1());
private Cash.State outState = new Cash.State(inState.getAmount(), getDUMMY_PUBKEY_2());
private final OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1});
private final PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef);
private final Cash.State inState = new Cash.State(issuedBy(DOLLARS(1000), defaultIssuer), getDUMMY_PUBKEY_1());
private final Cash.State outState = new Cash.State(inState.getAmount(), getDUMMY_PUBKEY_2());
@Test
public void trivial() {

View File

@ -268,8 +268,8 @@ class IRSTests {
LocalDate.of(2015, 12, 8) to "0.55",
LocalDate.of(2016, 3, 8) to "0.644")
for (it in fixings) {
newCalculation = newCalculation.applyFixing(it.key, FixedRate(PercentageRatioUnit(it.value)))
for ((key, value) in fixings) {
newCalculation = newCalculation.applyFixing(key, FixedRate(PercentageRatioUnit(value)))
}
val newIRS = InterestRateSwap.State(irs.fixedLeg, irs.floatingLeg, newCalculation, irs.common)

View File

@ -22,8 +22,8 @@ class ObligationTests {
val defaultIssuer = MEGA_CORP.ref(defaultRef)
val oneMillionDollars = 1000000.DOLLARS `issued by` defaultIssuer
val trustedCashContract = nonEmptySetOf(SecureHash.Companion.randomSHA256() as SecureHash)
val megaIssuedDollars = nonEmptySetOf(Issued<Currency>(defaultIssuer, USD))
val megaIssuedPounds = nonEmptySetOf(Issued<Currency>(defaultIssuer, GBP))
val megaIssuedDollars = nonEmptySetOf(Issued(defaultIssuer, USD))
val megaIssuedPounds = nonEmptySetOf(Issued(defaultIssuer, GBP))
val fivePm = TEST_TX_TIME.truncatedTo(ChronoUnit.DAYS).plus(17, ChronoUnit.HOURS)
val sixPm = fivePm.plus(1, ChronoUnit.HOURS)
val megaCorpDollarSettlement = Obligation.Terms(trustedCashContract, megaIssuedDollars, fivePm)
@ -181,7 +181,7 @@ class ObligationTests {
this `fails with` "All commands must be matched at end of execution."
}
tweak {
command(MEGA_CORP_PUBKEY) { Obligation.Commands.Exit<Currency>(inState.amount / 2) }
command(MEGA_CORP_PUBKEY) { Obligation.Commands.Exit(inState.amount / 2) }
this `fails with` "All commands must be matched at end of execution."
}
this.verifies()
@ -451,7 +451,7 @@ class ObligationTests {
input("Alice's $1,000,000 obligation to Bob")
input("Alice's $1,000,000")
output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY }
command(ALICE_PUBKEY) { Obligation.Commands.Settle<Currency>(Amount(oneMillionDollars.quantity, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
this.verifies()
}
@ -465,7 +465,7 @@ class ObligationTests {
input(500000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY)
output("Alice's $500,000 obligation to Bob") { halfAMillionDollars.OBLIGATION between Pair(ALICE, BOB_PUBKEY) }
output("Bob's $500,000") { 500000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY }
command(ALICE_PUBKEY) { Obligation.Commands.Settle<Currency>(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
this.verifies()
}
@ -478,7 +478,7 @@ class ObligationTests {
input(defaultedObligation) // Alice's defaulted $1,000,000 obligation to Bob
input(1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY)
output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY }
command(ALICE_PUBKEY) { Obligation.Commands.Settle<Currency>(Amount(oneMillionDollars.quantity, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
this `fails with` "all inputs are in the normal state"
}
@ -491,7 +491,7 @@ class ObligationTests {
input("Alice's $1,000,000 obligation to Bob")
input("Alice's $1,000,000")
output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_PUBKEY }
command(ALICE_PUBKEY) { Obligation.Commands.Settle<Currency>(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) }
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
this `fails with` "amount in settle command"
}
@ -502,7 +502,7 @@ class ObligationTests {
fun `commodity settlement`() {
val defaultFcoj = FCOJ `issued by` defaultIssuer
val oneUnitFcoj = Amount(1, defaultFcoj)
val obligationDef = Obligation.Terms<Commodity>(nonEmptySetOf(CommodityContract().legalContractReference), nonEmptySetOf(defaultFcoj), TEST_TX_TIME)
val obligationDef = Obligation.Terms(nonEmptySetOf(CommodityContract().legalContractReference), nonEmptySetOf(defaultFcoj), TEST_TX_TIME)
val oneUnitFcojObligation = Obligation.State(Obligation.Lifecycle.NORMAL, ALICE,
obligationDef, oneUnitFcoj.quantity, NullPublicKey)
// Try settling a simple commodity obligation
@ -515,7 +515,7 @@ class ObligationTests {
input("Alice's 1 FCOJ obligation to Bob")
input("Alice's 1 FCOJ")
output("Bob's 1 FCOJ") { CommodityContract.State(oneUnitFcoj, BOB_PUBKEY) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle<Commodity>(Amount(oneUnitFcoj.quantity, oneUnitFcojObligation.issuanceDef)) }
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneUnitFcoj.quantity, oneUnitFcojObligation.issuanceDef)) }
command(ALICE_PUBKEY) { CommodityContract.Commands.Move(Obligation<Commodity>().legalContractReference) }
verifies()
}
@ -646,13 +646,13 @@ class ObligationTests {
output { outState.copy(quantity = inState.quantity - 200.DOLLARS.quantity) }
tweak {
command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit<Currency>(Amount(100.DOLLARS.quantity, inState.issuanceDef)) }
command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(100.DOLLARS.quantity, inState.issuanceDef)) }
command(DUMMY_PUBKEY_1) { Obligation.Commands.Move() }
this `fails with` "the amounts balance"
}
tweak {
command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit<Currency>(Amount(200.DOLLARS.quantity, inState.issuanceDef)) }
command(DUMMY_PUBKEY_1) { Obligation.Commands.Exit(Amount(200.DOLLARS.quantity, inState.issuanceDef)) }
this `fails with` "required com.r3corda.contracts.asset.FungibleAsset.Commands.Move command"
tweak {
@ -817,7 +817,7 @@ class ObligationTests {
5000.DOLLARS.quantity, MINI_CORP_PUBKEY)
val amount = fiveKDollarsFromMegaToMini.amount
val expected = mapOf(Pair(Pair(MEGA_CORP_PUBKEY, MINI_CORP_PUBKEY), Amount(amount.quantity, amount.token.product)))
val actual = extractAmountsDue<Currency>(megaCorpDollarSettlement, listOf(fiveKDollarsFromMegaToMini))
val actual = extractAmountsDue(megaCorpDollarSettlement, listOf(fiveKDollarsFromMegaToMini))
assertEquals(expected, actual)
}
@ -843,7 +843,7 @@ class ObligationTests {
val expected = mapOf(
Pair(Pair(BOB_PUBKEY, ALICE_PUBKEY), Amount(100000000, GBP))
)
val actual = netAmountsDue<Currency>(balanced)
val actual = netAmountsDue(balanced)
assertEquals(expected, actual)
}

View File

@ -28,7 +28,7 @@ import java.util.*;
* same as the original author of the R3 repository.
*/
public class Base58 {
public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private static final char ENCODED_ZERO = ALPHABET[0];
private static final int[] INDEXES = new int[128];

View File

@ -20,14 +20,18 @@ import kotlin.concurrent.withLock
import kotlin.reflect.KProperty
val Int.days: Duration get() = Duration.ofDays(this.toLong())
@Suppress("unused") // It's here for completeness
val Int.hours: Duration get() = Duration.ofHours(this.toLong())
@Suppress("unused") // It's here for completeness
val Int.minutes: Duration get() = Duration.ofMinutes(this.toLong())
val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong())
val Int.bd: BigDecimal get() = BigDecimal(this)
val Double.bd: BigDecimal get() = BigDecimal(this)
val String.bd: BigDecimal get() = BigDecimal(this)
val Long.bd: BigDecimal get() = BigDecimal(this)
// TODO: Review by EOY2016 if we ever found these utilities helpful.
@Suppress("unused") val Int.bd: BigDecimal get() = BigDecimal(this)
@Suppress("unused") val Double.bd: BigDecimal get() = BigDecimal(this)
@Suppress("unused") val String.bd: BigDecimal get() = BigDecimal(this)
@Suppress("unused") val Long.bd: BigDecimal get() = BigDecimal(this)
fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else take(maxWidth - 1) + ""
@ -149,8 +153,7 @@ fun <T> logElapsedTime(label: String, logger: Logger? = null, body: () -> T): T
*
* val ii = state.locked { i }
*/
class ThreadBox<out T>(content: T, val lock: ReentrantLock = ReentrantLock()) {
val content = content
class ThreadBox<out T>(val content: T, val lock: ReentrantLock = ReentrantLock()) {
inline fun <R> locked(body: T.() -> R): R = lock.withLock { body(content) }
inline fun <R> alreadyLocked(body: T.() -> R): R {
check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." })

View File

@ -41,8 +41,8 @@ val Int.FCOJ: Amount<Commodity> get() = FCOJ(this)
infix fun Currency.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
infix fun Commodity.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
infix fun Amount<Currency>.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued<Currency>(deposit, this)
infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued<Commodity>(deposit, this)
infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued(deposit, this)
infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued(deposit, this)
infix fun Amount<Currency>.issuedBy(deposit: PartyAndReference) = Amount(quantity, token.issuedBy(deposit))
//// Requirements /////////////////////////////////////////////////////////////////////////////////////////////////////
@ -64,7 +64,7 @@ inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>
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<T>(it.signers, it.signingParties, it.value as T) }
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
/** Filters the command list by type, parties and public keys all at once. */
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.select(signers: Collection<PublicKey>?,
@ -72,7 +72,7 @@ inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>
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<T>(it.signers, it.signingParties, it.value as T) }
map { AuthenticatedObject(it.signers, it.signingParties, it.value as T) }
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.requireSingleCommand() = try {
select<T>().single()
@ -99,7 +99,7 @@ fun List<AuthenticatedObject<CommandData>>.getTimestampBy(timestampingAuthority:
fun List<AuthenticatedObject<CommandData>>.getTimestampByName(vararg names: String): TimestampCommand? {
val timestampCmd = filter { it.value is TimestampCommand }.singleOrNull() ?: return null
val tsaNames = timestampCmd.signingParties.map { it.name.toLowerCase() }
val acceptableNames = names.map { it.toLowerCase() }
val acceptableNames = names.map(String::toLowerCase)
val acceptableNameFound = tsaNames.intersect(acceptableNames).isNotEmpty()
if (acceptableNameFound)
return timestampCmd.value as TimestampCommand

View File

@ -71,7 +71,7 @@ data class Amount<T>(val quantity: Long, val token: T) : Comparable<Amount<T>> {
fun <T> Iterable<Amount<T>>.sumOrNull() = if (!iterator().hasNext()) null else sumOrThrow()
fun <T> Iterable<Amount<T>>.sumOrThrow() = reduce { left, right -> left + right }
fun <T> Iterable<Amount<T>>.sumOrZero(currency: T) = if (iterator().hasNext()) sumOrThrow() else Amount<T>(0, currency)
fun <T> Iterable<Amount<T>>.sumOrZero(currency: T) = if (iterator().hasNext()) sumOrThrow() else Amount(0, currency)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
@ -136,7 +136,7 @@ data class Tenor(val name: String) {
return daysToMaturity.toInt()
}
override fun toString(): String = "$name"
override fun toString(): String = name
enum class TimeUnit(val code: String) {
Day("D"), Week("W"), Month("M"), Year("Y")
@ -237,6 +237,7 @@ enum class PaymentRule {
* Frequency at which an event occurs - the enumerator also casts to an integer specifying the number of times per year
* that would divide into (eg annually = 1, semiannual = 2, monthly = 12 etc).
*/
@Suppress("unused") // TODO: Revisit post-Vega and see if annualCompoundCount is still needed.
enum class Frequency(val annualCompoundCount: Int) {
Annual(1) {
override fun offset(d: LocalDate, n: Long) = d.plusYears(1 * n)
@ -265,6 +266,7 @@ enum class Frequency(val annualCompoundCount: Int) {
}
@Suppress("unused") // This utility may be useful in future. TODO: Review before API stability guarantees in place.
fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = accordingToCalendar.isWorkingDay(this)
// TODO: Make Calendar data come from an oracle
@ -274,7 +276,7 @@ fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = acc
* typical feature of financial contracts, in which a business may not want a payment event to fall on a day when
* no staff are around to handle problems.
*/
open class BusinessCalendar private constructor(val calendars: Array<out String>, val holidayDates: List<LocalDate>) {
open class BusinessCalendar private constructor(val holidayDates: List<LocalDate>) {
class UnknownCalendar(name: String) : Exception("$name not found")
companion object {
@ -288,7 +290,7 @@ open class BusinessCalendar private constructor(val calendars: Array<out String>
fun parseDateFromString(it: String) = LocalDate.parse(it, DateTimeFormatter.ISO_LOCAL_DATE)
/** Returns a business calendar that combines all the named holiday calendars into one list of holiday dates. */
fun getInstance(vararg calname: String) = BusinessCalendar(calname,
fun getInstance(vararg calname: String) = BusinessCalendar(
calname.flatMap { (TEST_CALENDAR_DATA[it] ?: throw UnknownCalendar(it)).split(",") }.
toSet().
map { parseDateFromString(it) }.
@ -426,7 +428,7 @@ data class Commodity(val symbol: String,
val commodityCode: String = symbol,
val defaultFractionDigits: Int = 0) {
companion object {
private val registry = mapOf<String, Commodity>(
private val registry = mapOf(
Pair("FCOJ", Commodity("FCOJ", "Frozen concentrated orange juice"))
)
fun getInstance(symbol: String): Commodity?

View File

@ -40,7 +40,7 @@ interface BilateralNettableState<N: BilateralNettableState<N>> {
/**
* Interface for state objects that support being netted with other state objects.
*/
interface MultilateralNettableState<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.

View File

@ -21,11 +21,6 @@ data class TransactionForContract(val inputs: List<ContractState>,
override fun hashCode() = origHash.hashCode()
override fun equals(other: Any?) = other is TransactionForContract && other.origHash == origHash
@Deprecated("This property was renamed to inputs", ReplaceWith("inputs"))
val inStates: List<ContractState> get() = inputs
@Deprecated("This property was renamed to outputs", ReplaceWith("outputs"))
val outStates: List<ContractState> get() = outputs
/**
* Given a type and a function that returns a grouping key, associates inputs and outputs together so that they
* can be processed as one. The grouping key is any arbitrary object that can act as a map key (so must implement

View File

@ -19,7 +19,7 @@ interface GroupVerify<in S, in T : Any> {
token: T): Set<CommandData>
}
interface GroupClause<S : ContractState, T : Any> : Clause, GroupVerify<S, T>
interface GroupClause<in S : ContractState, in T : Any> : Clause, GroupVerify<S, T>
abstract class GroupClauseVerifier<S : ContractState, T : Any> : SingleClause {
abstract val clauses: List<GroupClause<S, T>>

View File

@ -66,10 +66,9 @@ fun OpaqueBytes.sha256(): SecureHash.SHA256 = SecureHash.sha256(this.bits)
* signature. It isn't used currently, but experience from Bitcoin suggests such a feature is useful, especially when
* building partially signed transactions.
*/
open class DigitalSignature(bits: ByteArray, val covering: Int = 0) : OpaqueBytes(bits) {
open class DigitalSignature(bits: ByteArray) : OpaqueBytes(bits) {
/** A digital signature that identifies who the public key is owned by. */
open class WithKey(val by: PublicKey, bits: ByteArray, covering: Int = 0) : DigitalSignature(bits, covering) {
open class WithKey(val by: PublicKey, bits: ByteArray, covering: Int = 0) : DigitalSignature(bits) {
fun verifyWithECDSA(content: ByteArray) = by.verifyWithECDSA(content, this)
fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bits, this)
}

View File

@ -1,6 +1,5 @@
package com.r3corda.core.messaging
import com.google.common.util.concurrent.ListenableFuture
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.serialization.DeserializeAsKotlinObjectDef
import com.r3corda.core.serialization.serialize
@ -148,7 +147,7 @@ data class TopicSession(val topic: String, val sessionID: Long = DEFAULT_SESSION
}
fun isBlank() = topic.isBlank() && sessionID == DEFAULT_SESSION_ID
override fun toString(): String = "${topic}.${sessionID}"
override fun toString(): String = "$topic.$sessionID"
}
/**

View File

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

View File

@ -46,7 +46,7 @@ class ProtocolLogicRefFactory(private val protocolWhitelist: Map<String, Set<Str
return
}
// TODO: make this specific to the attachments in the [AppContext] by including [SecureHash] in whitelist check
require(protocolWhitelist[className]!!.contains(argClassName)) { "Args to ${className} must have types on the args whitelist: $argClassName" }
require(protocolWhitelist[className]!!.contains(argClassName)) { "Args to $className must have types on the args whitelist: $argClassName" }
}
/**

View File

@ -18,7 +18,6 @@ import com.r3corda.core.utilities.NonEmptySetSerializer
import de.javakaffee.kryoserializers.ArraysAsListSerializer
import net.i2p.crypto.eddsa.EdDSAPrivateKey
import net.i2p.crypto.eddsa.EdDSAPublicKey
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
import org.objenesis.strategy.StdInstantiatorStrategy
@ -414,9 +413,7 @@ object ReferencesAwareJavaSerializer : JavaSerializer() {
super.read(kryo, input, type)
}
else {
ObjectInputStream(input).use {
it.readObject()
}
ObjectInputStream(input).use(ObjectInputStream::readObject)
}
}
}

View File

@ -105,7 +105,7 @@ data class SingletonSerializationToken private constructor(private val className
constructor(toBeTokenized: SerializeAsToken) : this(toBeTokenized.javaClass.name)
override fun fromToken(context: SerializeAsTokenContext): Any = context.tokenToTokenized[this] ?:
throw IllegalStateException("Unable to find tokenized instance of ${className} in context $context")
throw IllegalStateException("Unable to find tokenized instance of $className in context $context")
companion object {
fun registerWithContext(token: SingletonSerializationToken, toBeTokenized: SerializeAsToken, context: SerializeAsTokenContext): SerializationToken =
@ -126,7 +126,7 @@ data class SingletonSerializationToken private constructor(private val className
* to indicate which instance the token is a serialized form of.
*/
abstract class SingletonSerializeAsToken() : SerializeAsToken {
@Suppress("LeakingThis")
private val token = SingletonSerializationToken(this)
override fun toToken(context: SerializeAsTokenContext) = SingletonSerializationToken.registerWithContext(token, this, context)

View File

@ -52,7 +52,6 @@ val DUMMY_PUBKEY_2: PublicKey get() = DummyPublicKey("x2")
val DUMMY_KEY_1: KeyPair by lazy { generateKeyPair() }
val DUMMY_KEY_2: KeyPair by lazy { generateKeyPair() }
val DUMMY_KEY_3: KeyPair by lazy { generateKeyPair() }
val ALICE_KEY: KeyPair by lazy { generateKeyPair() }
val ALICE_PUBKEY: PublicKey get() = ALICE_KEY.public

View File

@ -150,12 +150,6 @@ class LedgerDSL<out T : TransactionDSLInterpreter, out L : LedgerDSLInterpreter<
inline fun <reified S : ContractState> String.output(): S =
outputStateAndRef<S>().state.data
/**
* Retrieves the output [StateRef] based on the label.
* @see OutputStateLookup.retrieveOutputStateAndRef
*/
fun String.outputRef(): StateRef = outputStateAndRef<ContractState>().ref
/**
* @see OutputStateLookup.retrieveOutputStateAndRef
*/

View File

@ -40,7 +40,7 @@ import java.util.*
message = "ledger doesn't nest, use tweak",
replaceWith = ReplaceWith("tweak"),
level = DeprecationLevel.ERROR)
@Suppress("UNUSED_PARAMETER")
@Suppress("UNUSED_PARAMETER", "unused")
fun TransactionDSLInterpreter.ledger(
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
}
@ -49,7 +49,7 @@ fun TransactionDSLInterpreter.ledger(
message = "transaction doesn't nest, use tweak",
replaceWith = ReplaceWith("tweak"),
level = DeprecationLevel.ERROR)
@Suppress("UNUSED_PARAMETER")
@Suppress("UNUSED_PARAMETER", "unused")
fun TransactionDSLInterpreter.transaction(
dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail) {
}
@ -58,7 +58,7 @@ fun TransactionDSLInterpreter.transaction(
message = "ledger doesn't nest, use tweak",
replaceWith = ReplaceWith("tweak"),
level = DeprecationLevel.ERROR)
@Suppress("UNUSED_PARAMETER")
@Suppress("UNUSED_PARAMETER", "unused")
fun LedgerDSLInterpreter<TransactionDSLInterpreter>.ledger(
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
}

View File

@ -12,7 +12,7 @@ import java.util.*
* The underlying set is exposed for Kryo to access, but should not be accessed directly.
*/
class NonEmptySet<T>(initial: T) : MutableSet<T> {
private val set: MutableSet<T> = HashSet<T>()
private val set: MutableSet<T> = HashSet()
init {
set.add(initial)
@ -28,7 +28,7 @@ class NonEmptySet<T>(initial: T) : MutableSet<T> {
override fun containsAll(elements: Collection<T>): Boolean = set.containsAll(elements)
override fun isEmpty(): Boolean = false
override fun iterator(): MutableIterator<T> = Iterator<T>(set.iterator())
override fun iterator(): MutableIterator<T> = Iterator(set.iterator())
override fun remove(element: T): Boolean =
// Test either there's more than one element, or the removal is a no-op
@ -65,7 +65,7 @@ class NonEmptySet<T>(initial: T) : MutableSet<T> {
override fun equals(other: Any?): Boolean =
if (other is Set<*>)
// Delegate down to the wrapped set's equals() function
set.equals(other)
set == other
else
false
@ -84,7 +84,7 @@ class NonEmptySet<T>(initial: T) : MutableSet<T> {
}
fun <T> nonEmptySetOf(initial: T, vararg elements: T): NonEmptySet<T> {
val set = NonEmptySet<T>(initial)
val set = NonEmptySet(initial)
// We add the first element twice, but it's a set, so who cares
set.addAll(elements)
return set

View File

@ -151,6 +151,7 @@ class ProgressTracker(vararg steps: Step) {
var parent: ProgressTracker? = null
private set
@Suppress("unused") // TODO: Review by EOY2016 if this property is useful anywhere.
/** Walks up the tree to find the top level tracker. If this is the top level tracker, returns 'this' */
val topLevelTracker: ProgressTracker
get() {

View File

@ -1,50 +0,0 @@
package com.r3corda.core.utilities
import org.slf4j.Logger
import java.util.*
import javax.annotation.concurrent.ThreadSafe
/**
* A RecordingMap wraps a regular Map<K, V> and records the sequence of gets and puts to it. This is useful in
* white box unit tests to ensure that code is accessing a data store as much as you expect.
*
* Note: although this class itself thread safe, if the underlying map is not, then this class loses its thread safety.
*/
@ThreadSafe
class RecordingMap<K, V>(private val wrappedMap: MutableMap<K, V>,
private val logger: Logger = loggerFor<RecordingMap<K, V>>()) : MutableMap<K, V> by wrappedMap {
// If/when Kotlin supports data classes inside sealed classes, that would be preferable to this.
interface Record
data class Get<out K>(val key: K) : Record
data class Put<out K, out V>(val key: K, val value: V) : Record
private val _records = Collections.synchronizedList(ArrayList<Record>())
/** Returns a snapshot of the set of records */
val records: List<Record> get() = _records.toList()
fun clearRecords() = _records.clear()
override fun get(key: K): V? {
_records.add(Get(key))
logger.trace("GET ${logger.name} : $key = ${wrappedMap[key]}")
return wrappedMap[key]
}
override fun put(key: K, value: V): V? {
_records.add(Put(key, value))
logger.trace("PUT ${logger.name} : $key = $value")
return wrappedMap.put(key, value)
}
override fun putAll(from: Map<out K, V>) {
for ((k, v) in from) {
put(k, v)
}
}
fun putAllUnrecorded(from: Map<out K, V>) {
wrappedMap.putAll(from)
}
}

View File

@ -35,9 +35,9 @@ abstract class AbstractStateReplacementProtocol<T> {
override val replyToParty: Party,
override val sessionID: Long) : PartyRequestMessage
abstract class Instigator<S : ContractState, T>(val originalState: StateAndRef<S>,
val modification: T,
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<StateAndRef<S>>() {
abstract class Instigator<out S : ContractState, T>(val originalState: StateAndRef<S>,
val modification: T,
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<StateAndRef<S>>() {
companion object {
object SIGNING : ProgressTracker.Step("Requesting signatures from other parties")
@ -117,10 +117,10 @@ abstract class AbstractStateReplacementProtocol<T> {
}
}
abstract class Acceptor<T>(val otherSide: Party,
val sessionIdForSend: Long,
val sessionIdForReceive: Long,
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<Unit>() {
abstract class Acceptor<in T>(val otherSide: Party,
val sessionIdForSend: Long,
val sessionIdForReceive: Long,
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<Unit>() {
companion object {
object VERIFYING : ProgressTracker.Step("Verifying state replacement proposal")
@ -220,11 +220,9 @@ abstract class AbstractStateReplacementProtocol<T> {
}
/** Thrown when a participant refuses proposed the state replacement */
/** Thrown when a participant refuses the proposed state replacement */
class StateReplacementRefused(val identity: Party, val state: StateRef, val detail: String?) {
override fun toString(): String
= "A participant $identity refused to change state $state"
override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided")
}
class StateReplacementException(val error: StateReplacementRefused)
: Exception("State change failed - $error")
class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error")

View File

@ -11,6 +11,7 @@ import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.random63BitValue
import com.r3corda.core.utilities.ProgressTracker
import com.r3corda.core.utilities.suggestInterestRateAnnouncementTimeWindow
import com.r3corda.protocols.RatesFixProtocol.FixOutOfRange
import java.math.BigDecimal
import java.time.Duration
import java.time.Instant
@ -46,7 +47,7 @@ open class RatesFixProtocol(protected val tx: TransactionBuilder,
override val topic: String get() = TOPIC
class FixOutOfRange(val byAmount: BigDecimal) : Exception()
class FixOutOfRange(@Suppress("unused") val byAmount: BigDecimal) : Exception("Fix out of range by $byAmount")
data class QueryRequest(val queries: List<FixOf>, override val replyToParty: Party, override val sessionID: Long, val deadline: Instant) : PartyRequestMessage
data class SignRequest(val tx: WireTransaction, override val replyToParty: Party, override val sessionID: Long) : PartyRequestMessage

View File

@ -157,9 +157,7 @@ object TwoPartyDealProtocol {
if (regulators.isNotEmpty()) {
// Copy the transaction to every regulator in the network. This is obviously completely bogus, it's
// just for demo purposes.
for (regulator in regulators) {
send(regulator.identity, DEFAULT_SESSION_ID, fullySigned)
}
regulators.forEach { send(it.identity, DEFAULT_SESSION_ID, fullySigned) }
}
return fullySigned
@ -276,12 +274,12 @@ object TwoPartyDealProtocol {
/**
* One side of the protocol for inserting a pre-agreed deal.
*/
open class Instigator<T : DealState>(override val otherSide: Party,
val notary: Party,
override val payload: T,
override val myKeyPair: KeyPair,
override val otherSessionID: Long,
override val progressTracker: ProgressTracker = Primary.tracker()) : Primary<T>() {
open class Instigator<out T : DealState>(override val otherSide: Party,
val notary: Party,
override val payload: T,
override val myKeyPair: KeyPair,
override val otherSessionID: Long,
override val progressTracker: ProgressTracker = Primary.tracker()) : Primary<T>() {
override val notaryNode: NodeInfo get() =
serviceHub.networkMapCache.notaryNodes.filter { it.identity == notary }.single()
@ -378,7 +376,7 @@ object TwoPartyDealProtocol {
val newDeal = deal
val ptx = TransactionType.General.Builder()
val addFixing = object : RatesFixProtocol(ptx, serviceHub.networkMapCache.ratesOracleNodes[0].identity, fixOf, BigDecimal.ZERO, BigDecimal.ONE, initiation.timeout) {
val addFixing = object : RatesFixProtocol(ptx, serviceHub.networkMapCache.ratesOracleNodes[0].identity, fixOf, BigDecimal.ZERO, BigDecimal.ONE) {
@Suspendable
override fun beforeSigning(fix: Fix) {
newDeal.generateFix(ptx, StateAndRef(txState, handshake.payload), fix)

View File

@ -8,23 +8,23 @@ import java.util.*;
public class ProtocolLogicRefFromJavaTest {
public static class ParamType1 {
public final int value;
private static class ParamType1 {
final int value;
ParamType1(int v) {
value = v;
}
}
public static class ParamType2 {
public final String value;
private static class ParamType2 {
final String value;
ParamType2(String v) {
value = v;
}
}
public static class JavaProtocolLogic extends ProtocolLogic<Void> {
private static class JavaProtocolLogic extends ProtocolLogic<Void> {
public JavaProtocolLogic(ParamType1 A, ParamType2 b) {
}
@ -41,7 +41,7 @@ public class ProtocolLogicRefFromJavaTest {
}
}
public static class JavaNoArgProtocolLogic extends ProtocolLogic<Void> {
private static class JavaNoArgProtocolLogic extends ProtocolLogic<Void> {
public JavaNoArgProtocolLogic() {
}
@ -72,8 +72,7 @@ public class ProtocolLogicRefFromJavaTest {
@Test
public void testNoArg() {
Map<String, Set<String>> whiteList = new HashMap<>();
Set<String> argsList = new HashSet<>();
whiteList.put(JavaNoArgProtocolLogic.class.getName(), argsList);
whiteList.put(JavaNoArgProtocolLogic.class.getName(), new HashSet<>());
ProtocolLogicRefFactory factory = new ProtocolLogicRefFactory(whiteList);
factory.create(JavaNoArgProtocolLogic.class);
}

View File

@ -11,7 +11,7 @@ class FinanceTypesTest {
@Test
fun `make sure Amount has decimal places`() {
var x = Amount(1, Currency.getInstance("USD"))
val x = Amount(1, Currency.getInstance("USD"))
assert("0.01" in x.toString())
}
@ -44,17 +44,17 @@ class FinanceTypesTest {
@Test
fun `schedule generator 1`() {
var ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2014, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3)
val ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2014, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3)
// We know that Jan 25th 2015 is on the weekend -> It should not be in this list returned.
assert(!(LocalDate.of(2015, 1, 25) in ret))
assert(LocalDate.of(2015, 1, 25) !in ret)
println(ret)
}
@Test
fun `schedule generator 2`() {
var ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2015, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3, calendar = BusinessCalendar.getInstance("London"), dateRollConvention = DateRollConvention.Following)
val ret = BusinessCalendar.createGenericSchedule(startDate = LocalDate.of(2015, 11, 25), period = Frequency.Monthly, noOfAdditionalPeriods = 3, calendar = BusinessCalendar.getInstance("London"), dateRollConvention = DateRollConvention.Following)
// Xmas should not be in the list!
assert(!(LocalDate.of(2015, 12, 25) in ret))
assert(LocalDate.of(2015, 12, 25) !in ret)
println(ret)
}
@ -126,7 +126,7 @@ class FinanceTypesTest {
)
for ((inc, exp) in expected) {
var result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc)
val result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc)
assertEquals(exp, result)
}
}
@ -146,7 +146,7 @@ class FinanceTypesTest {
)
for ((inc, exp) in expected) {
var result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc)
val result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc)
assertEquals(exp, result)
}

View File

@ -13,7 +13,7 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
// We cast null to things in order to select overloads here but Kotlin doesn't know that it's OK.
// TODO: This suppress is needed due to KT-260, fixed in Kotlin 1.0.4 so remove after upgrading.
@Suppress("CAST_NEVER_SUCCEEDS")
class WhitelistTrustManagerTest {
companion object {

View File

@ -11,7 +11,6 @@ import java.io.DataOutputStream
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.file.Paths
import java.security.PrivateKey
import java.security.SecureRandom
import java.security.Signature

View File

@ -10,7 +10,7 @@ class ProtocolLogicRefTest {
data class ParamType1(val value: Int)
data class ParamType2(val value: String)
@Suppress("UNUSED_PARAMETER") // We will never use A or b
@Suppress("UNUSED_PARAMETER", "unused") // Things are used via reflection.
class KotlinProtocolLogic(A: ParamType1, b: ParamType2) : ProtocolLogic<Unit>() {
constructor() : this(ParamType1(1), ParamType2("2"))
@ -22,22 +22,18 @@ class ProtocolLogicRefTest {
constructor(kotlinType: Int) : this(ParamType1(kotlinType), ParamType2("b"))
override fun call(): Unit {
}
override fun call() = Unit
override val topic: String get() = throw UnsupportedOperationException()
}
class KotlinNoArgProtocolLogic : ProtocolLogic<Unit>() {
override fun call(): Unit {
}
override fun call() = Unit
override val topic: String get() = throw UnsupportedOperationException()
}
@Suppress("UNUSED_PARAMETER") // We will never use A or b
class NotWhiteListedKotlinProtocolLogic(A: Int, b: String) : ProtocolLogic<Unit>() {
override fun call(): Unit {
}
override fun call() = Unit
override val topic: String get() = throw UnsupportedOperationException()
}
@ -99,5 +95,4 @@ class ProtocolLogicRefTest {
val args = mapOf(Pair("kotlinType", 3))
factory.createKotlin(KotlinProtocolLogic::class.java, args)
}
}

View File

@ -2,7 +2,6 @@ package com.r3corda.core.serialization
import com.r3corda.core.contracts.*
import com.r3corda.core.crypto.SecureHash
import com.r3corda.core.crypto.newSecureRandom
import com.r3corda.core.seconds
import com.r3corda.core.testing.*
import org.junit.Before
@ -34,8 +33,6 @@ class TransactionSerializationTests {
}
interface Commands : CommandData {
class Move() : TypeOnlyCommandData(), Commands
data class Issue(val nonce: Long = newSecureRandom().nextLong()) : Commands
data class Exit(val amount: Amount<Currency>) : Commands
}
}

View File

@ -111,7 +111,9 @@ class ProgressTrackerTest {
pt.setChildProgressTracker(SimpleSteps.TWO, pt2)
class Tmp {
val unserializable = Unserializable()
val subscription = pt2.changes.subscribe { unserializable.foo() }
init {
pt2.changes.subscribe { unserializable.foo() }
}
}
Tmp()
pt.serialize(kryo)

View File

@ -0,0 +1,4 @@
package com.r3corda.protocols
class ResolveTransactionsProtocolTest {
}

View File

@ -8,15 +8,6 @@ interface StatesQuery {
fun select(criteria: Criteria): Selection {
return Selection(criteria)
}
fun selectAllDeals(): Selection {
return select(Criteria.AllDeals)
}
fun selectDeal(ref: String): Selection {
return select(Criteria.Deal(ref))
}
}
// TODO make constructors private

View File

@ -6,13 +6,13 @@ import com.google.common.util.concurrent.SettableFuture
import com.r3corda.core.RunOnCallerThread
import com.r3corda.core.contracts.SignedTransaction
import com.r3corda.core.crypto.Party
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.runOnNextMessage
import com.r3corda.core.node.CityDatabase
import com.r3corda.core.node.CordaPluginRegistry
import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.PhysicalLocation
import com.r3corda.core.node.services.*
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.protocols.ProtocolLogicRefFactory
import com.r3corda.core.random63BitValue
@ -27,14 +27,15 @@ import com.r3corda.node.services.events.NodeSchedulerService
import com.r3corda.node.services.events.ScheduledActivityObserver
import com.r3corda.node.services.identity.InMemoryIdentityService
import com.r3corda.node.services.keys.E2ETestKeyManagementService
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.node.services.network.InMemoryNetworkMapCache
import com.r3corda.node.services.network.InMemoryNetworkMapService
import com.r3corda.node.services.network.NetworkMapService
import com.r3corda.node.services.network.NetworkMapService.Companion.REGISTER_PROTOCOL_TOPIC
import com.r3corda.node.services.network.NodeRegistration
import com.r3corda.node.services.persistence.*
import com.r3corda.node.services.persistence.NodeAttachmentService
import com.r3corda.node.services.persistence.PerFileCheckpointStorage
import com.r3corda.node.services.persistence.PerFileTransactionStorage
import com.r3corda.node.services.persistence.StorageServiceImpl
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.transactions.InMemoryUniquenessProvider
import com.r3corda.node.services.transactions.NotaryService
@ -158,7 +159,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
storage = storageServices.first
checkpointStorage = storageServices.second
net = makeMessagingService()
netMapCache = InMemoryNetworkMapCache(net)
netMapCache = InMemoryNetworkMapCache()
wallet = NodeWalletService(services)
identity = makeIdentityService()
@ -201,8 +202,8 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
private fun initialiseProtocolLogicFactory(): ProtocolLogicRefFactory {
val protocolWhitelist = HashMap<String, Set<String>>()
for (plugin in pluginRegistries) {
for (protocol in plugin.requiredProtocols) {
protocolWhitelist.merge(protocol.key, protocol.value, { x, y -> x + y })
for ((className, classWhitelist) in plugin.requiredProtocols) {
protocolWhitelist.merge(className, classWhitelist, { x, y -> x + y })
}
}

View File

@ -4,7 +4,6 @@ import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.google.common.util.concurrent.Futures
import com.r3corda.core.crypto.Party
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.SingleMessageRecipient
import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.PhysicalLocation
@ -104,7 +103,8 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
}
// This does not indirect through the NodeInfo object so it can be called before the node is started.
val place: PhysicalLocation get() = findMyLocation()!!
// It is used from the network visualiser tool.
@Suppress("unused") val place: PhysicalLocation get() = findMyLocation()!!
}
/** Returns a node, optionally created by the passed factory method. */
@ -168,6 +168,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
fun createNotaryNode(legalName: String? = null, keyPair: KeyPair? = null) = createNode(null, -1, defaultFactory, true, legalName, keyPair, NetworkMapService.Type, SimpleNotaryService.Type)
fun createPartyNode(networkMapAddr: NodeInfo, legalName: String? = null, keyPair: KeyPair? = null) = createNode(networkMapAddr, -1, defaultFactory, true, legalName, keyPair)
@Suppress("unused") // This is used from the network visualiser tool.
fun addressToNode(address: SingleMessageRecipient): MockNode = nodes.single { it.net.myAddress == address }
fun startNodes() {

View File

@ -31,8 +31,8 @@ import java.util.*
* in a few cities around the world.
*/
abstract class Simulation(val networkSendManuallyPumped: Boolean,
val runAsync: Boolean,
val latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
runAsync: Boolean,
latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
init {
if (!runAsync && latencyInjector != null)
throw IllegalArgumentException("The latency injector is only useful when using manual pumping.")
@ -160,10 +160,11 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean,
val clocks = (serviceProviders + regulators + banks).map { it.services.clock as TestClock }
// These are used from the network visualiser tool.
private val _allProtocolSteps = PublishSubject.create<Pair<SimulatedNode, ProgressTracker.Change>>()
private val _doneSteps = PublishSubject.create<Collection<SimulatedNode>>()
val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
@Suppress("unused") val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
@Suppress("unused") val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
private var pumpCursor = 0
@ -258,6 +259,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean,
}
}
@Suppress("unused") // Used from the network visualiser tool.
val networkInitialisationFinished: ListenableFuture<*> =
Futures.allAsList(network.nodes.map { it.networkMapRegistrationFuture })

View File

@ -2,7 +2,6 @@ package com.r3corda.node.services.api
import com.r3corda.core.messaging.Message
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.TopicSession
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.serialization.SingletonSerializeAsToken

View File

@ -3,7 +3,6 @@ package com.r3corda.node.services.api
import com.r3corda.core.serialization.SerializedBytes
import com.r3corda.node.services.statemachine.FiberRequest
import com.r3corda.node.services.statemachine.ProtocolStateMachineImpl
import com.r3corda.node.services.statemachine.StateMachineManager
/**
* Thread-safe storage of fiber checkpoints.

View File

@ -3,7 +3,6 @@ package com.r3corda.node.services.clientapi
import com.r3corda.core.node.CordaPluginRegistry
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.serialization.deserialize
import com.r3corda.node.internal.AbstractNode
import com.r3corda.node.services.api.ServiceHubInternal
import com.r3corda.protocols.TwoPartyDealProtocol

View File

@ -197,7 +197,7 @@ object NodeInterestRates {
class UnknownFix(val fix: FixOf) : RetryableException("Unknown fix: $fix")
/** Fix container, for every fix name & date pair stores a tenor to interest rate map - [InterpolatingRateMap] */
class FixContainer(val fixes: List<Fix>, val factory: InterpolatorFactory = CubicSplineInterpolator) {
class FixContainer(fixes: List<Fix>, val factory: InterpolatorFactory = CubicSplineInterpolator) {
private val container = buildContainer(fixes)
val size = fixes.size
@ -227,7 +227,7 @@ object NodeInterestRates {
* Interpolates missing values using the provided interpolation mechanism.
*/
class InterpolatingRateMap(val date: LocalDate,
val inputRates: Map<Tenor, BigDecimal>,
inputRates: Map<Tenor, BigDecimal>,
val calendar: BusinessCalendar,
val factory: InterpolatorFactory) {
@ -274,7 +274,7 @@ object NodeInterestRates {
/** Parses lines containing fixes */
fun parseFile(s: String): FixContainer {
val fixes = s.lines().
map { it.trim() }.
map(String::trim).
// Filter out comment and empty lines.
filterNot { it.startsWith("#") || it.isBlank() }.
map { parseFix(it) }
@ -283,7 +283,7 @@ object NodeInterestRates {
/** Parses a string of the form "LIBOR 16-March-2016 1M = 0.678" into a [Fix] */
fun parseFix(s: String): Fix {
val (key, value) = s.split('=').map { it.trim() }
val (key, value) = s.split('=').map(String::trim)
val of = parseFixOf(key)
val rate = BigDecimal(value)
return Fix(of, rate)

View File

@ -50,6 +50,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
// The corresponding sentMessages stream reflects when a message was pumpSend'd
private val messageSendQueue = LinkedBlockingQueue<MessageTransfer>()
private val _sentMessages = PublishSubject.create<MessageTransfer>()
@Suppress("unused") // Used by the visualiser tool.
/** A stream of (sender, message, recipients) triples */
val sentMessages: Observable<MessageTransfer>
get() = _sentMessages
@ -61,6 +62,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
// The corresponding stream reflects when a message was pumpReceive'd
private val messageReceiveQueues = HashMap<Handle, LinkedBlockingQueue<MessageTransfer>>()
private val _receivedMessages = PublishSubject.create<MessageTransfer>()
@Suppress("unused") // Used by the visualiser tool.
/** A stream of (sender, message, recipients) triples */
val receivedMessages: Observable<MessageTransfer>
get() = _receivedMessages
@ -202,18 +205,18 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
val callback: (Message, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration
@Volatile
protected var running = true
private var running = true
protected inner class InnerState {
private inner class InnerState {
val handlers: MutableList<Handler> = ArrayList()
val pendingRedelivery = LinkedList<MessageTransfer>()
}
protected val state = ThreadBox(InnerState())
private val state = ThreadBox(InnerState())
override val myAddress: SingleMessageRecipient = handle
protected val backgroundThread = if (manuallyPumped) null else
private val backgroundThread = if (manuallyPumped) null else
thread(isDaemon = true, name = "In-memory message dispatcher") {
while (!Thread.currentThread().isInterrupted) {
try {
@ -235,8 +238,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
pendingRedelivery.clear()
Pair(handler, items)
}
for (it in items) {
send(it.message, handle)
for ((sender, message) in items) {
send(message, handle)
}
return handler
}
@ -329,10 +332,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
private fun pumpReceiveInternal(block: Boolean): MessageTransfer? {
val q = getQueueForHandle(handle)
val next = getNextQueue(q, block)
if (next == null) {
return null
}
val next = getNextQueue(q, block) ?: return null
val (transfer, deliverTo) = next
for (handler in deliverTo) {

View File

@ -13,14 +13,13 @@ import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.NetworkCacheError
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.node.services.NetworkMapCache.MapChange
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.node.services.ServiceType
import com.r3corda.core.random63BitValue
import com.r3corda.core.serialization.SingletonSerializeAsToken
import com.r3corda.core.serialization.deserialize
import com.r3corda.core.serialization.serialize
import com.r3corda.node.services.api.MessagingServiceInternal
import com.r3corda.node.services.api.RegulatorService
import com.r3corda.node.services.clientapi.NodeInterestRates
import com.r3corda.node.services.transactions.NotaryService
@ -36,7 +35,7 @@ import javax.annotation.concurrent.ThreadSafe
* Extremely simple in-memory cache of the network map.
*/
@ThreadSafe
open class InMemoryNetworkMapCache(val netInternal: MessagingServiceInternal?) : SingletonSerializeAsToken(), NetworkMapCache {
open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCache {
override val networkMapNodes: List<NodeInfo>
get() = get(NetworkMapService.Type)
override val regulators: List<NodeInfo>

View File

@ -12,14 +12,14 @@ import rx.subjects.PublishSubject
/**
* Network map cache with no backing map service.
*/
class MockNetworkMapCache() : InMemoryNetworkMapCache(null) {
class MockNetworkMapCache() : InMemoryNetworkMapCache() {
override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>()
data class MockAddress(val id: String): SingleMessageRecipient
init {
var mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
var mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
val mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
val mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
registeredNodes[mockNodeA.identity] = mockNodeA
registeredNodes[mockNodeB.identity] = mockNodeB
}

View File

@ -280,7 +280,7 @@ class NodeRegistration(val node: NodeInfo, val serial: Long, val type: AddOrRemo
return WireNodeRegistration(regSerialized, regSig)
}
override fun toString() : String = "$node #${serial} (${type})"
override fun toString() : String = "$node #$serial ($type)"
}
/**

View File

@ -62,7 +62,7 @@ object DataVending {
if (data.accepted) {
future.set(Unit)
} else {
future.setException(TransactionRejectedError("Transaction ${transaction} rejected by remote party ${recipient.identity}"))
future.setException(TransactionRejectedError("Transaction $transaction rejected by remote party ${recipient.identity}"))
}
}
val msg = NotifyTxRequestMessage(transaction, myIdentity, sessionID)

View File

@ -22,7 +22,7 @@ import javax.annotation.concurrent.ThreadSafe
* Stores attachments in the specified local directory, which must exist. Doesn't allow new attachments to be uploaded.
*/
@ThreadSafe
class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload {
class NodeAttachmentService(val storePath: Path, metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload {
private val log = loggerFor<NodeAttachmentService>()
@VisibleForTesting
@ -122,7 +122,7 @@ class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) :
Files.deleteIfExists(tmp)
}
if (automaticallyExtractAttachments) {
val extractTo = storePath.resolve("${id}.jar")
val extractTo = storePath.resolve("$id.jar")
try {
Files.createDirectory(extractTo)
extractZipFile(finalPath, extractTo)

View File

@ -40,7 +40,7 @@ class PerFileCheckpointStorage(val storeDir: Path) : CheckpointStorage {
override fun addCheckpoint(checkpoint: Checkpoint) {
val serialisedCheckpoint = checkpoint.serialize()
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}${fileExtension}"
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}$fileExtension"
val checkpointFile = storeDir.resolve(fileName)
atomicWrite(checkpointFile, serialisedCheckpoint)
logger.trace { "Stored $checkpoint to $checkpointFile" }

View File

@ -59,15 +59,15 @@ sealed class FiberRequest(val topic: String,
) : FiberRequest(topic, destination, sessionIDForSend, sessionIDForReceive, obj) {
private val responseTypeName: String = type.name
override fun equals(other: Any?): Boolean
= if (other is ExpectingResponse<*>) {
super.equals(other)
&& responseTypeName == other.responseTypeName
} else
false
override fun equals(other: Any?): Boolean {
return if (other is ExpectingResponse<*>) {
super.equals(other) && responseTypeName == other.responseTypeName
} else
false
}
override fun toString(): String {
return "Expecting response via topic ${receiveTopicSession} of type ${responseTypeName}"
return "Expecting response via topic $receiveTopicSession of type $responseTypeName"
}
// We have to do an unchecked cast, but unless the serialized form is damaged, this was

View File

@ -30,13 +30,13 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) {
//
// Note: exported as pennies.
val m = serviceHubInternal.monitoringService.metrics
for (balance in wallet.cashBalances) {
val metric = balanceMetrics.getOrPut(balance.key) {
for ((key, value) in wallet.cashBalances) {
val metric = balanceMetrics.getOrPut(key) {
val newMetric = BalanceMetric()
m.register("WalletBalances.${balance.key}Pennies", newMetric)
m.register("WalletBalances.${key}Pennies", newMetric)
newMetric
}
metric.pennies = balance.value.quantity
metric.pennies = value.quantity
}
}
}

View File

@ -4,7 +4,6 @@ import com.r3corda.core.ThreadBox
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.utilities.ProgressTracker
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.protocols.TwoPartyDealProtocol
import java.util.*
/**

View File

@ -36,7 +36,7 @@ import kotlin.concurrent.withLock
* TODO: We should consider using a [Semaphore] or [CountDownLatch] here to make it a little easier to understand, but it seems
* as though the current version of Qasar does not support suspending on either of their implementations.
*/
class FiberBox<T>(private val content: T, private val lock: Lock = ReentrantLock()) {
class FiberBox<out T>(private val content: T, private val lock: Lock = ReentrantLock()) {
private var mutated: SettableFuture<Boolean>? = null
@Suppress("UNUSED_VALUE") // This is here due to the compiler thinking ourMutated is not used

View File

@ -13,8 +13,6 @@ import com.r3corda.core.contracts.BusinessCalendar
import com.r3corda.core.crypto.*
import com.r3corda.core.node.services.IdentityService
import net.i2p.crypto.eddsa.EdDSAPublicKey
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime

View File

@ -19,6 +19,7 @@ import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.wallet.NodeWalletService
import java.time.Clock
@Suppress("LeakingThis")
open class MockServiceHubInternal(
customWallet: WalletService? = null,
val keyManagement: KeyManagementService? = null,

View File

@ -22,7 +22,6 @@ import com.r3corda.protocols.RatesFixProtocol
import org.junit.Assert
import org.junit.Test
import java.time.Clock
import java.time.Duration
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@ -109,7 +108,7 @@ class NodeInterestRatesTest {
val tx = TransactionType.General.Builder()
val fixOf = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M")
val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd, Duration.ofNanos(1))
val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd)
BriefLogFormatter.initVerbose("rates")
net.runNetwork()
val future = n1.smm.add("rates", protocol)

View File

@ -196,7 +196,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
@Test
fun `test activity due in the future and schedule another for same time then unschedule original`() {
val time = stoppedClock.instant() + 1.days
var scheduledRef1 = scheduleTX(time)
val scheduledRef1 = scheduleTX(time)
val backgroundExecutor = Executors.newSingleThreadExecutor()
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
@ -214,7 +214,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
@Test
fun `test activity due in the future then unschedule`() {
var scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days)
val scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days)
val backgroundExecutor = Executors.newSingleThreadExecutor()
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }

View File

@ -7,7 +7,6 @@ import com.r3corda.core.random63BitValue
import com.r3corda.core.serialization.SerializedBytes
import com.r3corda.node.services.api.Checkpoint
import com.r3corda.node.services.statemachine.FiberRequest
import com.r3corda.node.services.statemachine.StateMachineManager
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.After

View File

@ -2,7 +2,6 @@ package com.r3corda.node.services.statemachine
import co.paralleluniverse.fibers.Fiber
import co.paralleluniverse.fibers.Suspendable
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.node.services.MockServiceHubInternal
import com.r3corda.node.services.api.Checkpoint

View File

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

View File

@ -37,7 +37,7 @@ public class StateViewer {
frame.setVisible(true);
}
public StateViewer(List<Pair<String, Object>> props) {
private StateViewer(List<Pair<String, Object>> props) {
propsTable.setModel(new AbstractTableModel() {
@Override
public int getRowCount() {

View File

@ -90,7 +90,7 @@ fun main(args: Array<String>) {
// Make a garbage transaction that includes a rate fix.
val tx = TransactionType.General.Builder()
tx.addOutputState(TransactionState(Cash.State(1500.DOLLARS `issued by` node.storage.myLegalIdentity.ref(1), node.keyManagement.freshKey().public), notary.identity))
val protocol = RatesFixProtocol(tx, oracleNode.identity, fixOf, expectedRate, rateTolerance, 24.hours)
val protocol = RatesFixProtocol(tx, oracleNode.identity, fixOf, expectedRate, rateTolerance)
node.smm.add("demo.ratefix", protocol).get()
node.stop()

View File

@ -1,4 +1,4 @@
"use strict"
"use strict";
define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
let calculationModel = {
@ -25,7 +25,7 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
let Deal = function(dealViewModel) {
let now = new Date();
let tradeId = `T${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}.${now.getUTCHours()}:${now.getUTCMinutes()}:${now.getUTCSeconds()}:${now.getUTCMilliseconds()}`
let tradeId = `T${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}.${now.getUTCHours()}:${now.getUTCMinutes()}:${now.getUTCSeconds()}:${now.getUTCMilliseconds()}`;
this.toJson = () => {
let fixedLeg = {};
@ -70,10 +70,10 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
floatingLeg: floatingLeg,
calculation: calculationModel,
common: common
}
};
return json;
};
};
return Deal;
})
});

View File

@ -1,4 +1,4 @@
"use strict"
"use strict";
function formatDateForNode(date) {
// Produces yyyy-dd-mm. JS is missing proper date formatting libs

View File

@ -6,7 +6,7 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no
let handleHttpFail = (resp) => {
$scope.httpError = resp.data
}
};
$scope.infoMsg = "";
$scope.errorText = "";
@ -20,4 +20,4 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no
nodeService.getDate().then((date) => $scope.date = date);
nodeService.getDeals().then((deals) => $scope.deals = deals);
});
})
});

View File

@ -15,7 +15,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
curLoading[type] = false;
throw arg;
});
}
};
let changeDateOnNode = (newDate) => {
const dateStr = formatDateForNode(newDate);
@ -24,7 +24,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
date = newDate;
return this.getDateModel(date);
});
}
};
this.getDate = () => {
return load('date', $http.get('/api/irs/demodate')).then((resp) => {
@ -32,7 +32,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
date = new Date(parts[0], parts[1] - 1, parts[2]); // JS uses 0 based months
return this.getDateModel(date);
});
}
};
this.updateDate = (type) => {
let newDate = date;
@ -74,17 +74,17 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
"month": date.getMonth() + 1, // JS uses 0 based months
"day": date.getDate()
};
}
};
this.isLoading = () => {
return _.reduce(Object.keys(curLoading), (last, key) => {
return (last || curLoading[key]);
}, false);
}
};
this.newDeal = () => {
return dealViewModel;
}
};
this.createDeal = (deal) => {
return load('create-deal', $http.post('/api/irs/deals', deal.toJson()))

View File

@ -31,4 +31,4 @@ define([], () => {
"year": "YICMA"
},
};
})
});