如何在Corda Demobench的Cordapp中创建自定义AdvertisedServices
Hey there! Let me start by clarifying your understanding first, then walk you through how to create custom AdvertisedServices in a CordApp for Demobench.
First, a quick correction to your understanding
You mentioned corda.issuer.CURRENCY and corda.cash as custom services, but that's not quite right — these are built-in identifiers tied to Corda's core cash module:
corda.cashmaps to Corda's native cash management service, which handles core cash operations like issuance and transferscorda.issuer.CURRENCY(whereCURRENCYis a code like GBP/USD) is a role marker for nodes acting as issuers of a specific currency, not an independent custom service
Now, let's build a custom AdvertisedService step by step
Creating a custom advertised service involves defining your service logic, registering it, and configuring the node to advertise it to the network.
1. Define a unique service identifier
First, pick a unique string to identify your service (this will show up in Demobench's service list). For example:com.yourcompany.custom.asset-oracle
2. Implement your service class
Create a service class that extends Corda's service framework. For a singleton service (most common use case), use SingletonSerializeAsToken and annotate it with @CordaService:
package com.yourcompany.cordapp.services import net.corda.core.node.ServiceHub import net.corda.core.node.services.CordaService import net.corda.core.serialization.SingletonSerializeAsToken @CordaService class CustomAssetOracle(private val serviceHub: ServiceHub) : SingletonSerializeAsToken() { // Add your custom service logic here fun getAssetCurrentValue(assetSymbol: String): Double { // Example logic: return a hardcoded value (replace with real data fetching) return when(assetSymbol) { "GOLD" -> 1925.75 "SILVER" -> 24.10 else -> 0.0 } } }
3. Register the service with your CordApp
To ensure the node automatically loads your service on startup, create a file at src/main/resources/META-INF/services/net.corda.core.node.services.CordaService and add your service's full class path:
com.yourcompany.cordapp.services.CustomAssetOracle
4. Configure the node to advertise the service
You have two ways to set this up for Demobench:
- Manual setup in Demobench: When creating a new node, go to the Advanced tab, find the
advertisedServicesfield, and add your service identifier as a string entry. - Node config file: If you're using a pre-written
node.conf, add the service to theadvertisedServiceslist:advertisedServices: [ "com.yourcompany.custom.asset-oracle" ]
5. Use the service in Demobench
Once you package your CordApp and import it into Demobench, your custom service identifier will appear in the Services dropdown when creating new nodes. Select it, start the node, and your service will be active and discoverable by other nodes on the network.
内容的提问来源于stack exchange,提问作者Paradox

