Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core-16349: corda 5 Kotlin negotiation app #21

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions kotlin-samples/corda5-negotiation/.ci/Jenkinsfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
@Library('[email protected]') _

cordaPipeline(
nexusAppId: 'com.corda.CSDE-kotlin.5.0',
publishRepoPrefix: '',
slimBuild: true,
runUnitTests: false,
dedicatedJobForSnykDelta: false,
slackChannel: '#corda-corda5-dev-ex-build-notifications',
gitHubComments: false
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@Library('[email protected]') _

cordaSnykScanPipeline (
snykTokenId: 'r3-snyk-corda5',
snykAdditionalCommands: "--all-sub-projects -d"
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="DebugCorDapp" type="Remote">
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5005" />
<option name="AUTO_RESTART" value="false" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="5005" />
<option name="LOCAL" value="false" />
</RunnerSettings>
<method v="2" />
</configuration>
</component>
14 changes: 14 additions & 0 deletions kotlin-samples/corda5-negotiation/.snyk
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.25.0
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
SNYK-JAVA-ORGJETBRAINSKOTLIN-2393744:
- '*':
reason: >-
This vulnerability relates to information exposure via creation of
temporary files (via Kotlin functions) with insecure permissions.
Corda does not use any of the vulnerable functions so it is not
susceptible to this vulnerability
expires: 2023-10-19T17:08:41.029Z
created: 2023-02-02T17:08:41.032Z
patch: {}
125 changes: 125 additions & 0 deletions kotlin-samples/corda5-negotiation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Negotiation Cordapp

This CorDapp shows how multi-party negotiation is handled on the Corda ledger, in the absence of an API for user
interaction.

## Concepts

A flow is provided that allows a node to propose a trade to a counterparty. The counterparty has two options:

* Accepting the proposal, converting the `ProposalState` into a `TradeState` with identical attributes
* Modifying the proposal, consuming the existing `ProposalState` and replacing it with a new `ProposalState` for a new
amount

Only the recipient of the proposal has the ability to accept it or modify it. If the sender of the proposal tries to
accept or modify the proposal, this attempt will be rejected automatically at the flow level. Similarly, the modifier cannot accept the modified proposal.

### Flows

We start with the proposal flow implemented in `ProposalFlowRequest.kt`.


The modification of the proposal is implemented in `ModifyFlowRequest.java.kt`.


In the `AcceptFlowRequest.kt`, we receive the modified or unmodified ProposalState, and it is converted into a TradeState.



### Setting up

1. We begin our test deployment with clicking the `startCorda`. This task load up the combined Corda workers in Docker.
A successful deployment will allow you to open the REST APIs at: https://localhost:8888/api/v1/swagger#. You can test out some
functions to check connectivity. (GET /cpi function call should return an empty list as for now.)
2. We now deploy the CorDapp with a click of `5-vNodeSetup` task. Upon successful deployment of the CPI, the GET /cpi function call returns the metadata of the CPI you just upload.



### Running the CorDapp

In Corda 5, flows are triggered via `POST /flow/{holdingidentityshorthash}` and flow result has to be viewed at `GET /flow/{holdingidentityshorthash}/{clientrequestid}`
* holdingidentityshorthash: the ID of the network participants, i.e. Bob, Alice, Charlie. You can view all the short hashes of the network member with another Gradle task called `ListVNodes`
* clientrequestid: the ID you specify in the flow request body when you trigger a flow.

#### Step 1: Create Proposal State between two parties
Pick a VNode identity to initiate the Proposal state creation, and get its short hash. For example let's pick Alice.

Go to `POST /flow/{holdingidentityshorthash}`, enter the Alice's identity short hash and the following request body:
```
{
"clientRequestId": "createProposal",
"flowClassName": "com.r3.developers.samples.negotiation.workflows.Propose.ProposalFlowRequest",
"requestBody": {
"amount": 20,
"counterParty":"CN=Bob, OU=Test Dept, O=R3, L=London, C=GB"
}
}
```
After triggering the create-ProposalFlow, hop to `GET /flow/{holdingidentityshorthash}/{clientrequestid}` and enter Alice's identity short hash and client request id ("createProposal" in the case above) to view the flow result.


#### Step 2: List created Proposal state
In order to continue the CorDapp's logics, we need the Proposal ID- the identity of the created Proposal state. This step will bring out all the Proposal this entity (Alice) has.
Go to `POST /flow/{holdingidentityshorthash}`, enter the Alice's identity short hash and request body:
```
{
"clientRequestId": "list-1",
"flowClassName": "com.r3.developers.samples.negotiation.workflows.util.ListProposal",
"requestBody": {}
}
```
After trigger the List Proposal, hop to `GET /flow/{holdingidentityshorthash}/{clientrequestid}` and enter the Alice's short hash and client request id ("list-1" in the case above) to view the flow result.


#### Step 3: Modify the proposal
The responder, Bob, can edit the proposal if required by entering the new amount.
Go to `POST /flow/{holdingidentityshorthash}`, enter the Bob's identity short hash and request body:
```
{
"clientRequestId": "ModifyFlow",
"flowClassName": "com.r3.developers.samples.negotiation.workflows.Modify.ModifyFlowRequest",
"requestBody": {
"newAmount": 22,
"proposalID": "<use the proposal id here>"
}
}
```
After triggering the modify flow we need to hop to `GET /flow/{holdingidentityshorthash}/{clientrequestid}` and check the result. Enter Bob's hash id and the modify flow ID which is "ModifyFlow" in the case above.


#### Step 4: Accept the new proposal from bob `AcceptFlow`
In this step, Alice will accept the new proposal from Bob.
Goto `POST /flow/{holdingidentityshorthash}`, enter the identity Alice's short hash and request body, we also need to provide the proposalId, which is same as the proposal ID used in ModifyFlow body.
```
{
"clientRequestId": "AcceptFlow",
"flowClassName": "com.r3.developers.samples.negotiation.workflows.Accept.AcceptFlowRequest",
"requestBody": {
"proposalID": "<use the proposal id here>"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are missing the variable acceptor, but why do you need this input?
The accepter can only be the proposee of the proposal. In the contract, you can just use the proposee variable.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @peterli-r3 I've added the Acceptor to the documentation. We still need to know who is trying to accept the trade to be able to perform the necessary checks in the Accept contract.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @khutsijabari , I had quickly chatted with @7Dhruv eariler, You dont really need to add a variable to keep track of the proposer. You can check it in two ways:

  1. Check if the proposer with myInfo in the AcceptProposal flow initiator.
  2. Make the accept command take input, we can pass in the myInfo into the contract via the command.
    The idea is that we will try to have as less variables as possible in the states.

}
}
```
And as for the result of this flow, go to `GET /flow/{holdingidentityshorthash}/{clientrequestid}` and enter the required fields.

Thus, we have concluded a full run through of the Negotiation app.

### App Diagrams
Below are the app diagrams which are useful for the visual understanding.

#### Dynamic Diagram


![img_2.png](negotiation-sequence-diagram.png)





#### Static Diagram

![img.png](negotiation-design-diagram.png)





84 changes: 84 additions & 0 deletions kotlin-samples/corda5-negotiation/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import static org.gradle.api.JavaVersion.VERSION_11

plugins {
id 'org.jetbrains.kotlin.jvm'
id 'net.corda.cordapp.cordapp-configuration'
id 'org.jetbrains.kotlin.plugin.jpa'
id 'java'
id 'maven-publish'
id 'net.corda.plugins.csde'
}

allprojects {
group 'com.r3.developers.csdetemplate'
version '1.0-SNAPSHOT'

def javaVersion = VERSION_11

// Configure the CSDE
csde {
cordaClusterURL = "https://localhost:8888"
networkConfigFile = "config/static-network-config.json"
r3RootCertFile = "config/r3-ca-key.pem"
corDappCpiName = "MyCorDapp"
notaryCpiName = "NotaryServer"
cordaRpcUser = "admin"
cordaRpcPasswd ="admin"
workflowsModuleName = workflowsModule
csdeWorkspaceDir = "workspace"
notaryVersion = cordaNotaryPluginsVersion
combinedWorkerVersion = combinedWorkerJarVersion
postgresJdbcVersion = "42.4.3"
cordaDbContainerName = "CSDEpostgresql"
cordaBinDir = "${System.getProperty("user.home")}/.corda/corda5"
cordaCliBinDir = "${System.getProperty("user.home")}/.corda/cli"
}

// Declare the set of Kotlin compiler options we need to build a CorDapp.
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
allWarningsAsErrors = false

// Specify the version of Kotlin that we are that we will be developing.
languageVersion = '1.7'
// Specify the Kotlin libraries that code is compatible with
apiVersion = '1.7'
// Note that we Need to use a version of Kotlin that will be compatible with the Corda API.
// Currently that is developed in Kotlin 1.7 so picking the same version ensures compatibility with that.

// Specify the version of Java to target.
jvmTarget = javaVersion

// Needed for reflection to work correctly.
javaParameters = true

// -Xjvm-default determines how Kotlin supports default methods.
// JetBrains currently recommends developers use -Xjvm-default=all
// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-default/
freeCompilerArgs += [
"-Xjvm-default=all"
]
}
}

repositories {
// All dependencies are held in Maven Central
mavenLocal()
mavenCentral()
}

tasks.withType(Test).configureEach {
useJUnitPlatform()
}

}

