我如何处理Corda节点中提交到Vault中的新状态的事件?

时间:2018-02-05 15:38:21

标签: corda

我需要知道新状态何时被提交到节点的保险库中以获取当时的时间戳。所以,我想如果我能处理提交状态,那么触发我的timestamp记录类会很好。

顺便提一下,如果您对捕获状态随时间变化的时间戳有任何建议,请告诉我。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用CordaRPCOps.vaultTrackBy方法执行此操作。此方法返回对Vault的可观察更新。您可以订阅此observable,以便在保管库中记录新状态时收到通知。

RPC示例

fun main(args: Array<String>) {
    require(args.size == 1) { "Usage: ExampleClientRPC <node address>" }
    val nodeAddress = NetworkHostAndPort.parse(args[0])
    val client = CordaRPCClient(nodeAddress)

    val rpcOps = client.start("user1", "test").proxy

    val updates = rpcOps.vaultTrackBy<ContractState>().updates

    // Log the 'placed' IOU states and listen for new ones.
    updates.toBlocking().subscribe { update ->
        update.produced.forEach { stateAndRef ->
            val timeStamp = Instant.now()
            // TODO("Use the timestamp as you wish.")
        }
    }
}

流程测试示例

class FlowTests {
    lateinit var network: MockNetwork
    lateinit var a: StartedMockNode
    lateinit var b: StartedMockNode

    @Before
    fun setup() {
        network = MockNetwork(
                listOf("com.example.contract"),
                // We need each node to operate on a separate thread so that we can
                // subscribe to the vault updates on a separate thread later.
                threadPerNode = true)
        a = network.createPartyNode()
        b = network.createPartyNode()
        listOf(a, b).forEach { it.registerInitiatedFlow(ExampleFlow.Acceptor::class.java) }
    }

    @After
    fun tearDown() {
        network.stopNodes()
    }

    @Test
    fun `flowTest`() {
        // Trying to access the node database in a separate thread would result in a
        // `java.lang.IllegalStateException: Was expecting to find CordaPersistence set on current thread` exception
        val updates = a.services.vaultService.trackBy<ContractState>().updates

        Thread {
            updates.toBlocking().subscribe { update ->
                update.produced.forEach { stateAndRef ->
                    val timeStamp = Instant.now()
                    // TODO("Use the timestamp as you wish.")
                }
            }
        }.start()

        repeat(3) {
            val flow = ExampleFlow.Initiator(1, b.info.singleIdentity())
            a.startFlow(flow).getOrThrow()
        }

        // We give the other thread time to observe the updates.
        Thread.sleep(10000)
    }
}