对于Corda,需要熟悉的API的使用才能在处理业务逻辑的时候利用好平台的接口编写正确的代码。

Contracts

contracts都是implement于接口contracts,这个接口只有一个verify方法,输入是一个LedgerTransaction的实例。

使用kotlin语言定义如下

/**
 * Implemented by a program that implements business logic on the shared ledger. All participants run this code for
 * every [net.corda.core.transactions.LedgerTransaction] they see on the network, for every input and output state. All
 * contracts must accept the transaction for it to be accepted: failure of any aborts the entire thing. The time is taken
 * from a trusted time-window attached to the transaction itself i.e. it is NOT necessarily the current time.
 *
 * TODO: Contract serialization is likely to change, so the annotation is likely temporary.
 */
@KeepForDJVM
@CordaSerializable
interface Contract {
    /**
     * Takes an object that represents a state transition, and ensures the inputs/outputs/commands make sense.
     * Must throw an exception if there's a problem that should prevent state transition. Takes a single object
     * rather than an argument so that additional data can be added without breaking binary compatibility with
     * existing contract code.
     */
    @Throws(IllegalArgumentException::class)
    fun verify(tx: LedgerTransaction)
}

verify方法通过以下三步判断交易是否合法:

  • 收集每一个交易的输入和输出states

  • 将交易tx作为输入传入verify函数

  • 只有全部通过才能在数据中进行

verify函数在沙盒执行,在验证交易tx的合法性时只能访问定义在LedgerTransaction里面的属性。

在每一个constract中必须重写verify方法:

@override
public void verify(LeadgerTransaction tx){
    // 1.什么都不写表示全部通过
    // Always accepts!

    // 2.只写下面表示全部拒绝
    throw new IllegalArgumentException('Always rejects!');
}

LedgerTransaction