Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.insureflight.flows
- import co.paralleluniverse.fibers.Suspendable
- import net.corda.confidential.SwapIdentitiesFlow
- import net.corda.core.contracts.Amount
- import net.corda.core.flows.*
- import net.corda.core.identity.Party
- import net.corda.core.contracts.Command
- import net.corda.core.transactions.SignedTransaction
- import net.corda.core.transactions.TransactionBuilder
- import net.corda.core.utilities.ProgressTracker
- import net.corda.core.utilities.ProgressTracker.Step
- import net.corda.core.utilities.seconds
- import net.corda.finance.contracts.asset.Cash
- import net.corda.finance.contracts.getCashBalance
- import com.insureflight.Policy
- import com.insureflight.InsureFlightContract
- import net.corda.confidential.IdentitySyncFlow
- import com.insureflight.InsureFlightContract.Companion.INSUREFLIGHT_CONTRACT_ID
- import java.util.*
- import java.security.PrivateKey
- import java.time.LocalDateTime
- import net.corda.core.contracts.requireThat
- import net.corda.core.utilities.loggerFor
- import java.util.function.Predicate
- //Added Oraclize to grab external data
- import it.oraclize.cordapi.entities.Answer
- import it.oraclize.cordapi.flows.*
- import it.oraclize.cordapi.entities.*
- import it.oraclize.cordapi.OraclizeUtils
- //NOTE: IssuePolicy must be executed on client interface only
- object IssuePolicy {
- @InitiatingFlow
- @StartableByRPC
- class Initiator(private val premium: Amount<Currency>,
- private val client: Party,
- private val underwriter: Party,
- private val flight: String) : InsureFlightBaseFlow() {
- companion object {
- object INITIALIZING : Step("Performing initial steps.")
- object BUILDING : Step("Building and verifying transaction.")
- object SIGNING : Step("Signing transaction.")
- object COLLECTING : Step("Collecting counterparty signature.") {
- override fun childProgressTracker() = CollectSignaturesFlow.tracker()
- }
- object FINALIZING : Step("Finalizing transaction.") {
- override fun childProgressTracker() = FinalityFlow.tracker()
- }
- val console = loggerFor<IssuePolicy>()
- fun tracker() = ProgressTracker(INITIALIZING, BUILDING, SIGNING, COLLECTING, FINALIZING)
- }
- override val progressTracker: ProgressTracker = tracker()
- @Suspendable
- override fun call(): SignedTransaction {
- // Step 1. Initialization.
- progressTracker.currentStep = INITIALIZING
- val claim = Amount(0.toLong() * 100, Currency.getInstance("CAD"))
- val policy = Policy(premium, claim, client, underwriter, flight)
- val ourSigningKey = policy.client.owningKey
- // Stage 2. Check client has enough cash to issue a policy and that the flight is grounded.
- val cashBalance = serviceHub.getCashBalance(premium.token)
- check(cashBalance.quantity > 0) {
- throw FlowException("Client has no ${premium.token} to receive a policy.")
- }
- check(cashBalance >= premium) {
- throw FlowException("Client has only $cashBalance but needs $premium to receive a policy.")
- }
- val current = LocalDateTime.now().toString()
- val airplaneStatus = subFlow(OraclizeQueryAwaitFlow(
- datasource = "URL",
- query = "json(https://api.flightstats.com/flex/flightstatus/rest/v2/json/flight/status/" + flight.subSequence(0,2) + "/" + flight.subSequence(2, flight.length) + "/arr/" +
- current.subSequence(0,4) + "/" + current.subSequence(5,7) + "/" + current.subSequence(8,10) + "?appId=8b03564f&appKey=b2b168c689f3fabc6ef252ca95fa77ad&utc=false).flightStatuses.status",
- proofType = ProofType.TLSNOTARY
- ))
- console.info(airplaneStatus.toString())
- console.info("Oraclize: ${airplaneStatus.queryId} proccessed")
- val proofVerificationTool = OraclizeUtils.ProofVerificationTool()
- proofVerificationTool.verifyProof(airplaneStatus.proof as ByteArray)
- val oracle = serviceHub.identityService.wellKnownPartyFromX500Name(OraclizeUtils.getNodeName()) as Party
- val answerCommand = Command(airplaneStatus, oracle.owningKey)
- /*
- val status = airplaneStatus.rawValue as? String
- check(status.equals("S")) {
- throw FlowException("The flight should not have departed.")
- }
- */
- // Step 3. Building.
- progressTracker.currentStep = BUILDING
- val notary = serviceHub.networkMapCache.notaryIdentities[0]
- val utx = TransactionBuilder(notary = notary)
- .addOutputState(policy, INSUREFLIGHT_CONTRACT_ID)
- .addCommand(InsureFlightContract.Commands.Issue(), policy.participants.map { it.owningKey })
- .setTimeWindow(serviceHub.clock.instant(), 30.seconds)
- .withItems(answerCommand)
- utx.verify(serviceHub)
- // Give to the oracle only the appropriate
- // commands inside the tx
- fun filtering(elem: Any): Boolean {
- return when (elem) {
- is Command<*> -> oracle.owningKey in elem.signers && elem.value is Answer
- else -> false
- }
- }
- val ftx = utx.toWireTransaction(serviceHub).buildFilteredTransaction(Predicate { filtering(it) })
- // Stage 4. Get some cash from the vault and add a spend to our transaction builder.
- // We pay cash to the underwriter's policy key.
- val (_, cashSigningKeys) = Cash.generateSpend(serviceHub, utx, premium, underwriter)
- // Step 5. Sign the transaction.
- progressTracker.currentStep = SIGNING
- val ptx = serviceHub.signInitialTransaction(utx, ourSigningKey).withAdditionalSignature(subFlow(OraclizeSignFlow(ftx)))
- // Step 6. Get the counter-party signature.
- progressTracker.currentStep = COLLECTING
- val otherpartySession = initiateFlow(underwriter)
- val stx = subFlow(CollectSignaturesFlow(
- ptx,
- listOf(otherpartySession),
- COLLECTING.childProgressTracker())
- )
- // Step 7. Finalize the transaction.
- progressTracker.currentStep = FINALIZING
- return subFlow(FinalityFlow(stx, FINALIZING.childProgressTracker()))
- }
- }
- @InitiatedBy(Initiator::class)
- class IssuePolicyResponder(val otherPartySession: FlowSession) : FlowLogic<Unit>() {
- @Suspendable
- override fun call() {
- val signTransactionFlow = object : SignTransactionFlow(otherPartySession, SignTransactionFlow.tracker()) {
- override fun checkTransaction(stx: SignedTransaction) = requireThat {
- }
- }
- subFlow(signTransactionFlow)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement