在Corda中,是否有一种不花费状态的方式来引用交易中的未使用状态?目的是允许合约在verify方法中使用被引用状态中的某些信息。
参考状态将会被添加到 Corda 4 版本中,该版本将在今年晚些时候发布。这解决了上面提到的问题。详情请见:
https://github.com/corda/corda/blob/master/docs/source/design/reference-states/design.md
目前Corda不支持此模式的内置支持,但将在Corda 4中添加(请参见下面Roger的答案)。目前,您有几个选择:
编写状态合约以允许此行为:
您可以向合约添加一个命令,强制执行要求每个输入都有与之匹配的输出的要求。这确保了交易只引用状态,而不是修改它。以下是一个示例:
class MyContract : Contract {
override fun verify(tx: LedgerTransaction) {
val command = tx.commands.requireSingleCommand<MyContract.Commands>()
when (command.value) {
is Commands.Reference -> requireThat {
val inputs = tx.inputsOfType<MyState>()
val outputs = tx.outputsOfType<MyState>()
// Assuming `MyState.equals` has been overridden appropriately.
"There must be a matching output state for each input state" using
(inputs.toSet() == outputs.toSet())
}
}
}
interface Commands : CommandData {
class Reference: Commands
}
}
将状态作为输入状态、输出状态或命令中的字段进行引用:
您可以将参考状态作为输入状态、输出状态或命令的字段包含在交易中。命令可能是最合适的选择:
interface Commands : CommandData {
class Reference(val referenceState: MyState): Commands
}
然后您可以在合约的验证方法中检查此状态的内容。例如:
class MyContract : Contract {
override fun verify(tx: LedgerTransaction) {
val command = tx.commands.requireSingleCommand<MyContract.Commands>()
when (command.value) {
is Commands.Reference -> requireThat {
val commandData = command.value as Commands.Reference
val referenceState = commandData.referenceStateAndRef.state.data
val inputs = tx.inputsOfType<MyState>()
"The input state contents must match the reference data" using
(inputs.all { it.contents == referenceState.contents })
}
}
}
interface Commands : CommandData {
class Reference(val referenceStateAndRef: StateAndRef<MyState>): Commands
}
}
采用这种方法时,您还必须在流程中检查参考状态是否与实际账本上的状态相同(即交易提议者是否添加了一个虚假的状态对象作为参考)。例如:
val referenceCommand = ledgerTransaction.commandsOfType<Reference>().single()
val referenceStateAndRef = referenceCommand.value.referenceStateAndRef
val actualStateAndRefFromVault = serviceHub.toStateAndRef<MyState>(referenceStateRef)
if (referenceStateAndRef != actualStateAndRefFromVault) {
throw FlowException("Referenced state does not match state in the vault.")
}