Advertisement
Guest User

Corda Flow

a guest
Jul 10th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.08 KB | None | 0 0
  1. package com.insureflight.flows
  2.  
  3. import co.paralleluniverse.fibers.Suspendable
  4. import net.corda.confidential.SwapIdentitiesFlow
  5. import net.corda.core.contracts.Amount
  6. import net.corda.core.flows.*
  7. import net.corda.core.identity.Party
  8. import net.corda.core.contracts.Command
  9. import net.corda.core.transactions.SignedTransaction
  10. import net.corda.core.transactions.TransactionBuilder
  11. import net.corda.core.utilities.ProgressTracker
  12. import net.corda.core.utilities.ProgressTracker.Step
  13. import net.corda.core.utilities.seconds
  14. import net.corda.finance.contracts.asset.Cash
  15. import net.corda.finance.contracts.getCashBalance
  16. import com.insureflight.Policy
  17. import com.insureflight.InsureFlightContract
  18. import net.corda.confidential.IdentitySyncFlow
  19. import com.insureflight.InsureFlightContract.Companion.INSUREFLIGHT_CONTRACT_ID
  20. import java.util.*
  21. import java.security.PrivateKey
  22. import java.time.LocalDateTime
  23. import net.corda.core.contracts.requireThat
  24. import net.corda.core.utilities.loggerFor
  25. import java.util.function.Predicate
  26. //Added Oraclize to grab external data
  27. import it.oraclize.cordapi.entities.Answer
  28. import it.oraclize.cordapi.flows.*
  29. import it.oraclize.cordapi.entities.*
  30. import it.oraclize.cordapi.OraclizeUtils
  31.  
  32.  
  33. //NOTE: IssuePolicy must be executed on client interface only
  34. object IssuePolicy {
  35. @InitiatingFlow
  36. @StartableByRPC
  37. class Initiator(private val premium: Amount<Currency>,
  38. private val client: Party,
  39. private val underwriter: Party,
  40. private val flight: String) : InsureFlightBaseFlow() {
  41.  
  42. companion object {
  43. object INITIALIZING : Step("Performing initial steps.")
  44. object BUILDING : Step("Building and verifying transaction.")
  45. object SIGNING : Step("Signing transaction.")
  46. object COLLECTING : Step("Collecting counterparty signature.") {
  47. override fun childProgressTracker() = CollectSignaturesFlow.tracker()
  48. }
  49. object FINALIZING : Step("Finalizing transaction.") {
  50. override fun childProgressTracker() = FinalityFlow.tracker()
  51. }
  52. val console = loggerFor<IssuePolicy>()
  53. fun tracker() = ProgressTracker(INITIALIZING, BUILDING, SIGNING, COLLECTING, FINALIZING)
  54. }
  55.  
  56. override val progressTracker: ProgressTracker = tracker()
  57.  
  58. @Suspendable
  59. override fun call(): SignedTransaction {
  60. // Step 1. Initialization.
  61. progressTracker.currentStep = INITIALIZING
  62. val claim = Amount(0.toLong() * 100, Currency.getInstance("CAD"))
  63. val policy = Policy(premium, claim, client, underwriter, flight)
  64. val ourSigningKey = policy.client.owningKey
  65.  
  66. // Stage 2. Check client has enough cash to issue a policy and that the flight is grounded.
  67. val cashBalance = serviceHub.getCashBalance(premium.token)
  68. check(cashBalance.quantity > 0) {
  69. throw FlowException("Client has no ${premium.token} to receive a policy.")
  70. }
  71. check(cashBalance >= premium) {
  72. throw FlowException("Client has only $cashBalance but needs $premium to receive a policy.")
  73. }
  74.  
  75. val current = LocalDateTime.now().toString()
  76. val airplaneStatus = subFlow(OraclizeQueryAwaitFlow(
  77. datasource = "URL",
  78. query = "json(https://api.flightstats.com/flex/flightstatus/rest/v2/json/flight/status/" + flight.subSequence(0,2) + "/" + flight.subSequence(2, flight.length) + "/arr/" +
  79. current.subSequence(0,4) + "/" + current.subSequence(5,7) + "/" + current.subSequence(8,10) + "?appId=8b03564f&appKey=b2b168c689f3fabc6ef252ca95fa77ad&utc=false).flightStatuses.status",
  80. proofType = ProofType.TLSNOTARY
  81.  
  82. ))
  83.  
  84. console.info(airplaneStatus.toString())
  85. console.info("Oraclize: ${airplaneStatus.queryId} proccessed")
  86. val proofVerificationTool = OraclizeUtils.ProofVerificationTool()
  87. proofVerificationTool.verifyProof(airplaneStatus.proof as ByteArray)
  88. val oracle = serviceHub.identityService.wellKnownPartyFromX500Name(OraclizeUtils.getNodeName()) as Party
  89. val answerCommand = Command(airplaneStatus, oracle.owningKey)
  90.  
  91.  
  92. /*
  93. val status = airplaneStatus.rawValue as? String
  94. check(status.equals("S")) {
  95. throw FlowException("The flight should not have departed.")
  96. }
  97. */
  98.  
  99. // Step 3. Building.
  100. progressTracker.currentStep = BUILDING
  101. val notary = serviceHub.networkMapCache.notaryIdentities[0]
  102. val utx = TransactionBuilder(notary = notary)
  103. .addOutputState(policy, INSUREFLIGHT_CONTRACT_ID)
  104. .addCommand(InsureFlightContract.Commands.Issue(), policy.participants.map { it.owningKey })
  105. .setTimeWindow(serviceHub.clock.instant(), 30.seconds)
  106. .withItems(answerCommand)
  107.  
  108. utx.verify(serviceHub)
  109.  
  110. // Give to the oracle only the appropriate
  111. // commands inside the tx
  112. fun filtering(elem: Any): Boolean {
  113. return when (elem) {
  114. is Command<*> -> oracle.owningKey in elem.signers && elem.value is Answer
  115. else -> false
  116. }
  117. }
  118.  
  119. val ftx = utx.toWireTransaction(serviceHub).buildFilteredTransaction(Predicate { filtering(it) })
  120.  
  121. // Stage 4. Get some cash from the vault and add a spend to our transaction builder.
  122. // We pay cash to the underwriter's policy key.
  123. val (_, cashSigningKeys) = Cash.generateSpend(serviceHub, utx, premium, underwriter)
  124.  
  125. // Step 5. Sign the transaction.
  126. progressTracker.currentStep = SIGNING
  127.  
  128. val ptx = serviceHub.signInitialTransaction(utx, ourSigningKey).withAdditionalSignature(subFlow(OraclizeSignFlow(ftx)))
  129.  
  130. // Step 6. Get the counter-party signature.
  131. progressTracker.currentStep = COLLECTING
  132. val otherpartySession = initiateFlow(underwriter)
  133. val stx = subFlow(CollectSignaturesFlow(
  134. ptx,
  135. listOf(otherpartySession),
  136. COLLECTING.childProgressTracker())
  137. )
  138.  
  139.  
  140. // Step 7. Finalize the transaction.
  141. progressTracker.currentStep = FINALIZING
  142. return subFlow(FinalityFlow(stx, FINALIZING.childProgressTracker()))
  143. }
  144. }
  145.  
  146. @InitiatedBy(Initiator::class)
  147. class IssuePolicyResponder(val otherPartySession: FlowSession) : FlowLogic<Unit>() {
  148. @Suspendable
  149. override fun call() {
  150. val signTransactionFlow = object : SignTransactionFlow(otherPartySession, SignTransactionFlow.tracker()) {
  151. override fun checkTransaction(stx: SignedTransaction) = requireThat {
  152. }
  153. }
  154.  
  155. subFlow(signTransactionFlow)
  156. }
  157. }
  158. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement