mirror of
https://github.com/corda/corda.git
synced 2025-05-06 02:28:28 +00:00
Merged in mike-regular-autocleaning (pull request #270)
Regular autocleaning
This commit is contained in:
commit
e18a80beb2
@ -24,7 +24,7 @@ import static kotlin.collections.CollectionsKt.*;
|
|||||||
*/
|
*/
|
||||||
public class JavaCommercialPaper extends ClauseVerifier {
|
public class JavaCommercialPaper extends ClauseVerifier {
|
||||||
//public static SecureHash JCP_PROGRAM_ID = SecureHash.sha256("java commercial paper (this should be a bytecode hash)");
|
//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 {
|
public static class State implements ContractState, ICommercialPaperState {
|
||||||
private PartyAndReference issuance;
|
private PartyAndReference issuance;
|
||||||
@ -326,7 +326,7 @@ public class JavaCommercialPaper extends ClauseVerifier {
|
|||||||
public Collection<AuthenticatedObject<CommandData>> extractCommands(@NotNull TransactionForContract tx) {
|
public Collection<AuthenticatedObject<CommandData>> extractCommands(@NotNull TransactionForContract tx) {
|
||||||
return tx.getCommands()
|
return tx.getCommands()
|
||||||
.stream()
|
.stream()
|
||||||
.filter((AuthenticatedObject<CommandData> command) -> { return command.getValue() instanceof Commands; })
|
.filter((AuthenticatedObject<CommandData> command) -> command.getValue() instanceof Commands)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -205,7 +205,7 @@ class CommercialPaper : ClauseVerifier() {
|
|||||||
@Throws(InsufficientBalanceException::class)
|
@Throws(InsufficientBalanceException::class)
|
||||||
fun generateRedeem(tx: TransactionBuilder, paper: StateAndRef<State>, wallet: List<StateAndRef<Cash.State>>) {
|
fun generateRedeem(tx: TransactionBuilder, paper: StateAndRef<State>, wallet: List<StateAndRef<Cash.State>>) {
|
||||||
// Add the cash movement using the states in our wallet.
|
// 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)
|
Cash().generateSpend(tx, amount, paper.state.data.owner, wallet)
|
||||||
tx.addInputState(paper)
|
tx.addInputState(paper)
|
||||||
tx.addCommand(CommercialPaper.Commands.Redeem(paper.state.notary), paper.state.data.owner)
|
tx.addCommand(CommercialPaper.Commands.Redeem(paper.state.notary), paper.state.data.owner)
|
||||||
|
@ -55,7 +55,7 @@ class CommercialPaperLegacy : Contract {
|
|||||||
|
|
||||||
override fun verify(tx: TransactionForContract) {
|
override fun verify(tx: TransactionForContract) {
|
||||||
// Group by everything except owner: any modification to the CP at all is considered changing it fundamentally.
|
// 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
|
// 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.
|
// it for cash on or after the maturity date.
|
||||||
|
@ -79,7 +79,7 @@ class ReferenceRate(val oracle: String, val tenor: Tenor, val name: String) : Fl
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: For further discussion.
|
// 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)
|
//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)
|
//fun Amount<Currency>.times(other: InterestRateSwap.RatioUnit): Amount<Currency> = Amount<Currency>((BigDecimal(this.pennies).multiply(other.value)).longValueExact(), this.currency)
|
||||||
|
|
||||||
|
@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount
|
|||||||
import com.r3corda.contracts.clause.AbstractIssue
|
import com.r3corda.contracts.clause.AbstractIssue
|
||||||
import com.r3corda.contracts.clause.NoZeroSizedOutputs
|
import com.r3corda.contracts.clause.NoZeroSizedOutputs
|
||||||
import com.r3corda.core.contracts.*
|
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.crypto.*
|
||||||
import com.r3corda.core.node.services.Wallet
|
import com.r3corda.core.node.services.Wallet
|
||||||
import com.r3corda.core.utilities.Emoji
|
import com.r3corda.core.utilities.Emoji
|
||||||
@ -81,7 +82,7 @@ class Cash : OnLedgerAsset<Currency, Cash.State>() {
|
|||||||
override val owner: PublicKey
|
override val owner: PublicKey
|
||||||
) : FungibleAsset<Currency> {
|
) : FungibleAsset<Currency> {
|
||||||
constructor(deposit: PartyAndReference, amount: Amount<Currency>, owner: PublicKey)
|
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 deposit = amount.token.issuer
|
||||||
override val exitKeys = setOf(deposit.party.owningKey)
|
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. */
|
/** 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>> {
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -4,7 +4,8 @@ import com.r3corda.contracts.clause.AbstractConserveAmount
|
|||||||
import com.r3corda.contracts.clause.AbstractIssue
|
import com.r3corda.contracts.clause.AbstractIssue
|
||||||
import com.r3corda.contracts.clause.NoZeroSizedOutputs
|
import com.r3corda.contracts.clause.NoZeroSizedOutputs
|
||||||
import com.r3corda.core.contracts.*
|
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.Party
|
||||||
import com.r3corda.core.crypto.SecureHash
|
import com.r3corda.core.crypto.SecureHash
|
||||||
import com.r3corda.core.crypto.newSecureRandom
|
import com.r3corda.core.crypto.newSecureRandom
|
||||||
@ -107,7 +108,7 @@ class CommodityContract : OnLedgerAsset<Commodity, CommodityContract.State>() {
|
|||||||
override val owner: PublicKey
|
override val owner: PublicKey
|
||||||
) : FungibleAsset<Commodity> {
|
) : FungibleAsset<Commodity> {
|
||||||
constructor(deposit: PartyAndReference, amount: Amount<Commodity>, owner: PublicKey)
|
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 deposit = amount.token.issuer
|
||||||
override val contract = COMMODITY_PROGRAM_ID
|
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()
|
fun Iterable<ContractState>.sumCommodities() = filterIsInstance<CommodityContract.State>().map { it.amount }.sumOrThrow()
|
||||||
|
|
||||||
/** Sums the cash states in the list, returning null if there are none. */
|
/** 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. */
|
/** 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)
|
||||||
|
@ -2,7 +2,6 @@ package com.r3corda.contracts.asset
|
|||||||
|
|
||||||
import com.r3corda.core.contracts.*
|
import com.r3corda.core.contracts.*
|
||||||
import java.security.PublicKey
|
import java.security.PublicKey
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
class InsufficientBalanceException(val amountMissing: Amount<*>) : Exception() {
|
class InsufficientBalanceException(val amountMissing: Amount<*>) : Exception() {
|
||||||
override fun toString() = "Insufficient balance, missing $amountMissing"
|
override fun toString() = "Insufficient balance, missing $amountMissing"
|
||||||
|
@ -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
|
// Settle commands exclude all other commands, so we don't need to check for contracts moving at the same
|
||||||
// time.
|
// time.
|
||||||
"amounts paid must match recipients to settle" by inputs.map { it.owner }.containsAll(amountReceivedByOwner.keys)
|
"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)
|
"signatures are present from all obligors" by command.signers.containsAll(requiredSigners)
|
||||||
"there are no zero sized inputs" by inputs.none { it.amount.quantity == 0L }
|
"there are no zero sized inputs" by inputs.none { it.amount.quantity == 0L }
|
||||||
"at obligor ${obligor.name} the obligations after settlement balance" by
|
"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.
|
* A default command mutates inputs and produces identical outputs, except that the lifecycle changes.
|
||||||
*/
|
*/
|
||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
protected fun verifySetLifecycleCommand(inputs: List<FungibleAsset<Terms<P>>>,
|
private fun verifySetLifecycleCommand(inputs: List<FungibleAsset<Terms<P>>>,
|
||||||
outputs: List<FungibleAsset<Terms<P>>>,
|
outputs: List<FungibleAsset<Terms<P>>>,
|
||||||
tx: TransactionForContract,
|
tx: TransactionForContract,
|
||||||
setLifecycleCommand: AuthenticatedObject<Commands.SetLifecycle>) {
|
setLifecycleCommand: AuthenticatedObject<Commands.SetLifecycle>) {
|
||||||
@ -439,7 +439,7 @@ class Obligation<P> : ClauseVerifier() {
|
|||||||
"signer is in the state parties" by (signer in netState!!.partyKeys)
|
"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)
|
if (out.quantity > 0L)
|
||||||
tx.addOutputState(out)
|
tx.addOutputState(out)
|
||||||
tx.addCommand(Commands.Net(NetType.PAYMENT), signer)
|
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.
|
* 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.
|
* @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>>>,
|
fun generateExit(tx: TransactionBuilder, amountIssued: Amount<Issued<Terms<P>>>,
|
||||||
changeKey: PublicKey, assetStates: List<StateAndRef<Obligation.State<P>>>): PublicKey
|
changeKey: PublicKey, assetStates: List<StateAndRef<Obligation.State<P>>>): PublicKey
|
||||||
= Clauses.ConserveAmount<P>().generateExit(tx, amountIssued, changeKey, assetStates,
|
= Clauses.ConserveAmount<P>().generateExit(tx, amountIssued, changeKey, assetStates,
|
||||||
deriveState = { state, amount, owner -> state.copy(data = state.data.move(amount, owner)) },
|
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.DEFAULTED -> Lifecycle.NORMAL
|
||||||
Lifecycle.NORMAL -> Lifecycle.DEFAULTED
|
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
|
// Produce a new set of states
|
||||||
val groups = statesAndRefs.groupBy { it.state.data.issuanceDef }
|
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>.`owned by`(owner: PublicKey) = copy(beneficiary = owner)
|
||||||
infix fun <T> Obligation.State<T>.`issued by`(party: Party) = copy(obligor = party)
|
infix fun <T> Obligation.State<T>.`issued by`(party: Party) = copy(obligor = party)
|
||||||
// For Java users:
|
// For Java users:
|
||||||
fun <T> Obligation.State<T>.ownedBy(owner: PublicKey) = copy(beneficiary = owner)
|
@Suppress("unused") 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>.issuedBy(party: Party) = copy(obligor = party)
|
||||||
|
|
||||||
val Issued<Currency>.OBLIGATION_DEF: Obligation.Terms<Currency>
|
val Issued<Currency>.OBLIGATION_DEF: Obligation.Terms<Currency>
|
||||||
get() = Obligation.Terms(nonEmptySetOf(Cash().legalContractReference), nonEmptySetOf(this), TEST_TX_TIME)
|
get() = Obligation.Terms(nonEmptySetOf(Cash().legalContractReference), nonEmptySetOf(this), TEST_TX_TIME)
|
||||||
|
@ -2,10 +2,9 @@ package com.r3corda.contracts.asset
|
|||||||
|
|
||||||
import com.r3corda.contracts.clause.AbstractConserveAmount
|
import com.r3corda.contracts.clause.AbstractConserveAmount
|
||||||
import com.r3corda.core.contracts.*
|
import com.r3corda.core.contracts.*
|
||||||
import com.r3corda.core.contracts.clauses.*
|
import com.r3corda.core.contracts.clauses.ClauseVerifier
|
||||||
import com.r3corda.core.crypto.*
|
import com.r3corda.core.crypto.Party
|
||||||
import java.security.PublicKey
|
import java.security.PublicKey
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
//
|
//
|
||||||
|
@ -75,7 +75,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
|
|||||||
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, Amount(amount.quantity, currency))
|
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, Amount(amount.quantity, currency))
|
||||||
val takeChangeFrom = gathered.lastOrNull()
|
val takeChangeFrom = gathered.lastOrNull()
|
||||||
val change = if (takeChangeFrom != null && gatheredAmount > amount) {
|
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 {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
@ -139,7 +139,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
|
|||||||
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, amount)
|
val (gathered, gatheredAmount) = gatherCoins(acceptableCoins, amount)
|
||||||
val takeChangeFrom = gathered.firstOrNull()
|
val takeChangeFrom = gathered.firstOrNull()
|
||||||
val change = if (takeChangeFrom != null && gatheredAmount > amount) {
|
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 {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
@ -175,7 +175,7 @@ abstract class AbstractConserveAmount<S: FungibleAsset<T>, T: Any> : GroupClause
|
|||||||
outputs: List<S>,
|
outputs: List<S>,
|
||||||
commands: Collection<AuthenticatedObject<CommandData>>,
|
commands: Collection<AuthenticatedObject<CommandData>>,
|
||||||
token: Issued<T>): Set<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 deposit = token.issuer
|
||||||
val outputAmount: Amount<Issued<T>> = outputs.sumFungibleOrZero(token)
|
val outputAmount: Amount<Issued<T>> = outputs.sumFungibleOrZero(token)
|
||||||
|
|
||||||
|
@ -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
|
* @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.
|
* 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 sum: List<S>.() -> Amount<Issued<T>>,
|
||||||
val sumOrZero: List<S>.(token: Issued<T>) -> Amount<Issued<T>>
|
val sumOrZero: List<S>.(token: Issued<T>) -> Amount<Issued<T>>
|
||||||
) : GroupClause<S, Issued<T>> {
|
) : GroupClause<S, Issued<T>> {
|
||||||
|
@ -51,6 +51,7 @@ open class NetClause<P> : SingleClause {
|
|||||||
override val requiredCommands: Set<Class<out CommandData>>
|
override val requiredCommands: Set<Class<out CommandData>>
|
||||||
get() = setOf(Obligation.Commands.Net::class.java)
|
get() = setOf(Obligation.Commands.Net::class.java)
|
||||||
|
|
||||||
|
@Suppress("ConvertLambdaToReference")
|
||||||
override fun verify(tx: TransactionForContract, commands: Collection<AuthenticatedObject<CommandData>>): Set<CommandData> {
|
override fun verify(tx: TransactionForContract, commands: Collection<AuthenticatedObject<CommandData>>): Set<CommandData> {
|
||||||
val command = commands.requireSingleCommand<Obligation.Commands.Net>()
|
val command = commands.requireSingleCommand<Obligation.Commands.Net>()
|
||||||
val groups = when (command.value.type) {
|
val groups = when (command.value.type) {
|
||||||
@ -67,10 +68,10 @@ open class NetClause<P> : SingleClause {
|
|||||||
* Verify a netting command. This handles both close-out and payment netting.
|
* Verify a netting command. This handles both close-out and payment netting.
|
||||||
*/
|
*/
|
||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
public fun verifyNetCommand(inputs: List<Obligation.State<P>>,
|
fun verifyNetCommand(inputs: List<Obligation.State<P>>,
|
||||||
outputs: List<Obligation.State<P>>,
|
outputs: List<Obligation.State<P>>,
|
||||||
command: AuthenticatedObject<Obligation.Commands.Net>,
|
command: AuthenticatedObject<Obligation.Commands.Net>,
|
||||||
netState: NetState<P>) {
|
netState: NetState<P>) {
|
||||||
val template = netState.template
|
val template = netState.template
|
||||||
// Create two maps of balances from obligors to beneficiaries, one for input states, the other for output states.
|
// Create two maps of balances from obligors to beneficiaries, one for input states, the other for output states.
|
||||||
val inputBalances = extractAmountsDue(template, inputs)
|
val inputBalances = extractAmountsDue(template, inputs)
|
||||||
|
@ -9,7 +9,7 @@ import com.r3corda.core.contracts.clauses.MatchBehaviour
|
|||||||
* Clause for fungible asset contracts, which enforces that no output state should have
|
* Clause for fungible asset contracts, which enforces that no output state should have
|
||||||
* a balance of zero.
|
* 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
|
override val ifMatched: MatchBehaviour
|
||||||
get() = MatchBehaviour.CONTINUE
|
get() = MatchBehaviour.CONTINUE
|
||||||
override val ifNotMatched: MatchBehaviour
|
override val ifNotMatched: MatchBehaviour
|
||||||
|
@ -48,7 +48,7 @@ object TwoPartyTradeProtocol {
|
|||||||
|
|
||||||
val TOPIC = "platform.trade"
|
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() {
|
class AssetMismatchException(val expectedTypeName: String, val typeName: String) : Exception() {
|
||||||
override fun toString() = "The submitted asset didn't match the expected type: $expectedTypeName vs $typeName"
|
override fun toString() = "The submitted asset didn't match the expected type: $expectedTypeName vs $typeName"
|
||||||
}
|
}
|
||||||
|
@ -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
|
* This is an incomplete Java replica of CashTests.kt to show how to use the Java test DSL
|
||||||
*/
|
*/
|
||||||
public class CashTestsJava {
|
public class CashTestsJava {
|
||||||
private OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1});
|
private final OpaqueBytes defaultRef = new OpaqueBytes(new byte[]{1});
|
||||||
private PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef);
|
private final PartyAndReference defaultIssuer = getMEGA_CORP().ref(defaultRef);
|
||||||
private Cash.State inState = new Cash.State(issuedBy(DOLLARS(1000), defaultIssuer), getDUMMY_PUBKEY_1());
|
private final 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 Cash.State outState = new Cash.State(inState.getAmount(), getDUMMY_PUBKEY_2());
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void trivial() {
|
public void trivial() {
|
||||||
|
@ -268,8 +268,8 @@ class IRSTests {
|
|||||||
LocalDate.of(2015, 12, 8) to "0.55",
|
LocalDate.of(2015, 12, 8) to "0.55",
|
||||||
LocalDate.of(2016, 3, 8) to "0.644")
|
LocalDate.of(2016, 3, 8) to "0.644")
|
||||||
|
|
||||||
for (it in fixings) {
|
for ((key, value) in fixings) {
|
||||||
newCalculation = newCalculation.applyFixing(it.key, FixedRate(PercentageRatioUnit(it.value)))
|
newCalculation = newCalculation.applyFixing(key, FixedRate(PercentageRatioUnit(value)))
|
||||||
}
|
}
|
||||||
|
|
||||||
val newIRS = InterestRateSwap.State(irs.fixedLeg, irs.floatingLeg, newCalculation, irs.common)
|
val newIRS = InterestRateSwap.State(irs.fixedLeg, irs.floatingLeg, newCalculation, irs.common)
|
||||||
|
@ -22,8 +22,8 @@ class ObligationTests {
|
|||||||
val defaultIssuer = MEGA_CORP.ref(defaultRef)
|
val defaultIssuer = MEGA_CORP.ref(defaultRef)
|
||||||
val oneMillionDollars = 1000000.DOLLARS `issued by` defaultIssuer
|
val oneMillionDollars = 1000000.DOLLARS `issued by` defaultIssuer
|
||||||
val trustedCashContract = nonEmptySetOf(SecureHash.Companion.randomSHA256() as SecureHash)
|
val trustedCashContract = nonEmptySetOf(SecureHash.Companion.randomSHA256() as SecureHash)
|
||||||
val megaIssuedDollars = nonEmptySetOf(Issued<Currency>(defaultIssuer, USD))
|
val megaIssuedDollars = nonEmptySetOf(Issued(defaultIssuer, USD))
|
||||||
val megaIssuedPounds = nonEmptySetOf(Issued<Currency>(defaultIssuer, GBP))
|
val megaIssuedPounds = nonEmptySetOf(Issued(defaultIssuer, GBP))
|
||||||
val fivePm = TEST_TX_TIME.truncatedTo(ChronoUnit.DAYS).plus(17, ChronoUnit.HOURS)
|
val fivePm = TEST_TX_TIME.truncatedTo(ChronoUnit.DAYS).plus(17, ChronoUnit.HOURS)
|
||||||
val sixPm = fivePm.plus(1, ChronoUnit.HOURS)
|
val sixPm = fivePm.plus(1, ChronoUnit.HOURS)
|
||||||
val megaCorpDollarSettlement = Obligation.Terms(trustedCashContract, megaIssuedDollars, fivePm)
|
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."
|
this `fails with` "All commands must be matched at end of execution."
|
||||||
}
|
}
|
||||||
tweak {
|
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 `fails with` "All commands must be matched at end of execution."
|
||||||
}
|
}
|
||||||
this.verifies()
|
this.verifies()
|
||||||
@ -451,7 +451,7 @@ class ObligationTests {
|
|||||||
input("Alice's $1,000,000 obligation to Bob")
|
input("Alice's $1,000,000 obligation to Bob")
|
||||||
input("Alice's $1,000,000")
|
input("Alice's $1,000,000")
|
||||||
output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_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) }
|
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
|
||||||
this.verifies()
|
this.verifies()
|
||||||
}
|
}
|
||||||
@ -465,7 +465,7 @@ class ObligationTests {
|
|||||||
input(500000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY)
|
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("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 }
|
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) }
|
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
|
||||||
this.verifies()
|
this.verifies()
|
||||||
}
|
}
|
||||||
@ -478,7 +478,7 @@ class ObligationTests {
|
|||||||
input(defaultedObligation) // Alice's defaulted $1,000,000 obligation to Bob
|
input(defaultedObligation) // Alice's defaulted $1,000,000 obligation to Bob
|
||||||
input(1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` ALICE_PUBKEY)
|
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 }
|
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) }
|
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
|
||||||
this `fails with` "all inputs are in the normal state"
|
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 obligation to Bob")
|
||||||
input("Alice's $1,000,000")
|
input("Alice's $1,000,000")
|
||||||
output("Bob's $1,000,000") { 1000000.DOLLARS.CASH `issued by` defaultIssuer `owned by` BOB_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 / 2, inState.issuanceDef)) }
|
command(ALICE_PUBKEY) { Obligation.Commands.Settle(Amount(oneMillionDollars.quantity / 2, inState.issuanceDef)) }
|
||||||
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
|
command(ALICE_PUBKEY) { Cash.Commands.Move(Obligation<Currency>().legalContractReference) }
|
||||||
this `fails with` "amount in settle command"
|
this `fails with` "amount in settle command"
|
||||||
}
|
}
|
||||||
@ -502,7 +502,7 @@ class ObligationTests {
|
|||||||
fun `commodity settlement`() {
|
fun `commodity settlement`() {
|
||||||
val defaultFcoj = FCOJ `issued by` defaultIssuer
|
val defaultFcoj = FCOJ `issued by` defaultIssuer
|
||||||
val oneUnitFcoj = Amount(1, defaultFcoj)
|
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,
|
val oneUnitFcojObligation = Obligation.State(Obligation.Lifecycle.NORMAL, ALICE,
|
||||||
obligationDef, oneUnitFcoj.quantity, NullPublicKey)
|
obligationDef, oneUnitFcoj.quantity, NullPublicKey)
|
||||||
// Try settling a simple commodity obligation
|
// 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 obligation to Bob")
|
||||||
input("Alice's 1 FCOJ")
|
input("Alice's 1 FCOJ")
|
||||||
output("Bob's 1 FCOJ") { CommodityContract.State(oneUnitFcoj, BOB_PUBKEY) }
|
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) }
|
command(ALICE_PUBKEY) { CommodityContract.Commands.Move(Obligation<Commodity>().legalContractReference) }
|
||||||
verifies()
|
verifies()
|
||||||
}
|
}
|
||||||
@ -646,13 +646,13 @@ class ObligationTests {
|
|||||||
output { outState.copy(quantity = inState.quantity - 200.DOLLARS.quantity) }
|
output { outState.copy(quantity = inState.quantity - 200.DOLLARS.quantity) }
|
||||||
|
|
||||||
tweak {
|
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() }
|
command(DUMMY_PUBKEY_1) { Obligation.Commands.Move() }
|
||||||
this `fails with` "the amounts balance"
|
this `fails with` "the amounts balance"
|
||||||
}
|
}
|
||||||
|
|
||||||
tweak {
|
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"
|
this `fails with` "required com.r3corda.contracts.asset.FungibleAsset.Commands.Move command"
|
||||||
|
|
||||||
tweak {
|
tweak {
|
||||||
@ -817,7 +817,7 @@ class ObligationTests {
|
|||||||
5000.DOLLARS.quantity, MINI_CORP_PUBKEY)
|
5000.DOLLARS.quantity, MINI_CORP_PUBKEY)
|
||||||
val amount = fiveKDollarsFromMegaToMini.amount
|
val amount = fiveKDollarsFromMegaToMini.amount
|
||||||
val expected = mapOf(Pair(Pair(MEGA_CORP_PUBKEY, MINI_CORP_PUBKEY), Amount(amount.quantity, amount.token.product)))
|
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)
|
assertEquals(expected, actual)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -843,7 +843,7 @@ class ObligationTests {
|
|||||||
val expected = mapOf(
|
val expected = mapOf(
|
||||||
Pair(Pair(BOB_PUBKEY, ALICE_PUBKEY), Amount(100000000, GBP))
|
Pair(Pair(BOB_PUBKEY, ALICE_PUBKEY), Amount(100000000, GBP))
|
||||||
)
|
)
|
||||||
val actual = netAmountsDue<Currency>(balanced)
|
val actual = netAmountsDue(balanced)
|
||||||
assertEquals(expected, actual)
|
assertEquals(expected, actual)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -28,7 +28,7 @@ import java.util.*;
|
|||||||
* same as the original author of the R3 repository.
|
* same as the original author of the R3 repository.
|
||||||
*/
|
*/
|
||||||
public class Base58 {
|
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 char ENCODED_ZERO = ALPHABET[0];
|
||||||
private static final int[] INDEXES = new int[128];
|
private static final int[] INDEXES = new int[128];
|
||||||
|
|
||||||
|
@ -20,14 +20,18 @@ import kotlin.concurrent.withLock
|
|||||||
import kotlin.reflect.KProperty
|
import kotlin.reflect.KProperty
|
||||||
|
|
||||||
val Int.days: Duration get() = Duration.ofDays(this.toLong())
|
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())
|
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.minutes: Duration get() = Duration.ofMinutes(this.toLong())
|
||||||
val Int.seconds: Duration get() = Duration.ofSeconds(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)
|
// TODO: Review by EOY2016 if we ever found these utilities helpful.
|
||||||
val String.bd: BigDecimal get() = BigDecimal(this)
|
@Suppress("unused") val Int.bd: BigDecimal get() = BigDecimal(this)
|
||||||
val Long.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) + "…"
|
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 }
|
* val ii = state.locked { i }
|
||||||
*/
|
*/
|
||||||
class ThreadBox<out T>(content: T, val lock: ReentrantLock = ReentrantLock()) {
|
class ThreadBox<out T>(val content: T, val lock: ReentrantLock = ReentrantLock()) {
|
||||||
val content = content
|
|
||||||
inline fun <R> locked(body: T.() -> R): R = lock.withLock { body(content) }
|
inline fun <R> locked(body: T.() -> R): R = lock.withLock { body(content) }
|
||||||
inline fun <R> alreadyLocked(body: T.() -> R): R {
|
inline fun <R> alreadyLocked(body: T.() -> R): R {
|
||||||
check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." })
|
check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." })
|
||||||
|
@ -41,8 +41,8 @@ val Int.FCOJ: Amount<Commodity> get() = FCOJ(this)
|
|||||||
infix fun Currency.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
|
infix fun Currency.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
|
||||||
infix fun Commodity.`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 Amount<Currency>.`issued by`(deposit: PartyAndReference) = issuedBy(deposit)
|
||||||
infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued<Currency>(deposit, this)
|
infix fun Currency.issuedBy(deposit: PartyAndReference) = Issued(deposit, this)
|
||||||
infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued<Commodity>(deposit, this)
|
infix fun Commodity.issuedBy(deposit: PartyAndReference) = Issued(deposit, this)
|
||||||
infix fun Amount<Currency>.issuedBy(deposit: PartyAndReference) = Amount(quantity, token.issuedBy(deposit))
|
infix fun Amount<Currency>.issuedBy(deposit: PartyAndReference) = Amount(quantity, token.issuedBy(deposit))
|
||||||
|
|
||||||
//// Requirements /////////////////////////////////////////////////////////////////////////////////////////////////////
|
//// Requirements /////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
@ -64,7 +64,7 @@ inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>
|
|||||||
filter { it.value is T }.
|
filter { it.value is T }.
|
||||||
filter { if (signer == null) true else signer in it.signers }.
|
filter { if (signer == null) true else signer in it.signers }.
|
||||||
filter { if (party == null) true else party in it.signingParties }.
|
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. */
|
/** 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>?,
|
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 { it.value is T }.
|
||||||
filter { if (signers == null) true else it.signers.containsAll(signers)}.
|
filter { if (signers == null) true else it.signers.containsAll(signers)}.
|
||||||
filter { if (parties == null) true else it.signingParties.containsAll(parties) }.
|
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 {
|
inline fun <reified T : CommandData> Collection<AuthenticatedObject<CommandData>>.requireSingleCommand() = try {
|
||||||
select<T>().single()
|
select<T>().single()
|
||||||
@ -99,7 +99,7 @@ fun List<AuthenticatedObject<CommandData>>.getTimestampBy(timestampingAuthority:
|
|||||||
fun List<AuthenticatedObject<CommandData>>.getTimestampByName(vararg names: String): TimestampCommand? {
|
fun List<AuthenticatedObject<CommandData>>.getTimestampByName(vararg names: String): TimestampCommand? {
|
||||||
val timestampCmd = filter { it.value is TimestampCommand }.singleOrNull() ?: return null
|
val timestampCmd = filter { it.value is TimestampCommand }.singleOrNull() ?: return null
|
||||||
val tsaNames = timestampCmd.signingParties.map { it.name.toLowerCase() }
|
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()
|
val acceptableNameFound = tsaNames.intersect(acceptableNames).isNotEmpty()
|
||||||
if (acceptableNameFound)
|
if (acceptableNameFound)
|
||||||
return timestampCmd.value as TimestampCommand
|
return timestampCmd.value as TimestampCommand
|
||||||
|
@ -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>>.sumOrNull() = if (!iterator().hasNext()) null else sumOrThrow()
|
||||||
fun <T> Iterable<Amount<T>>.sumOrThrow() = reduce { left, right -> left + right }
|
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()
|
return daysToMaturity.toInt()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun toString(): String = "$name"
|
override fun toString(): String = name
|
||||||
|
|
||||||
enum class TimeUnit(val code: String) {
|
enum class TimeUnit(val code: String) {
|
||||||
Day("D"), Week("W"), Month("M"), Year("Y")
|
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
|
* 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).
|
* 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) {
|
enum class Frequency(val annualCompoundCount: Int) {
|
||||||
Annual(1) {
|
Annual(1) {
|
||||||
override fun offset(d: LocalDate, n: Long) = d.plusYears(1 * n)
|
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)
|
fun LocalDate.isWorkingDay(accordingToCalendar: BusinessCalendar): Boolean = accordingToCalendar.isWorkingDay(this)
|
||||||
|
|
||||||
// TODO: Make Calendar data come from an oracle
|
// 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
|
* 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.
|
* 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")
|
class UnknownCalendar(name: String) : Exception("$name not found")
|
||||||
|
|
||||||
companion object {
|
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)
|
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. */
|
/** 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(",") }.
|
calname.flatMap { (TEST_CALENDAR_DATA[it] ?: throw UnknownCalendar(it)).split(",") }.
|
||||||
toSet().
|
toSet().
|
||||||
map { parseDateFromString(it) }.
|
map { parseDateFromString(it) }.
|
||||||
@ -426,7 +428,7 @@ data class Commodity(val symbol: String,
|
|||||||
val commodityCode: String = symbol,
|
val commodityCode: String = symbol,
|
||||||
val defaultFractionDigits: Int = 0) {
|
val defaultFractionDigits: Int = 0) {
|
||||||
companion object {
|
companion object {
|
||||||
private val registry = mapOf<String, Commodity>(
|
private val registry = mapOf(
|
||||||
Pair("FCOJ", Commodity("FCOJ", "Frozen concentrated orange juice"))
|
Pair("FCOJ", Commodity("FCOJ", "Frozen concentrated orange juice"))
|
||||||
)
|
)
|
||||||
fun getInstance(symbol: String): Commodity?
|
fun getInstance(symbol: String): Commodity?
|
||||||
|
@ -40,7 +40,7 @@ interface BilateralNettableState<N: BilateralNettableState<N>> {
|
|||||||
/**
|
/**
|
||||||
* Interface for state objects that support being netted with other state objects.
|
* 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
|
* 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.
|
* equal objects, they can be close out netted together.
|
||||||
|
@ -21,11 +21,6 @@ data class TransactionForContract(val inputs: List<ContractState>,
|
|||||||
override fun hashCode() = origHash.hashCode()
|
override fun hashCode() = origHash.hashCode()
|
||||||
override fun equals(other: Any?) = other is TransactionForContract && other.origHash == origHash
|
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
|
* 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
|
* can be processed as one. The grouping key is any arbitrary object that can act as a map key (so must implement
|
||||||
|
@ -19,7 +19,7 @@ interface GroupVerify<in S, in T : Any> {
|
|||||||
token: T): Set<CommandData>
|
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 class GroupClauseVerifier<S : ContractState, T : Any> : SingleClause {
|
||||||
abstract val clauses: List<GroupClause<S, T>>
|
abstract val clauses: List<GroupClause<S, T>>
|
||||||
|
@ -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
|
* signature. It isn't used currently, but experience from Bitcoin suggests such a feature is useful, especially when
|
||||||
* building partially signed transactions.
|
* 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. */
|
/** 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: ByteArray) = by.verifyWithECDSA(content, this)
|
||||||
fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bits, this)
|
fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bits, this)
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.r3corda.core.messaging
|
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.node.services.DEFAULT_SESSION_ID
|
||||||
import com.r3corda.core.serialization.DeserializeAsKotlinObjectDef
|
import com.r3corda.core.serialization.DeserializeAsKotlinObjectDef
|
||||||
import com.r3corda.core.serialization.serialize
|
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
|
fun isBlank() = topic.isBlank() && sessionID == DEFAULT_SESSION_ID
|
||||||
|
|
||||||
override fun toString(): String = "${topic}.${sessionID}"
|
override fun toString(): String = "$topic.$sessionID"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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
|
* 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(π)).
|
* 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,
|
fun project(screenWidth: Double, screenHeight: Double, topLatitude: Double, bottomLatitude: Double,
|
||||||
leftLongitude: Double, rightLongitude: Double): Pair<Double, Double> {
|
leftLongitude: Double, rightLongitude: Double): Pair<Double, Double> {
|
||||||
require(latitude in bottomLatitude..topLatitude)
|
require(latitude in bottomLatitude..topLatitude)
|
||||||
|
@ -46,7 +46,7 @@ class ProtocolLogicRefFactory(private val protocolWhitelist: Map<String, Set<Str
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
// TODO: make this specific to the attachments in the [AppContext] by including [SecureHash] in whitelist check
|
// 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" }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -18,7 +18,6 @@ import com.r3corda.core.utilities.NonEmptySetSerializer
|
|||||||
import de.javakaffee.kryoserializers.ArraysAsListSerializer
|
import de.javakaffee.kryoserializers.ArraysAsListSerializer
|
||||||
import net.i2p.crypto.eddsa.EdDSAPrivateKey
|
import net.i2p.crypto.eddsa.EdDSAPrivateKey
|
||||||
import net.i2p.crypto.eddsa.EdDSAPublicKey
|
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.EdDSAPrivateKeySpec
|
||||||
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
|
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
|
||||||
import org.objenesis.strategy.StdInstantiatorStrategy
|
import org.objenesis.strategy.StdInstantiatorStrategy
|
||||||
@ -414,9 +413,7 @@ object ReferencesAwareJavaSerializer : JavaSerializer() {
|
|||||||
super.read(kryo, input, type)
|
super.read(kryo, input, type)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ObjectInputStream(input).use {
|
ObjectInputStream(input).use(ObjectInputStream::readObject)
|
||||||
it.readObject()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -105,7 +105,7 @@ data class SingletonSerializationToken private constructor(private val className
|
|||||||
constructor(toBeTokenized: SerializeAsToken) : this(toBeTokenized.javaClass.name)
|
constructor(toBeTokenized: SerializeAsToken) : this(toBeTokenized.javaClass.name)
|
||||||
|
|
||||||
override fun fromToken(context: SerializeAsTokenContext): Any = context.tokenToTokenized[this] ?:
|
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 {
|
companion object {
|
||||||
fun registerWithContext(token: SingletonSerializationToken, toBeTokenized: SerializeAsToken, context: SerializeAsTokenContext): SerializationToken =
|
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.
|
* to indicate which instance the token is a serialized form of.
|
||||||
*/
|
*/
|
||||||
abstract class SingletonSerializeAsToken() : SerializeAsToken {
|
abstract class SingletonSerializeAsToken() : SerializeAsToken {
|
||||||
|
@Suppress("LeakingThis")
|
||||||
private val token = SingletonSerializationToken(this)
|
private val token = SingletonSerializationToken(this)
|
||||||
|
|
||||||
override fun toToken(context: SerializeAsTokenContext) = SingletonSerializationToken.registerWithContext(token, this, context)
|
override fun toToken(context: SerializeAsTokenContext) = SingletonSerializationToken.registerWithContext(token, this, context)
|
||||||
|
@ -52,7 +52,6 @@ val DUMMY_PUBKEY_2: PublicKey get() = DummyPublicKey("x2")
|
|||||||
|
|
||||||
val DUMMY_KEY_1: KeyPair by lazy { generateKeyPair() }
|
val DUMMY_KEY_1: KeyPair by lazy { generateKeyPair() }
|
||||||
val DUMMY_KEY_2: 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_KEY: KeyPair by lazy { generateKeyPair() }
|
||||||
val ALICE_PUBKEY: PublicKey get() = ALICE_KEY.public
|
val ALICE_PUBKEY: PublicKey get() = ALICE_KEY.public
|
||||||
|
@ -150,12 +150,6 @@ class LedgerDSL<out T : TransactionDSLInterpreter, out L : LedgerDSLInterpreter<
|
|||||||
inline fun <reified S : ContractState> String.output(): S =
|
inline fun <reified S : ContractState> String.output(): S =
|
||||||
outputStateAndRef<S>().state.data
|
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
|
* @see OutputStateLookup.retrieveOutputStateAndRef
|
||||||
*/
|
*/
|
||||||
|
@ -40,7 +40,7 @@ import java.util.*
|
|||||||
message = "ledger doesn't nest, use tweak",
|
message = "ledger doesn't nest, use tweak",
|
||||||
replaceWith = ReplaceWith("tweak"),
|
replaceWith = ReplaceWith("tweak"),
|
||||||
level = DeprecationLevel.ERROR)
|
level = DeprecationLevel.ERROR)
|
||||||
@Suppress("UNUSED_PARAMETER")
|
@Suppress("UNUSED_PARAMETER", "unused")
|
||||||
fun TransactionDSLInterpreter.ledger(
|
fun TransactionDSLInterpreter.ledger(
|
||||||
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
|
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
|
||||||
}
|
}
|
||||||
@ -49,7 +49,7 @@ fun TransactionDSLInterpreter.ledger(
|
|||||||
message = "transaction doesn't nest, use tweak",
|
message = "transaction doesn't nest, use tweak",
|
||||||
replaceWith = ReplaceWith("tweak"),
|
replaceWith = ReplaceWith("tweak"),
|
||||||
level = DeprecationLevel.ERROR)
|
level = DeprecationLevel.ERROR)
|
||||||
@Suppress("UNUSED_PARAMETER")
|
@Suppress("UNUSED_PARAMETER", "unused")
|
||||||
fun TransactionDSLInterpreter.transaction(
|
fun TransactionDSLInterpreter.transaction(
|
||||||
dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail) {
|
dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail) {
|
||||||
}
|
}
|
||||||
@ -58,7 +58,7 @@ fun TransactionDSLInterpreter.transaction(
|
|||||||
message = "ledger doesn't nest, use tweak",
|
message = "ledger doesn't nest, use tweak",
|
||||||
replaceWith = ReplaceWith("tweak"),
|
replaceWith = ReplaceWith("tweak"),
|
||||||
level = DeprecationLevel.ERROR)
|
level = DeprecationLevel.ERROR)
|
||||||
@Suppress("UNUSED_PARAMETER")
|
@Suppress("UNUSED_PARAMETER", "unused")
|
||||||
fun LedgerDSLInterpreter<TransactionDSLInterpreter>.ledger(
|
fun LedgerDSLInterpreter<TransactionDSLInterpreter>.ledger(
|
||||||
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
|
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit) {
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@ import java.util.*
|
|||||||
* The underlying set is exposed for Kryo to access, but should not be accessed directly.
|
* The underlying set is exposed for Kryo to access, but should not be accessed directly.
|
||||||
*/
|
*/
|
||||||
class NonEmptySet<T>(initial: T) : MutableSet<T> {
|
class NonEmptySet<T>(initial: T) : MutableSet<T> {
|
||||||
private val set: MutableSet<T> = HashSet<T>()
|
private val set: MutableSet<T> = HashSet()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
set.add(initial)
|
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 containsAll(elements: Collection<T>): Boolean = set.containsAll(elements)
|
||||||
override fun isEmpty(): Boolean = false
|
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 =
|
override fun remove(element: T): Boolean =
|
||||||
// Test either there's more than one element, or the removal is a no-op
|
// 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 =
|
override fun equals(other: Any?): Boolean =
|
||||||
if (other is Set<*>)
|
if (other is Set<*>)
|
||||||
// Delegate down to the wrapped set's equals() function
|
// Delegate down to the wrapped set's equals() function
|
||||||
set.equals(other)
|
set == other
|
||||||
else
|
else
|
||||||
false
|
false
|
||||||
|
|
||||||
@ -84,7 +84,7 @@ class NonEmptySet<T>(initial: T) : MutableSet<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun <T> nonEmptySetOf(initial: T, vararg elements: T): NonEmptySet<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
|
// We add the first element twice, but it's a set, so who cares
|
||||||
set.addAll(elements)
|
set.addAll(elements)
|
||||||
return set
|
return set
|
||||||
|
@ -151,6 +151,7 @@ class ProgressTracker(vararg steps: Step) {
|
|||||||
var parent: ProgressTracker? = null
|
var parent: ProgressTracker? = null
|
||||||
private set
|
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' */
|
/** Walks up the tree to find the top level tracker. If this is the top level tracker, returns 'this' */
|
||||||
val topLevelTracker: ProgressTracker
|
val topLevelTracker: ProgressTracker
|
||||||
get() {
|
get() {
|
||||||
|
@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
@ -35,9 +35,9 @@ abstract class AbstractStateReplacementProtocol<T> {
|
|||||||
override val replyToParty: Party,
|
override val replyToParty: Party,
|
||||||
override val sessionID: Long) : PartyRequestMessage
|
override val sessionID: Long) : PartyRequestMessage
|
||||||
|
|
||||||
abstract class Instigator<S : ContractState, T>(val originalState: StateAndRef<S>,
|
abstract class Instigator<out S : ContractState, T>(val originalState: StateAndRef<S>,
|
||||||
val modification: T,
|
val modification: T,
|
||||||
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<StateAndRef<S>>() {
|
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<StateAndRef<S>>() {
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
object SIGNING : ProgressTracker.Step("Requesting signatures from other parties")
|
object SIGNING : ProgressTracker.Step("Requesting signatures from other parties")
|
||||||
@ -117,10 +117,10 @@ abstract class AbstractStateReplacementProtocol<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class Acceptor<T>(val otherSide: Party,
|
abstract class Acceptor<in T>(val otherSide: Party,
|
||||||
val sessionIdForSend: Long,
|
val sessionIdForSend: Long,
|
||||||
val sessionIdForReceive: Long,
|
val sessionIdForReceive: Long,
|
||||||
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<Unit>() {
|
override val progressTracker: ProgressTracker = tracker()) : ProtocolLogic<Unit>() {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
object VERIFYING : ProgressTracker.Step("Verifying state replacement proposal")
|
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?) {
|
class StateReplacementRefused(val identity: Party, val state: StateRef, val detail: String?) {
|
||||||
override fun toString(): String
|
override fun toString() = "A participant $identity refused to change state $state: " + (detail ?: "no reason provided")
|
||||||
= "A participant $identity refused to change state $state"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class StateReplacementException(val error: StateReplacementRefused)
|
class StateReplacementException(val error: StateReplacementRefused) : Exception("State change failed - $error")
|
||||||
: Exception("State change failed - $error")
|
|
@ -11,6 +11,7 @@ import com.r3corda.core.protocols.ProtocolLogic
|
|||||||
import com.r3corda.core.random63BitValue
|
import com.r3corda.core.random63BitValue
|
||||||
import com.r3corda.core.utilities.ProgressTracker
|
import com.r3corda.core.utilities.ProgressTracker
|
||||||
import com.r3corda.core.utilities.suggestInterestRateAnnouncementTimeWindow
|
import com.r3corda.core.utilities.suggestInterestRateAnnouncementTimeWindow
|
||||||
|
import com.r3corda.protocols.RatesFixProtocol.FixOutOfRange
|
||||||
import java.math.BigDecimal
|
import java.math.BigDecimal
|
||||||
import java.time.Duration
|
import java.time.Duration
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
@ -46,7 +47,7 @@ open class RatesFixProtocol(protected val tx: TransactionBuilder,
|
|||||||
|
|
||||||
override val topic: String get() = TOPIC
|
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 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
|
data class SignRequest(val tx: WireTransaction, override val replyToParty: Party, override val sessionID: Long) : PartyRequestMessage
|
||||||
|
@ -157,9 +157,7 @@ object TwoPartyDealProtocol {
|
|||||||
if (regulators.isNotEmpty()) {
|
if (regulators.isNotEmpty()) {
|
||||||
// Copy the transaction to every regulator in the network. This is obviously completely bogus, it's
|
// Copy the transaction to every regulator in the network. This is obviously completely bogus, it's
|
||||||
// just for demo purposes.
|
// just for demo purposes.
|
||||||
for (regulator in regulators) {
|
regulators.forEach { send(it.identity, DEFAULT_SESSION_ID, fullySigned) }
|
||||||
send(regulator.identity, DEFAULT_SESSION_ID, fullySigned)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return fullySigned
|
return fullySigned
|
||||||
@ -276,12 +274,12 @@ object TwoPartyDealProtocol {
|
|||||||
/**
|
/**
|
||||||
* One side of the protocol for inserting a pre-agreed deal.
|
* One side of the protocol for inserting a pre-agreed deal.
|
||||||
*/
|
*/
|
||||||
open class Instigator<T : DealState>(override val otherSide: Party,
|
open class Instigator<out T : DealState>(override val otherSide: Party,
|
||||||
val notary: Party,
|
val notary: Party,
|
||||||
override val payload: T,
|
override val payload: T,
|
||||||
override val myKeyPair: KeyPair,
|
override val myKeyPair: KeyPair,
|
||||||
override val otherSessionID: Long,
|
override val otherSessionID: Long,
|
||||||
override val progressTracker: ProgressTracker = Primary.tracker()) : Primary<T>() {
|
override val progressTracker: ProgressTracker = Primary.tracker()) : Primary<T>() {
|
||||||
|
|
||||||
override val notaryNode: NodeInfo get() =
|
override val notaryNode: NodeInfo get() =
|
||||||
serviceHub.networkMapCache.notaryNodes.filter { it.identity == notary }.single()
|
serviceHub.networkMapCache.notaryNodes.filter { it.identity == notary }.single()
|
||||||
@ -378,7 +376,7 @@ object TwoPartyDealProtocol {
|
|||||||
val newDeal = deal
|
val newDeal = deal
|
||||||
|
|
||||||
val ptx = TransactionType.General.Builder()
|
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
|
@Suspendable
|
||||||
override fun beforeSigning(fix: Fix) {
|
override fun beforeSigning(fix: Fix) {
|
||||||
newDeal.generateFix(ptx, StateAndRef(txState, handshake.payload), fix)
|
newDeal.generateFix(ptx, StateAndRef(txState, handshake.payload), fix)
|
||||||
|
@ -8,23 +8,23 @@ import java.util.*;
|
|||||||
|
|
||||||
public class ProtocolLogicRefFromJavaTest {
|
public class ProtocolLogicRefFromJavaTest {
|
||||||
|
|
||||||
public static class ParamType1 {
|
private static class ParamType1 {
|
||||||
public final int value;
|
final int value;
|
||||||
|
|
||||||
ParamType1(int v) {
|
ParamType1(int v) {
|
||||||
value = v;
|
value = v;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ParamType2 {
|
private static class ParamType2 {
|
||||||
public final String value;
|
final String value;
|
||||||
|
|
||||||
ParamType2(String v) {
|
ParamType2(String v) {
|
||||||
value = v;
|
value = v;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class JavaProtocolLogic extends ProtocolLogic<Void> {
|
private static class JavaProtocolLogic extends ProtocolLogic<Void> {
|
||||||
|
|
||||||
public JavaProtocolLogic(ParamType1 A, ParamType2 b) {
|
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() {
|
public JavaNoArgProtocolLogic() {
|
||||||
}
|
}
|
||||||
@ -72,8 +72,7 @@ public class ProtocolLogicRefFromJavaTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testNoArg() {
|
public void testNoArg() {
|
||||||
Map<String, Set<String>> whiteList = new HashMap<>();
|
Map<String, Set<String>> whiteList = new HashMap<>();
|
||||||
Set<String> argsList = new HashSet<>();
|
whiteList.put(JavaNoArgProtocolLogic.class.getName(), new HashSet<>());
|
||||||
whiteList.put(JavaNoArgProtocolLogic.class.getName(), argsList);
|
|
||||||
ProtocolLogicRefFactory factory = new ProtocolLogicRefFactory(whiteList);
|
ProtocolLogicRefFactory factory = new ProtocolLogicRefFactory(whiteList);
|
||||||
factory.create(JavaNoArgProtocolLogic.class);
|
factory.create(JavaNoArgProtocolLogic.class);
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ class FinanceTypesTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `make sure Amount has decimal places`() {
|
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())
|
assert("0.01" in x.toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,17 +44,17 @@ class FinanceTypesTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `schedule generator 1`() {
|
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.
|
// 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)
|
println(ret)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `schedule generator 2`() {
|
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!
|
// 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)
|
println(ret)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,7 +126,7 @@ class FinanceTypesTest {
|
|||||||
)
|
)
|
||||||
|
|
||||||
for ((inc, exp) in expected) {
|
for ((inc, exp) in expected) {
|
||||||
var result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc)
|
val result = ldn.moveBusinessDays(firstDay, DateRollDirection.FORWARD, inc)
|
||||||
assertEquals(exp, result)
|
assertEquals(exp, result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -146,7 +146,7 @@ class FinanceTypesTest {
|
|||||||
)
|
)
|
||||||
|
|
||||||
for ((inc, exp) in expected) {
|
for ((inc, exp) in expected) {
|
||||||
var result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc)
|
val result = ldn.moveBusinessDays(firstDay, DateRollDirection.BACKWARD, inc)
|
||||||
assertEquals(exp, result)
|
assertEquals(exp, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,6 +13,8 @@ import kotlin.test.assertEquals
|
|||||||
import kotlin.test.assertFailsWith
|
import kotlin.test.assertFailsWith
|
||||||
import kotlin.test.assertTrue
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
// 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 {
|
class WhitelistTrustManagerTest {
|
||||||
companion object {
|
companion object {
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
|
@ -11,7 +11,6 @@ import java.io.DataOutputStream
|
|||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.net.InetAddress
|
import java.net.InetAddress
|
||||||
import java.net.InetSocketAddress
|
import java.net.InetSocketAddress
|
||||||
import java.nio.file.Paths
|
|
||||||
import java.security.PrivateKey
|
import java.security.PrivateKey
|
||||||
import java.security.SecureRandom
|
import java.security.SecureRandom
|
||||||
import java.security.Signature
|
import java.security.Signature
|
||||||
@ -196,7 +195,7 @@ class X509UtilitiesTest {
|
|||||||
val context = SSLContext.getInstance("TLS")
|
val context = SSLContext.getInstance("TLS")
|
||||||
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
|
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
|
||||||
keyManagerFactory.init(keyStore, "serverstorepass".toCharArray())
|
keyManagerFactory.init(keyStore, "serverstorepass".toCharArray())
|
||||||
val keyManagers = keyManagerFactory.getKeyManagers()
|
val keyManagers = keyManagerFactory.keyManagers
|
||||||
val trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
|
val trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
|
||||||
trustMgrFactory.init(trustStore)
|
trustMgrFactory.init(trustStore)
|
||||||
val trustManagers = trustMgrFactory.trustManagers
|
val trustManagers = trustMgrFactory.trustManagers
|
||||||
|
@ -10,7 +10,7 @@ class ProtocolLogicRefTest {
|
|||||||
data class ParamType1(val value: Int)
|
data class ParamType1(val value: Int)
|
||||||
data class ParamType2(val value: String)
|
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>() {
|
class KotlinProtocolLogic(A: ParamType1, b: ParamType2) : ProtocolLogic<Unit>() {
|
||||||
constructor() : this(ParamType1(1), ParamType2("2"))
|
constructor() : this(ParamType1(1), ParamType2("2"))
|
||||||
|
|
||||||
@ -22,22 +22,18 @@ class ProtocolLogicRefTest {
|
|||||||
|
|
||||||
constructor(kotlinType: Int) : this(ParamType1(kotlinType), ParamType2("b"))
|
constructor(kotlinType: Int) : this(ParamType1(kotlinType), ParamType2("b"))
|
||||||
|
|
||||||
override fun call(): Unit {
|
override fun call() = Unit
|
||||||
}
|
|
||||||
|
|
||||||
override val topic: String get() = throw UnsupportedOperationException()
|
override val topic: String get() = throw UnsupportedOperationException()
|
||||||
}
|
}
|
||||||
|
|
||||||
class KotlinNoArgProtocolLogic : ProtocolLogic<Unit>() {
|
class KotlinNoArgProtocolLogic : ProtocolLogic<Unit>() {
|
||||||
override fun call(): Unit {
|
override fun call() = Unit
|
||||||
}
|
|
||||||
override val topic: String get() = throw UnsupportedOperationException()
|
override val topic: String get() = throw UnsupportedOperationException()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("UNUSED_PARAMETER") // We will never use A or b
|
@Suppress("UNUSED_PARAMETER") // We will never use A or b
|
||||||
class NotWhiteListedKotlinProtocolLogic(A: Int, b: String) : ProtocolLogic<Unit>() {
|
class NotWhiteListedKotlinProtocolLogic(A: Int, b: String) : ProtocolLogic<Unit>() {
|
||||||
override fun call(): Unit {
|
override fun call() = Unit
|
||||||
}
|
|
||||||
override val topic: String get() = throw UnsupportedOperationException()
|
override val topic: String get() = throw UnsupportedOperationException()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,5 +95,4 @@ class ProtocolLogicRefTest {
|
|||||||
val args = mapOf(Pair("kotlinType", 3))
|
val args = mapOf(Pair("kotlinType", 3))
|
||||||
factory.createKotlin(KotlinProtocolLogic::class.java, args)
|
factory.createKotlin(KotlinProtocolLogic::class.java, args)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,6 @@ package com.r3corda.core.serialization
|
|||||||
|
|
||||||
import com.r3corda.core.contracts.*
|
import com.r3corda.core.contracts.*
|
||||||
import com.r3corda.core.crypto.SecureHash
|
import com.r3corda.core.crypto.SecureHash
|
||||||
import com.r3corda.core.crypto.newSecureRandom
|
|
||||||
import com.r3corda.core.seconds
|
import com.r3corda.core.seconds
|
||||||
import com.r3corda.core.testing.*
|
import com.r3corda.core.testing.*
|
||||||
import org.junit.Before
|
import org.junit.Before
|
||||||
@ -34,8 +33,6 @@ class TransactionSerializationTests {
|
|||||||
}
|
}
|
||||||
interface Commands : CommandData {
|
interface Commands : CommandData {
|
||||||
class Move() : TypeOnlyCommandData(), Commands
|
class Move() : TypeOnlyCommandData(), Commands
|
||||||
data class Issue(val nonce: Long = newSecureRandom().nextLong()) : Commands
|
|
||||||
data class Exit(val amount: Amount<Currency>) : Commands
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -111,7 +111,9 @@ class ProgressTrackerTest {
|
|||||||
pt.setChildProgressTracker(SimpleSteps.TWO, pt2)
|
pt.setChildProgressTracker(SimpleSteps.TWO, pt2)
|
||||||
class Tmp {
|
class Tmp {
|
||||||
val unserializable = Unserializable()
|
val unserializable = Unserializable()
|
||||||
val subscription = pt2.changes.subscribe { unserializable.foo() }
|
init {
|
||||||
|
pt2.changes.subscribe { unserializable.foo() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Tmp()
|
Tmp()
|
||||||
pt.serialize(kryo)
|
pt.serialize(kryo)
|
||||||
|
@ -0,0 +1,4 @@
|
|||||||
|
package com.r3corda.protocols
|
||||||
|
|
||||||
|
class ResolveTransactionsProtocolTest {
|
||||||
|
}
|
@ -19,7 +19,7 @@ interface Arrangement
|
|||||||
// A base arrangement with no rights and no obligations. Contract cancellation/termination is a transition to ``Zero``.
|
// A base arrangement with no rights and no obligations. Contract cancellation/termination is a transition to ``Zero``.
|
||||||
class Zero() : Arrangement {
|
class Zero() : Arrangement {
|
||||||
override fun hashCode(): Int {
|
override fun hashCode(): Int {
|
||||||
return 0;
|
return 0
|
||||||
}
|
}
|
||||||
override fun equals(other: Any?): Boolean {
|
override fun equals(other: Any?): Boolean {
|
||||||
return other is Zero
|
return other is Zero
|
||||||
|
@ -34,7 +34,7 @@ fun liableParties(contract: Arrangement) : Set<PublicKey> {
|
|||||||
throw IllegalArgumentException()
|
throw IllegalArgumentException()
|
||||||
}
|
}
|
||||||
|
|
||||||
return visit(contract);
|
return visit(contract)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** returns list of involved parties for a given contract */
|
/** returns list of involved parties for a given contract */
|
||||||
@ -53,7 +53,7 @@ fun involvedParties(arrangement: Arrangement) : Set<PublicKey> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return visit(arrangement);
|
return visit(arrangement)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun replaceParty(action: Action, from: Party, to: Party) : Action {
|
fun replaceParty(action: Action, from: Party, to: Party) : Action {
|
||||||
|
@ -36,7 +36,7 @@ class BillOfLadingAgreementTests {
|
|||||||
quantity = 2500.0,
|
quantity = 2500.0,
|
||||||
unit = LocDataStructures.WeightUnit.KG
|
unit = LocDataStructures.WeightUnit.KG
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
val Bill = BillOfLadingAgreement.State(
|
val Bill = BillOfLadingAgreement.State(
|
||||||
owner = MEGA_CORP_PUBKEY,
|
owner = MEGA_CORP_PUBKEY,
|
||||||
beneficiary = BOB,
|
beneficiary = BOB,
|
||||||
@ -149,14 +149,14 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are multiple commands
|
//There are multiple commands
|
||||||
this.`fails with`("List has more than one element.");
|
this `fails with` "List has more than one element."
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
input { Bill }
|
input { Bill }
|
||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are no commands
|
//There are no commands
|
||||||
this.`fails with`("Required ${BillOfLadingAgreement.Commands::class.qualifiedName} command");
|
this `fails with` "Required ${BillOfLadingAgreement.Commands::class.qualifiedName} command"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -167,7 +167,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill }
|
output { Bill }
|
||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.verifies();
|
this.verifies()
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -175,14 +175,14 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("there is no input state");
|
this `fails with` "there is no input state"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
output { Bill }
|
output { Bill }
|
||||||
command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.IssueBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the carrier");
|
this `fails with` "the transaction is signed by the carrier"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -194,7 +194,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.verifies();
|
this.verifies()
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -202,7 +202,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
//There is no timestamp
|
//There is no timestamp
|
||||||
this.`fails with`("must be timestamped");
|
this `fails with` "must be timestamped"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -212,7 +212,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are two inputs
|
//There are two inputs
|
||||||
this.`fails with`("List has more than one element.");
|
this `fails with` "List has more than one element."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -220,7 +220,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are no inputs
|
//There are no inputs
|
||||||
this.`fails with`("List is empty.");
|
this `fails with` "List is empty."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -230,7 +230,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are two outputs
|
//There are two outputs
|
||||||
this.`fails with`("List has more than one element.");
|
this `fails with` "List has more than one element."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -238,7 +238,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are no outputs
|
//There are no outputs
|
||||||
this.`fails with`("List is empty.");
|
this `fails with` "List is empty."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -246,7 +246,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the beneficiary");
|
this `fails with` "the transaction is signed by the beneficiary"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -254,7 +254,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE) }
|
||||||
command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the state object owner");
|
this `fails with` "the transaction is signed by the state object owner"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -262,7 +262,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE, props = pros.copy(nameOfVessel = "Svet")) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, beneficiary = CHARLIE, props = pros.copy(nameOfVessel = "Svet")) }
|
||||||
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(MEGA_CORP_PUBKEY, BOB_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the bill of lading agreement properties are unchanged");
|
this `fails with` "the bill of lading agreement properties are unchanged"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -274,7 +274,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.verifies();
|
this.verifies()
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -282,7 +282,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
//There is no timestamp
|
//There is no timestamp
|
||||||
this.`fails with`("must be timestamped");
|
this `fails with` "must be timestamped"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -292,7 +292,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are two inputs
|
//There are two inputs
|
||||||
this.`fails with`("List has more than one element.");
|
this `fails with` "List has more than one element."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -300,7 +300,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are no inputs
|
//There are no inputs
|
||||||
this.`fails with`("List is empty.");
|
this `fails with` "List is empty."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -310,7 +310,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are two outputs
|
//There are two outputs
|
||||||
this.`fails with`("List has more than one element.");
|
this `fails with` "List has more than one element."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -318,7 +318,7 @@ class BillOfLadingAgreementTests {
|
|||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
//There are no outputs
|
//There are no outputs
|
||||||
this.`fails with`("List is empty.");
|
this `fails with` "List is empty."
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -326,7 +326,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY) }
|
||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the state object owner");
|
this `fails with` "the transaction is signed by the state object owner"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -334,7 +334,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY,beneficiary = CHARLIE) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY,beneficiary = CHARLIE) }
|
||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the beneficiary is unchanged");
|
this `fails with` "the beneficiary is unchanged"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -343,7 +343,7 @@ class BillOfLadingAgreementTests {
|
|||||||
output { Bill.copy(owner = CHARLIE_PUBKEY, props = pros.copy(nameOfVessel = "Svet")) }
|
output { Bill.copy(owner = CHARLIE_PUBKEY, props = pros.copy(nameOfVessel = "Svet")) }
|
||||||
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
command(MEGA_CORP_PUBKEY) { BillOfLadingAgreement.Commands.TransferPossession() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the bill of lading agreement properties are unchanged");
|
this `fails with` "the bill of lading agreement properties are unchanged"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -73,7 +73,7 @@ class InvoiceTests {
|
|||||||
this `fails with` "the transaction is signed by the invoice owner"
|
this `fails with` "the transaction is signed by the invoice owner"
|
||||||
}
|
}
|
||||||
|
|
||||||
var props = invoiceProperties.copy(seller = invoiceProperties.buyer);
|
var props = invoiceProperties.copy(seller = invoiceProperties.buyer)
|
||||||
transaction {
|
transaction {
|
||||||
output { initialInvoiceState.copy(props = props) }
|
output { initialInvoiceState.copy(props = props) }
|
||||||
command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() }
|
command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() }
|
||||||
@ -88,7 +88,7 @@ class InvoiceTests {
|
|||||||
this `fails with` "the invoice must not be assigned"
|
this `fails with` "the invoice must not be assigned"
|
||||||
}
|
}
|
||||||
|
|
||||||
props = invoiceProperties.copy(invoiceID = "");
|
props = invoiceProperties.copy(invoiceID = "")
|
||||||
transaction {
|
transaction {
|
||||||
output { initialInvoiceState.copy(props = props) }
|
output { initialInvoiceState.copy(props = props) }
|
||||||
command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() }
|
command(MEGA_CORP_PUBKEY) { Invoice.Commands.Issue() }
|
||||||
@ -98,7 +98,7 @@ class InvoiceTests {
|
|||||||
|
|
||||||
val withMessage = "the term must be a positive number"
|
val withMessage = "the term must be a positive number"
|
||||||
val r = try {
|
val r = try {
|
||||||
props = invoiceProperties.copy(term = 0);
|
props = invoiceProperties.copy(term = 0)
|
||||||
false
|
false
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
val m = e.message
|
val m = e.message
|
||||||
@ -179,7 +179,7 @@ class InvoiceTests {
|
|||||||
this `fails with` "the transaction must be signed by the owner"
|
this `fails with` "the transaction must be signed by the owner"
|
||||||
}
|
}
|
||||||
|
|
||||||
var props = invoiceProperties.copy(seller = invoiceProperties.buyer);
|
var props = invoiceProperties.copy(seller = invoiceProperties.buyer)
|
||||||
transaction {
|
transaction {
|
||||||
input { initialInvoiceState }
|
input { initialInvoiceState }
|
||||||
output { initialInvoiceState.copy(props = props) }
|
output { initialInvoiceState.copy(props = props) }
|
||||||
|
@ -154,19 +154,19 @@ class LOCTests {
|
|||||||
output { LOCstate.copy(issued = false) }
|
output { LOCstate.copy(issued = false) }
|
||||||
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the LOC must be Issued");
|
this `fails with` "the LOC must be Issued"
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
output { LOCstate.copy(beneficiaryPaid = true, issued = true) }
|
output { LOCstate.copy(beneficiaryPaid = true, issued = true) }
|
||||||
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("Demand Presentation must not be preformed successfully");
|
this `fails with` "Demand Presentation must not be preformed successfully"
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
output { LOCstate.copy(terminated = true, issued = true) }
|
output { LOCstate.copy(terminated = true, issued = true) }
|
||||||
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("LOC must not be terminated");
|
this `fails with` "LOC must not be terminated"
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
output { LOCstate.copy(issued = true) }
|
output { LOCstate.copy(issued = true) }
|
||||||
@ -179,7 +179,7 @@ class LOCTests {
|
|||||||
// output { LOCstate.copy() }
|
// output { LOCstate.copy() }
|
||||||
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
command(MEGA_CORP_PUBKEY) { LOC.Commands.Issuance() }
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the period of presentation must be a positive number");
|
this `fails with` "the period of presentation must be a positive number"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -199,7 +199,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.verifies();
|
this.verifies()
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -215,7 +215,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the issuing bank");
|
this `fails with` "the transaction is signed by the issuing bank"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -231,7 +231,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the Beneficiary");
|
this `fails with` "the transaction is signed by the Beneficiary"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -247,7 +247,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the LOC properties do not remain the same");
|
this `fails with` "the LOC properties do not remain the same"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -263,7 +263,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the shipment is late");
|
this `fails with` "the shipment is late"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -279,7 +279,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the cash state has not been transferred");
|
this `fails with` "the cash state has not been transferred"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -295,7 +295,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
command(ALICE_PUBKEY) { BillOfLadingAgreement.Commands.TransferAndEndorseBL() }
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the bill of lading has not been transferred");
|
this `fails with` "the bill of lading has not been transferred"
|
||||||
}
|
}
|
||||||
|
|
||||||
/* transaction {
|
/* transaction {
|
||||||
@ -327,7 +327,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the beneficiary has not been paid, status not changed");
|
this `fails with` "the beneficiary has not been paid, status not changed"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -343,7 +343,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the LOC must be Issued");
|
this `fails with` "the LOC must be Issued"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -359,7 +359,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
command(ALICE_PUBKEY) { Invoice.Commands.Extinguish()}
|
||||||
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
command(MEGA_CORP_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("LOC must not be terminated");
|
this `fails with` "LOC must not be terminated"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -375,7 +375,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.verifies();
|
this.verifies()
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
input { LOCstate.copy(issued = true, beneficiaryPaid = true) }
|
input { LOCstate.copy(issued = true, beneficiaryPaid = true) }
|
||||||
@ -385,7 +385,7 @@ class LOCTests {
|
|||||||
command(ALICE_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(ALICE_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the transaction is signed by the issuing bank");
|
this `fails with` "the transaction is signed by the issuing bank"
|
||||||
}
|
}
|
||||||
|
|
||||||
/*transaction {
|
/*transaction {
|
||||||
@ -407,7 +407,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the cash state has not been transferred");
|
this `fails with` "the cash state has not been transferred"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -418,7 +418,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("Empty collection can't be reduced");
|
this `fails with` "Empty collection can't be reduced"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -429,7 +429,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the beneficiary has not been paid, status not changed");
|
this `fails with` "the beneficiary has not been paid, status not changed"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -440,7 +440,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the LOC must be Issued");
|
this `fails with` "the LOC must be Issued"
|
||||||
}
|
}
|
||||||
transaction {
|
transaction {
|
||||||
input { LOCstate.copy(issued = true, beneficiaryPaid = true) }
|
input { LOCstate.copy(issued = true, beneficiaryPaid = true) }
|
||||||
@ -450,7 +450,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("LOC should be terminated");
|
this `fails with` "LOC should be terminated"
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction {
|
transaction {
|
||||||
@ -461,7 +461,7 @@ class LOCTests {
|
|||||||
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
command(MEGA_CORP_PUBKEY, CHARLIE_PUBKEY) { LOC.Commands.Termination() }
|
||||||
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
command(CHARLIE_PUBKEY) {Cash.Commands.Move()}
|
||||||
timestamp(Instant.now())
|
timestamp(Instant.now())
|
||||||
this.`fails with`("the LOC properties do not remain the same");
|
this `fails with` "the LOC properties do not remain the same"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,15 +8,6 @@ interface StatesQuery {
|
|||||||
fun select(criteria: Criteria): Selection {
|
fun select(criteria: Criteria): Selection {
|
||||||
return Selection(criteria)
|
return Selection(criteria)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun selectAllDeals(): Selection {
|
|
||||||
return select(Criteria.AllDeals)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun selectDeal(ref: String): Selection {
|
|
||||||
return select(Criteria.Deal(ref))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO make constructors private
|
// TODO make constructors private
|
||||||
|
@ -6,13 +6,13 @@ import com.google.common.util.concurrent.SettableFuture
|
|||||||
import com.r3corda.core.RunOnCallerThread
|
import com.r3corda.core.RunOnCallerThread
|
||||||
import com.r3corda.core.contracts.SignedTransaction
|
import com.r3corda.core.contracts.SignedTransaction
|
||||||
import com.r3corda.core.crypto.Party
|
import com.r3corda.core.crypto.Party
|
||||||
import com.r3corda.core.messaging.MessagingService
|
|
||||||
import com.r3corda.core.messaging.runOnNextMessage
|
import com.r3corda.core.messaging.runOnNextMessage
|
||||||
import com.r3corda.core.node.CityDatabase
|
import com.r3corda.core.node.CityDatabase
|
||||||
import com.r3corda.core.node.CordaPluginRegistry
|
import com.r3corda.core.node.CordaPluginRegistry
|
||||||
import com.r3corda.core.node.NodeInfo
|
import com.r3corda.core.node.NodeInfo
|
||||||
import com.r3corda.core.node.PhysicalLocation
|
import com.r3corda.core.node.PhysicalLocation
|
||||||
import com.r3corda.core.node.services.*
|
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.ProtocolLogic
|
||||||
import com.r3corda.core.protocols.ProtocolLogicRefFactory
|
import com.r3corda.core.protocols.ProtocolLogicRefFactory
|
||||||
import com.r3corda.core.random63BitValue
|
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.events.ScheduledActivityObserver
|
||||||
import com.r3corda.node.services.identity.InMemoryIdentityService
|
import com.r3corda.node.services.identity.InMemoryIdentityService
|
||||||
import com.r3corda.node.services.keys.E2ETestKeyManagementService
|
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.InMemoryNetworkMapCache
|
||||||
import com.r3corda.node.services.network.InMemoryNetworkMapService
|
import com.r3corda.node.services.network.InMemoryNetworkMapService
|
||||||
import com.r3corda.node.services.network.NetworkMapService
|
import com.r3corda.node.services.network.NetworkMapService
|
||||||
import com.r3corda.node.services.network.NetworkMapService.Companion.REGISTER_PROTOCOL_TOPIC
|
import com.r3corda.node.services.network.NetworkMapService.Companion.REGISTER_PROTOCOL_TOPIC
|
||||||
import com.r3corda.node.services.network.NodeRegistration
|
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.statemachine.StateMachineManager
|
||||||
import com.r3corda.node.services.transactions.InMemoryUniquenessProvider
|
import com.r3corda.node.services.transactions.InMemoryUniquenessProvider
|
||||||
import com.r3corda.node.services.transactions.NotaryService
|
import com.r3corda.node.services.transactions.NotaryService
|
||||||
@ -158,7 +159,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
|
|||||||
storage = storageServices.first
|
storage = storageServices.first
|
||||||
checkpointStorage = storageServices.second
|
checkpointStorage = storageServices.second
|
||||||
net = makeMessagingService()
|
net = makeMessagingService()
|
||||||
netMapCache = InMemoryNetworkMapCache(net)
|
netMapCache = InMemoryNetworkMapCache()
|
||||||
wallet = NodeWalletService(services)
|
wallet = NodeWalletService(services)
|
||||||
|
|
||||||
identity = makeIdentityService()
|
identity = makeIdentityService()
|
||||||
@ -201,8 +202,8 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
|
|||||||
private fun initialiseProtocolLogicFactory(): ProtocolLogicRefFactory {
|
private fun initialiseProtocolLogicFactory(): ProtocolLogicRefFactory {
|
||||||
val protocolWhitelist = HashMap<String, Set<String>>()
|
val protocolWhitelist = HashMap<String, Set<String>>()
|
||||||
for (plugin in pluginRegistries) {
|
for (plugin in pluginRegistries) {
|
||||||
for (protocol in plugin.requiredProtocols) {
|
for ((className, classWhitelist) in plugin.requiredProtocols) {
|
||||||
protocolWhitelist.merge(protocol.key, protocol.value, { x, y -> x + y })
|
protocolWhitelist.merge(className, classWhitelist, { x, y -> x + y })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,7 +4,6 @@ import com.google.common.jimfs.Configuration
|
|||||||
import com.google.common.jimfs.Jimfs
|
import com.google.common.jimfs.Jimfs
|
||||||
import com.google.common.util.concurrent.Futures
|
import com.google.common.util.concurrent.Futures
|
||||||
import com.r3corda.core.crypto.Party
|
import com.r3corda.core.crypto.Party
|
||||||
import com.r3corda.core.messaging.MessagingService
|
|
||||||
import com.r3corda.core.messaging.SingleMessageRecipient
|
import com.r3corda.core.messaging.SingleMessageRecipient
|
||||||
import com.r3corda.core.node.NodeInfo
|
import com.r3corda.core.node.NodeInfo
|
||||||
import com.r3corda.core.node.PhysicalLocation
|
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.
|
// 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. */
|
/** 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 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)
|
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 addressToNode(address: SingleMessageRecipient): MockNode = nodes.single { it.net.myAddress == address }
|
||||||
|
|
||||||
fun startNodes() {
|
fun startNodes() {
|
||||||
|
@ -31,8 +31,8 @@ import java.util.*
|
|||||||
* in a few cities around the world.
|
* in a few cities around the world.
|
||||||
*/
|
*/
|
||||||
abstract class Simulation(val networkSendManuallyPumped: Boolean,
|
abstract class Simulation(val networkSendManuallyPumped: Boolean,
|
||||||
val runAsync: Boolean,
|
runAsync: Boolean,
|
||||||
val latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
|
latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
|
||||||
init {
|
init {
|
||||||
if (!runAsync && latencyInjector != null)
|
if (!runAsync && latencyInjector != null)
|
||||||
throw IllegalArgumentException("The latency injector is only useful when using manual pumping.")
|
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 }
|
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 _allProtocolSteps = PublishSubject.create<Pair<SimulatedNode, ProgressTracker.Change>>()
|
||||||
private val _doneSteps = PublishSubject.create<Collection<SimulatedNode>>()
|
private val _doneSteps = PublishSubject.create<Collection<SimulatedNode>>()
|
||||||
val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
|
@Suppress("unused") val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
|
||||||
val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
|
@Suppress("unused") val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
|
||||||
|
|
||||||
private var pumpCursor = 0
|
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<*> =
|
val networkInitialisationFinished: ListenableFuture<*> =
|
||||||
Futures.allAsList(network.nodes.map { it.networkMapRegistrationFuture })
|
Futures.allAsList(network.nodes.map { it.networkMapRegistrationFuture })
|
||||||
|
|
||||||
|
@ -2,7 +2,6 @@ package com.r3corda.node.services.api
|
|||||||
|
|
||||||
import com.r3corda.core.messaging.Message
|
import com.r3corda.core.messaging.Message
|
||||||
import com.r3corda.core.messaging.MessagingService
|
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.DEFAULT_SESSION_ID
|
||||||
import com.r3corda.core.node.services.NetworkMapCache
|
import com.r3corda.core.node.services.NetworkMapCache
|
||||||
import com.r3corda.core.serialization.SingletonSerializeAsToken
|
import com.r3corda.core.serialization.SingletonSerializeAsToken
|
||||||
|
@ -3,7 +3,6 @@ package com.r3corda.node.services.api
|
|||||||
import com.r3corda.core.serialization.SerializedBytes
|
import com.r3corda.core.serialization.SerializedBytes
|
||||||
import com.r3corda.node.services.statemachine.FiberRequest
|
import com.r3corda.node.services.statemachine.FiberRequest
|
||||||
import com.r3corda.node.services.statemachine.ProtocolStateMachineImpl
|
import com.r3corda.node.services.statemachine.ProtocolStateMachineImpl
|
||||||
import com.r3corda.node.services.statemachine.StateMachineManager
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thread-safe storage of fiber checkpoints.
|
* Thread-safe storage of fiber checkpoints.
|
||||||
|
@ -3,7 +3,6 @@ package com.r3corda.node.services.clientapi
|
|||||||
import com.r3corda.core.node.CordaPluginRegistry
|
import com.r3corda.core.node.CordaPluginRegistry
|
||||||
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
|
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
|
||||||
import com.r3corda.core.serialization.deserialize
|
import com.r3corda.core.serialization.deserialize
|
||||||
import com.r3corda.node.internal.AbstractNode
|
|
||||||
import com.r3corda.node.services.api.ServiceHubInternal
|
import com.r3corda.node.services.api.ServiceHubInternal
|
||||||
import com.r3corda.protocols.TwoPartyDealProtocol
|
import com.r3corda.protocols.TwoPartyDealProtocol
|
||||||
|
|
||||||
|
@ -197,7 +197,7 @@ object NodeInterestRates {
|
|||||||
class UnknownFix(val fix: FixOf) : RetryableException("Unknown fix: $fix")
|
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] */
|
/** 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)
|
private val container = buildContainer(fixes)
|
||||||
val size = fixes.size
|
val size = fixes.size
|
||||||
|
|
||||||
@ -227,7 +227,7 @@ object NodeInterestRates {
|
|||||||
* Interpolates missing values using the provided interpolation mechanism.
|
* Interpolates missing values using the provided interpolation mechanism.
|
||||||
*/
|
*/
|
||||||
class InterpolatingRateMap(val date: LocalDate,
|
class InterpolatingRateMap(val date: LocalDate,
|
||||||
val inputRates: Map<Tenor, BigDecimal>,
|
inputRates: Map<Tenor, BigDecimal>,
|
||||||
val calendar: BusinessCalendar,
|
val calendar: BusinessCalendar,
|
||||||
val factory: InterpolatorFactory) {
|
val factory: InterpolatorFactory) {
|
||||||
|
|
||||||
@ -274,7 +274,7 @@ object NodeInterestRates {
|
|||||||
/** Parses lines containing fixes */
|
/** Parses lines containing fixes */
|
||||||
fun parseFile(s: String): FixContainer {
|
fun parseFile(s: String): FixContainer {
|
||||||
val fixes = s.lines().
|
val fixes = s.lines().
|
||||||
map { it.trim() }.
|
map(String::trim).
|
||||||
// Filter out comment and empty lines.
|
// Filter out comment and empty lines.
|
||||||
filterNot { it.startsWith("#") || it.isBlank() }.
|
filterNot { it.startsWith("#") || it.isBlank() }.
|
||||||
map { parseFix(it) }
|
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] */
|
/** Parses a string of the form "LIBOR 16-March-2016 1M = 0.678" into a [Fix] */
|
||||||
fun parseFix(s: String): 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 of = parseFixOf(key)
|
||||||
val rate = BigDecimal(value)
|
val rate = BigDecimal(value)
|
||||||
return Fix(of, rate)
|
return Fix(of, rate)
|
||||||
|
@ -50,6 +50,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
|
|||||||
// The corresponding sentMessages stream reflects when a message was pumpSend'd
|
// The corresponding sentMessages stream reflects when a message was pumpSend'd
|
||||||
private val messageSendQueue = LinkedBlockingQueue<MessageTransfer>()
|
private val messageSendQueue = LinkedBlockingQueue<MessageTransfer>()
|
||||||
private val _sentMessages = PublishSubject.create<MessageTransfer>()
|
private val _sentMessages = PublishSubject.create<MessageTransfer>()
|
||||||
|
@Suppress("unused") // Used by the visualiser tool.
|
||||||
/** A stream of (sender, message, recipients) triples */
|
/** A stream of (sender, message, recipients) triples */
|
||||||
val sentMessages: Observable<MessageTransfer>
|
val sentMessages: Observable<MessageTransfer>
|
||||||
get() = _sentMessages
|
get() = _sentMessages
|
||||||
@ -61,6 +62,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
|
|||||||
// The corresponding stream reflects when a message was pumpReceive'd
|
// The corresponding stream reflects when a message was pumpReceive'd
|
||||||
private val messageReceiveQueues = HashMap<Handle, LinkedBlockingQueue<MessageTransfer>>()
|
private val messageReceiveQueues = HashMap<Handle, LinkedBlockingQueue<MessageTransfer>>()
|
||||||
private val _receivedMessages = PublishSubject.create<MessageTransfer>()
|
private val _receivedMessages = PublishSubject.create<MessageTransfer>()
|
||||||
|
|
||||||
|
@Suppress("unused") // Used by the visualiser tool.
|
||||||
/** A stream of (sender, message, recipients) triples */
|
/** A stream of (sender, message, recipients) triples */
|
||||||
val receivedMessages: Observable<MessageTransfer>
|
val receivedMessages: Observable<MessageTransfer>
|
||||||
get() = _receivedMessages
|
get() = _receivedMessages
|
||||||
@ -202,18 +205,18 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
|
|||||||
val callback: (Message, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration
|
val callback: (Message, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
protected var running = true
|
private var running = true
|
||||||
|
|
||||||
protected inner class InnerState {
|
private inner class InnerState {
|
||||||
val handlers: MutableList<Handler> = ArrayList()
|
val handlers: MutableList<Handler> = ArrayList()
|
||||||
val pendingRedelivery = LinkedList<MessageTransfer>()
|
val pendingRedelivery = LinkedList<MessageTransfer>()
|
||||||
}
|
}
|
||||||
|
|
||||||
protected val state = ThreadBox(InnerState())
|
private val state = ThreadBox(InnerState())
|
||||||
|
|
||||||
override val myAddress: SingleMessageRecipient = handle
|
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") {
|
thread(isDaemon = true, name = "In-memory message dispatcher") {
|
||||||
while (!Thread.currentThread().isInterrupted) {
|
while (!Thread.currentThread().isInterrupted) {
|
||||||
try {
|
try {
|
||||||
@ -235,8 +238,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
|
|||||||
pendingRedelivery.clear()
|
pendingRedelivery.clear()
|
||||||
Pair(handler, items)
|
Pair(handler, items)
|
||||||
}
|
}
|
||||||
for (it in items) {
|
for ((sender, message) in items) {
|
||||||
send(it.message, handle)
|
send(message, handle)
|
||||||
}
|
}
|
||||||
return handler
|
return handler
|
||||||
}
|
}
|
||||||
@ -329,10 +332,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
|
|||||||
|
|
||||||
private fun pumpReceiveInternal(block: Boolean): MessageTransfer? {
|
private fun pumpReceiveInternal(block: Boolean): MessageTransfer? {
|
||||||
val q = getQueueForHandle(handle)
|
val q = getQueueForHandle(handle)
|
||||||
val next = getNextQueue(q, block)
|
val next = getNextQueue(q, block) ?: return null
|
||||||
if (next == null) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
val (transfer, deliverTo) = next
|
val (transfer, deliverTo) = next
|
||||||
|
|
||||||
for (handler in deliverTo) {
|
for (handler in deliverTo) {
|
||||||
|
@ -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.DEFAULT_SESSION_ID
|
||||||
import com.r3corda.core.node.services.NetworkCacheError
|
import com.r3corda.core.node.services.NetworkCacheError
|
||||||
import com.r3corda.core.node.services.NetworkMapCache
|
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.MapChange
|
||||||
|
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
|
||||||
import com.r3corda.core.node.services.ServiceType
|
import com.r3corda.core.node.services.ServiceType
|
||||||
import com.r3corda.core.random63BitValue
|
import com.r3corda.core.random63BitValue
|
||||||
import com.r3corda.core.serialization.SingletonSerializeAsToken
|
import com.r3corda.core.serialization.SingletonSerializeAsToken
|
||||||
import com.r3corda.core.serialization.deserialize
|
import com.r3corda.core.serialization.deserialize
|
||||||
import com.r3corda.core.serialization.serialize
|
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.api.RegulatorService
|
||||||
import com.r3corda.node.services.clientapi.NodeInterestRates
|
import com.r3corda.node.services.clientapi.NodeInterestRates
|
||||||
import com.r3corda.node.services.transactions.NotaryService
|
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.
|
* Extremely simple in-memory cache of the network map.
|
||||||
*/
|
*/
|
||||||
@ThreadSafe
|
@ThreadSafe
|
||||||
open class InMemoryNetworkMapCache(val netInternal: MessagingServiceInternal?) : SingletonSerializeAsToken(), NetworkMapCache {
|
open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCache {
|
||||||
override val networkMapNodes: List<NodeInfo>
|
override val networkMapNodes: List<NodeInfo>
|
||||||
get() = get(NetworkMapService.Type)
|
get() = get(NetworkMapService.Type)
|
||||||
override val regulators: List<NodeInfo>
|
override val regulators: List<NodeInfo>
|
||||||
|
@ -12,14 +12,14 @@ import rx.subjects.PublishSubject
|
|||||||
/**
|
/**
|
||||||
* Network map cache with no backing map service.
|
* 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>()
|
override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>()
|
||||||
|
|
||||||
data class MockAddress(val id: String): SingleMessageRecipient
|
data class MockAddress(val id: String): SingleMessageRecipient
|
||||||
|
|
||||||
init {
|
init {
|
||||||
var mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
|
val mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
|
||||||
var mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
|
val mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
|
||||||
registeredNodes[mockNodeA.identity] = mockNodeA
|
registeredNodes[mockNodeA.identity] = mockNodeA
|
||||||
registeredNodes[mockNodeB.identity] = mockNodeB
|
registeredNodes[mockNodeB.identity] = mockNodeB
|
||||||
}
|
}
|
||||||
|
@ -280,7 +280,7 @@ class NodeRegistration(val node: NodeInfo, val serial: Long, val type: AddOrRemo
|
|||||||
return WireNodeRegistration(regSerialized, regSig)
|
return WireNodeRegistration(regSerialized, regSig)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun toString() : String = "$node #${serial} (${type})"
|
override fun toString() : String = "$node #$serial ($type)"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -62,7 +62,7 @@ object DataVending {
|
|||||||
if (data.accepted) {
|
if (data.accepted) {
|
||||||
future.set(Unit)
|
future.set(Unit)
|
||||||
} else {
|
} 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)
|
val msg = NotifyTxRequestMessage(transaction, myIdentity, sessionID)
|
||||||
|
@ -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.
|
* Stores attachments in the specified local directory, which must exist. Doesn't allow new attachments to be uploaded.
|
||||||
*/
|
*/
|
||||||
@ThreadSafe
|
@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>()
|
private val log = loggerFor<NodeAttachmentService>()
|
||||||
|
|
||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
@ -122,7 +122,7 @@ class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) :
|
|||||||
Files.deleteIfExists(tmp)
|
Files.deleteIfExists(tmp)
|
||||||
}
|
}
|
||||||
if (automaticallyExtractAttachments) {
|
if (automaticallyExtractAttachments) {
|
||||||
val extractTo = storePath.resolve("${id}.jar")
|
val extractTo = storePath.resolve("$id.jar")
|
||||||
try {
|
try {
|
||||||
Files.createDirectory(extractTo)
|
Files.createDirectory(extractTo)
|
||||||
extractZipFile(finalPath, extractTo)
|
extractZipFile(finalPath, extractTo)
|
||||||
|
@ -40,7 +40,7 @@ class PerFileCheckpointStorage(val storeDir: Path) : CheckpointStorage {
|
|||||||
|
|
||||||
override fun addCheckpoint(checkpoint: Checkpoint) {
|
override fun addCheckpoint(checkpoint: Checkpoint) {
|
||||||
val serialisedCheckpoint = checkpoint.serialize()
|
val serialisedCheckpoint = checkpoint.serialize()
|
||||||
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}${fileExtension}"
|
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}$fileExtension"
|
||||||
val checkpointFile = storeDir.resolve(fileName)
|
val checkpointFile = storeDir.resolve(fileName)
|
||||||
atomicWrite(checkpointFile, serialisedCheckpoint)
|
atomicWrite(checkpointFile, serialisedCheckpoint)
|
||||||
logger.trace { "Stored $checkpoint to $checkpointFile" }
|
logger.trace { "Stored $checkpoint to $checkpointFile" }
|
||||||
|
@ -59,15 +59,15 @@ sealed class FiberRequest(val topic: String,
|
|||||||
) : FiberRequest(topic, destination, sessionIDForSend, sessionIDForReceive, obj) {
|
) : FiberRequest(topic, destination, sessionIDForSend, sessionIDForReceive, obj) {
|
||||||
private val responseTypeName: String = type.name
|
private val responseTypeName: String = type.name
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean
|
override fun equals(other: Any?): Boolean {
|
||||||
= if (other is ExpectingResponse<*>) {
|
return if (other is ExpectingResponse<*>) {
|
||||||
super.equals(other)
|
super.equals(other) && responseTypeName == other.responseTypeName
|
||||||
&& responseTypeName == other.responseTypeName
|
} else
|
||||||
} else
|
false
|
||||||
false
|
}
|
||||||
|
|
||||||
override fun toString(): String {
|
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
|
// We have to do an unchecked cast, but unless the serialized form is damaged, this was
|
||||||
|
@ -30,13 +30,13 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) {
|
|||||||
//
|
//
|
||||||
// Note: exported as pennies.
|
// Note: exported as pennies.
|
||||||
val m = serviceHubInternal.monitoringService.metrics
|
val m = serviceHubInternal.monitoringService.metrics
|
||||||
for (balance in wallet.cashBalances) {
|
for ((key, value) in wallet.cashBalances) {
|
||||||
val metric = balanceMetrics.getOrPut(balance.key) {
|
val metric = balanceMetrics.getOrPut(key) {
|
||||||
val newMetric = BalanceMetric()
|
val newMetric = BalanceMetric()
|
||||||
m.register("WalletBalances.${balance.key}Pennies", newMetric)
|
m.register("WalletBalances.${key}Pennies", newMetric)
|
||||||
newMetric
|
newMetric
|
||||||
}
|
}
|
||||||
metric.pennies = balance.value.quantity
|
metric.pennies = value.quantity
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -4,7 +4,6 @@ import com.r3corda.core.ThreadBox
|
|||||||
import com.r3corda.core.protocols.ProtocolLogic
|
import com.r3corda.core.protocols.ProtocolLogic
|
||||||
import com.r3corda.core.utilities.ProgressTracker
|
import com.r3corda.core.utilities.ProgressTracker
|
||||||
import com.r3corda.node.services.statemachine.StateMachineManager
|
import com.r3corda.node.services.statemachine.StateMachineManager
|
||||||
import com.r3corda.protocols.TwoPartyDealProtocol
|
|
||||||
import java.util.*
|
import java.util.*
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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
|
* 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.
|
* 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
|
private var mutated: SettableFuture<Boolean>? = null
|
||||||
|
|
||||||
@Suppress("UNUSED_VALUE") // This is here due to the compiler thinking ourMutated is not used
|
@Suppress("UNUSED_VALUE") // This is here due to the compiler thinking ourMutated is not used
|
||||||
|
@ -13,8 +13,6 @@ import com.r3corda.core.contracts.BusinessCalendar
|
|||||||
import com.r3corda.core.crypto.*
|
import com.r3corda.core.crypto.*
|
||||||
import com.r3corda.core.node.services.IdentityService
|
import com.r3corda.core.node.services.IdentityService
|
||||||
import net.i2p.crypto.eddsa.EdDSAPublicKey
|
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.math.BigDecimal
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
|
@ -19,6 +19,7 @@ import com.r3corda.node.services.statemachine.StateMachineManager
|
|||||||
import com.r3corda.node.services.wallet.NodeWalletService
|
import com.r3corda.node.services.wallet.NodeWalletService
|
||||||
import java.time.Clock
|
import java.time.Clock
|
||||||
|
|
||||||
|
@Suppress("LeakingThis")
|
||||||
open class MockServiceHubInternal(
|
open class MockServiceHubInternal(
|
||||||
customWallet: WalletService? = null,
|
customWallet: WalletService? = null,
|
||||||
val keyManagement: KeyManagementService? = null,
|
val keyManagement: KeyManagementService? = null,
|
||||||
|
@ -22,7 +22,6 @@ import com.r3corda.protocols.RatesFixProtocol
|
|||||||
import org.junit.Assert
|
import org.junit.Assert
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.time.Clock
|
import java.time.Clock
|
||||||
import java.time.Duration
|
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
import kotlin.test.assertFailsWith
|
import kotlin.test.assertFailsWith
|
||||||
|
|
||||||
@ -109,7 +108,7 @@ class NodeInterestRatesTest {
|
|||||||
|
|
||||||
val tx = TransactionType.General.Builder()
|
val tx = TransactionType.General.Builder()
|
||||||
val fixOf = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M")
|
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")
|
BriefLogFormatter.initVerbose("rates")
|
||||||
net.runNetwork()
|
net.runNetwork()
|
||||||
val future = n1.smm.add("rates", protocol)
|
val future = n1.smm.add("rates", protocol)
|
||||||
|
@ -196,7 +196,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
|
|||||||
@Test
|
@Test
|
||||||
fun `test activity due in the future and schedule another for same time then unschedule original`() {
|
fun `test activity due in the future and schedule another for same time then unschedule original`() {
|
||||||
val time = stoppedClock.instant() + 1.days
|
val time = stoppedClock.instant() + 1.days
|
||||||
var scheduledRef1 = scheduleTX(time)
|
val scheduledRef1 = scheduleTX(time)
|
||||||
|
|
||||||
val backgroundExecutor = Executors.newSingleThreadExecutor()
|
val backgroundExecutor = Executors.newSingleThreadExecutor()
|
||||||
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
|
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
|
||||||
@ -214,7 +214,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `test activity due in the future then unschedule`() {
|
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()
|
val backgroundExecutor = Executors.newSingleThreadExecutor()
|
||||||
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
|
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
|
||||||
|
@ -7,7 +7,6 @@ import com.r3corda.core.random63BitValue
|
|||||||
import com.r3corda.core.serialization.SerializedBytes
|
import com.r3corda.core.serialization.SerializedBytes
|
||||||
import com.r3corda.node.services.api.Checkpoint
|
import com.r3corda.node.services.api.Checkpoint
|
||||||
import com.r3corda.node.services.statemachine.FiberRequest
|
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.assertThat
|
||||||
import org.assertj.core.api.Assertions.assertThatExceptionOfType
|
import org.assertj.core.api.Assertions.assertThatExceptionOfType
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
|
@ -2,7 +2,6 @@ package com.r3corda.node.services.statemachine
|
|||||||
|
|
||||||
import co.paralleluniverse.fibers.Fiber
|
import co.paralleluniverse.fibers.Fiber
|
||||||
import co.paralleluniverse.fibers.Suspendable
|
import co.paralleluniverse.fibers.Suspendable
|
||||||
import com.r3corda.core.messaging.MessagingService
|
|
||||||
import com.r3corda.core.protocols.ProtocolLogic
|
import com.r3corda.core.protocols.ProtocolLogic
|
||||||
import com.r3corda.node.services.MockServiceHubInternal
|
import com.r3corda.node.services.MockServiceHubInternal
|
||||||
import com.r3corda.node.services.api.Checkpoint
|
import com.r3corda.node.services.api.Checkpoint
|
||||||
|
@ -11,6 +11,7 @@ import org.graphstream.graph.Node
|
|||||||
import org.graphstream.graph.implementations.SingleGraph
|
import org.graphstream.graph.implementations.SingleGraph
|
||||||
import kotlin.reflect.memberProperties
|
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>) {
|
class GraphVisualiser(val dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>) {
|
||||||
companion object {
|
companion object {
|
||||||
val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText()
|
val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText()
|
||||||
|
@ -37,7 +37,7 @@ public class StateViewer {
|
|||||||
frame.setVisible(true);
|
frame.setVisible(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public StateViewer(List<Pair<String, Object>> props) {
|
private StateViewer(List<Pair<String, Object>> props) {
|
||||||
propsTable.setModel(new AbstractTableModel() {
|
propsTable.setModel(new AbstractTableModel() {
|
||||||
@Override
|
@Override
|
||||||
public int getRowCount() {
|
public int getRowCount() {
|
||||||
|
@ -90,7 +90,7 @@ fun main(args: Array<String>) {
|
|||||||
// Make a garbage transaction that includes a rate fix.
|
// Make a garbage transaction that includes a rate fix.
|
||||||
val tx = TransactionType.General.Builder()
|
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))
|
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.smm.add("demo.ratefix", protocol).get()
|
||||||
node.stop()
|
node.stop()
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
"use strict"
|
"use strict";
|
||||||
|
|
||||||
define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
|
define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
|
||||||
let calculationModel = {
|
let calculationModel = {
|
||||||
@ -25,7 +25,7 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
|
|||||||
|
|
||||||
let Deal = function(dealViewModel) {
|
let Deal = function(dealViewModel) {
|
||||||
let now = new Date();
|
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 = () => {
|
this.toJson = () => {
|
||||||
let fixedLeg = {};
|
let fixedLeg = {};
|
||||||
@ -70,10 +70,10 @@ define(['viewmodel/FixedRate'], (fixedRateViewModel) => {
|
|||||||
floatingLeg: floatingLeg,
|
floatingLeg: floatingLeg,
|
||||||
calculation: calculationModel,
|
calculation: calculationModel,
|
||||||
common: common
|
common: common
|
||||||
}
|
};
|
||||||
|
|
||||||
return json;
|
return json;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
return Deal;
|
return Deal;
|
||||||
})
|
});
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
"use strict"
|
"use strict";
|
||||||
|
|
||||||
function formatDateForNode(date) {
|
function formatDateForNode(date) {
|
||||||
// Produces yyyy-dd-mm. JS is missing proper date formatting libs
|
// Produces yyyy-dd-mm. JS is missing proper date formatting libs
|
||||||
|
@ -6,7 +6,7 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no
|
|||||||
|
|
||||||
let handleHttpFail = (resp) => {
|
let handleHttpFail = (resp) => {
|
||||||
$scope.httpError = resp.data
|
$scope.httpError = resp.data
|
||||||
}
|
};
|
||||||
|
|
||||||
$scope.infoMsg = "";
|
$scope.infoMsg = "";
|
||||||
$scope.errorText = "";
|
$scope.errorText = "";
|
||||||
@ -20,4 +20,4 @@ define(['angular', 'utils/semantic', 'services/NodeApi'], (angular, semantic, no
|
|||||||
nodeService.getDate().then((date) => $scope.date = date);
|
nodeService.getDate().then((date) => $scope.date = date);
|
||||||
nodeService.getDeals().then((deals) => $scope.deals = deals);
|
nodeService.getDeals().then((deals) => $scope.deals = deals);
|
||||||
});
|
});
|
||||||
})
|
});
|
@ -15,7 +15,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
|
|||||||
curLoading[type] = false;
|
curLoading[type] = false;
|
||||||
throw arg;
|
throw arg;
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
let changeDateOnNode = (newDate) => {
|
let changeDateOnNode = (newDate) => {
|
||||||
const dateStr = formatDateForNode(newDate);
|
const dateStr = formatDateForNode(newDate);
|
||||||
@ -24,7 +24,7 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
|
|||||||
date = newDate;
|
date = newDate;
|
||||||
return this.getDateModel(date);
|
return this.getDateModel(date);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
this.getDate = () => {
|
this.getDate = () => {
|
||||||
return load('date', $http.get('/api/irs/demodate')).then((resp) => {
|
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
|
date = new Date(parts[0], parts[1] - 1, parts[2]); // JS uses 0 based months
|
||||||
return this.getDateModel(date);
|
return this.getDateModel(date);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
this.updateDate = (type) => {
|
this.updateDate = (type) => {
|
||||||
let newDate = date;
|
let newDate = date;
|
||||||
@ -74,17 +74,17 @@ define(['angular', 'lodash', 'viewmodel/Deal'], (angular, _, dealViewModel) => {
|
|||||||
"month": date.getMonth() + 1, // JS uses 0 based months
|
"month": date.getMonth() + 1, // JS uses 0 based months
|
||||||
"day": date.getDate()
|
"day": date.getDate()
|
||||||
};
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
this.isLoading = () => {
|
this.isLoading = () => {
|
||||||
return _.reduce(Object.keys(curLoading), (last, key) => {
|
return _.reduce(Object.keys(curLoading), (last, key) => {
|
||||||
return (last || curLoading[key]);
|
return (last || curLoading[key]);
|
||||||
}, false);
|
}, false);
|
||||||
}
|
};
|
||||||
|
|
||||||
this.newDeal = () => {
|
this.newDeal = () => {
|
||||||
return dealViewModel;
|
return dealViewModel;
|
||||||
}
|
};
|
||||||
|
|
||||||
this.createDeal = (deal) => {
|
this.createDeal = (deal) => {
|
||||||
return load('create-deal', $http.post('/api/irs/deals', deal.toJson()))
|
return load('create-deal', $http.post('/api/irs/deals', deal.toJson()))
|
||||||
|
@ -31,4 +31,4 @@ define([], () => {
|
|||||||
"year": "YICMA"
|
"year": "YICMA"
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
})
|
});
|
Loading…
x
Reference in New Issue
Block a user