publishing {
publications {
maven(MavenPublication) {
artifactId "corda-CSDE-kotlin-sample"
groupId project.group
artifact jar
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-----BEGIN CERTIFICATE-----
MIIB7zCCAZOgAwIBAgIEFyV7dzAMBggqhkjOPQQDAgUAMFsxCzAJBgNVBAYTAkdC
MQ8wDQYDVQQHDAZMb25kb24xDjAMBgNVBAoMBUNvcmRhMQswCQYDVQQLDAJSMzEe
MBwGA1UEAwwVQ29yZGEgRGV2IENvZGUgU2lnbmVyMB4XDTIwMDYyNTE4NTI1NFoX
DTMwMDYyMzE4NTI1NFowWzELMAkGA1UEBhMCR0IxDzANBgNVBAcTBkxvbmRvbjEO
MAwGA1UEChMFQ29yZGExCzAJBgNVBAsTAlIzMR4wHAYDVQQDExVDb3JkYSBEZXYg
Q29kZSBTaWduZXIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQDjSJtzQ+ldDFt
pHiqdSJebOGPZcvZbmC/PIJRsZZUF1bl3PfMqyG3EmAe0CeFAfLzPQtf2qTAnmJj
lGTkkQhxo0MwQTATBgNVHSUEDDAKBggrBgEFBQcDAzALBgNVHQ8EBAMCB4AwHQYD
VR0OBBYEFLMkL2nlYRLvgZZq7GIIqbe4df4pMAwGCCqGSM49BAMCBQADSAAwRQIh
ALB0ipx6EplT1fbUKqgc7rjH+pV1RQ4oKF+TkfjPdxnAAiArBdAI15uI70wf+xlL
zU+Rc5yMtcOY4/moZUq36r0Ilg==
-----END CERTIFICATE-----
51 changes: 51 additions & 0 deletions kotlin-samples/corda5-negotiation/config/log4j2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} %X - %msg%n"/>
</Console>

<RollingFile name="App"
fileName="logs/corda.log"
filePattern="logs/corda.%d{MM-dd-yyyy}.%i.log"
ignoreExceptions="false">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} %X - %msg%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy>
<Delete basePath="logs/">
<IfFileName glob="logs/corda.*.log">
<IfAny>
<IfAccumulatedFileSize exceeds="500 MB" />
<IfAccumulatedFileCount exceeds="10" />
</IfAny>
</IfFileName>
<IfLastModified age="7d" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<logger name="Console">
<AppenderRef ref="Console" level="info"/>
</logger>

<!-- log warn only for these 3rd party libs -->
<Logger name="com.zaxxer.hikari" level="warn" />
<Logger name="io.javalin.Javalin" level="warn" />
<Logger name="org.apache.aries.spifly" level="warn" />
<Logger name="org.apache.kafka" level="warn" />
<Logger name="org.eclipse.jetty" level="warn" />
<Logger name="org.hibernate" level="warn" />

<!-- default to warn only for OSGi logging -->
<Logger name="net.corda.osgi.framework.OSGiFrameworkWrap" level="warn" />

<root level="debug">
<AppenderRef ref="App" level="info"/>
</root>
</Loggers>
</Configuration>
32 changes: 32 additions & 0 deletions kotlin-samples/corda5-negotiation/config/r3-ca-key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-----BEGIN CERTIFICATE-----
MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg
RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV
UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu
Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG
SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y
ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If
xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV
ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO
DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ
jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6M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SoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm
gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+
-----END CERTIFICATE-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[
{
"x500Name" : "CN=Alice, OU=Test Dept, O=R3, L=London, C=GB",
"cpi" : "MyCorDapp"
},
{
"x500Name" : "CN=Bob, OU=Test Dept, O=R3, L=London, C=GB",
"cpi" : "MyCorDapp"
},
{
"x500Name" : "CN=Charlie, OU=Test Dept, O=R3, L=London, C=GB",
"cpi" : "MyCorDapp"
},
{
"x500Name" : "CN=Dave, OU=Test Dept, O=R3, L=London, C=GB",
"cpi" : "MyCorDapp"
},
{
"x500Name" : "CN=NotaryRep1, OU=Test Dept, O=R3, L=London, C=GB",
"cpi" : "NotaryServer",
"serviceX500Name": "CN=NotaryService, OU=Test Dept, O=R3, L=London, C=GB"
}
]
Loading