Get started with Corda

Corda Aug 03 2021 By: David Awad
Comments

0 Comments

Views

2,320 Views

Get started with Corda
David Awad
David Awad Developer
Share this post:
Copied

Perhaps you’ve heard about blockchain in the past. Maybe you’ve written code once or twice. I want to give you a simple guide on how you can think about building on a permissioned blockchain like Corda.

The use case for Corda is quite different from most blockchain technologies you have likely come across. Remember that Corda is a point-to-point network that operates on a need-to-know basis between only the required signers on any given transaction. Corda exists for an entirely different use case; blockchain for the enterprise. 

These organizations want to leverage the trustless, decentralized ledger but benefit from the anonymity trade-off by gaining privacy and scalability in exchange. With Corda, all kinds of organizations use blockchain, from the Nasdaq to the Central Bank of Egypt. Now is as good a time as any to learn what all the hype is about. 

Remember that in principle, each person on a blockchain is running a node that represents their identity for their transactions on the blockchain. In Corda’s model, you issue objects on the blockchain and associate them with a key pair that’s unique to you (or your node). You can customize these objects and do whatever you like with them as long as the updates you’re proposing are valid and your node has control over those assets. When these nodes collaborate as a network, they’re able to maintain a shared source of truth for the state of the objects on the ledger. You, a developer, can then write CorDapps to facilitate the exchanges of these objects and work with them however you want.

We generally think about these digital objects as possessing some value and then think about who owns what objects, and then change ownership or create new objects. This all sounds harder than it really is. There are essentially three concepts to keep in mind for building Cordapps; states, flows, and contracts.

States

The first question you’re probably wondering about representing objects on the ledger is how to define the things themselves. That’s what states do. 

A state is a java (or kotlin) class that maintains whatever data you want to track within a single object on the blockchain. Once you have your states on the blockchain, all you need to do is determine how they’re modified, and then you can start using the blockchain for whatever you like. 

Let’s imagine a state that tracks the most straightforward concept, a token intended to represent a digital asset. Our asset will have an owner and an amount.

    
@belongstocontract(tokencontract.class)
  public class tokenstate implements contractstate {
  
      private final party issuer;
      private final party owner;
      private final int amount;
      private final list participants;
  
      public tokenstate(party issuer, party owner, int amount) {
          this.issuer = issuer;
          this.owner = owner;
          this.amount = amount;
          this.participants = new arraylist<>();
          participants.add(issuer);
          participants.add(owner);
      }    

Flows

So how do we modify an object on the ledger? This is where you’d turn to use flows. Flows are a mechanism given to you by corda for updating states on the blockchain by sharing the proposed update to all the required signers. A big transition from public blockchains is that in a corda network, the transaction is only shared among the participants that need to know. There is no notion of required consensus among 51% of the network. Instead, Corda has the notary

Here’s an excellent example of seeing this concept come together as we propose an update to the corda ledger.

    
public TokenIssueFlowInitiator(Party owner, int amount) {
    this.owner = owner;
    this.amount = amount;
}


@Suspendable
@Override
public SignedTransaction call() throws FlowException {
    Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

    Party issuer = getOurIdentity();

    TokenState tokenState = new TokenState(issuer, owner, amount);

    TransactionBuilder transactionBuilder = new TransactionBuilder(notary);

    CommandData commandData = new TokenContract.Commands.Issue();

    transactionBuilder.addCommand(commandData, issuer.getOwningKey(), owner.getOwningKey());

    transactionBuilder.addOutputState(tokenState, TokenContract.ID);

    transactionBuilder.verify(getServiceHub());

    FlowSession session = initiateFlow(owner);

    SignedTransaction signedTransaction = getServiceHub().signInitialTransaction(transactionBuilder);

    SignedTransaction fullySignedTransaction = subFlow(new CollectSignaturesFlow(signedTransaction, singletonList(session)));

    return subFlow(new FinalityFlow(fullySignedTransaction, singletonList(session)));
}

Contracts

So a smart contract in Corda works the same way that you’d expect a contract to work. A contract is designed to outline an agreement between multiple entities. The contract in Corda outlines what you can and cannot do with the relevant states on the blockchain. For example, a token like we’ve outlined here can’t have a negative number for the ‘amount’ field because it’s a positive integer. 

    
public class TokenContract implements Contract {
    public static String ID = "bootcamp.TokenContract";

    @Override
    public void verify(LedgerTransaction tx) throws IllegalArgumentException {

        CommandWithParties command = requireSingleCommand(tx.getCommands(), TokenContract.Commands.class);

        List inputs = tx.getInputStates();
        List outputs = tx.getOutputStates();

        if (command.getValue() instanceof TokenContract.Commands.Issue) {
            requireThat(req -> {
                req.using("Transaction must have no input states.", inputs.isEmpty());
                req.using("Transaction must have exactly one output.", outputs.size() == 1);
                req.using("Output must be a TokenState.", outputs.get(0) instanceof TokenState);
                TokenState output = (TokenState) outputs.get(0);
                req.using("Issuer must be required singer.", command.getSigners().contains(output.getIssuer().getOwningKey()));
                req.using("Owner must be required singer.", command.getSigners().contains(output.getOwner().getOwningKey()));
                req.using("Amount must be positive.", output.getAmount() > 0);
                return null;
            });
        } else {
            throw new IllegalArgumentException("Unrecognized command");
        }
    }

Wrapping up

This post is about clearing up how to use Corda for developers. With these paradigms in mind, hopefully it’s clear how you can use this to build some meaningful ideas!

The best use cases we’ve seen are ones in which the parties involved don’t need identity to be private, but still want a trustless decentralized datastore. A great example is processing car insurance repair claims where the repair shops don’t trust the insurers. Another good example is using smart contracts for pro-rating internet service, meaning you run a node that monitors your bandwidth and actually updates the state of the ledger for the average speed per-day and your bill is a function of the ledger data.

David Awad
David Awad David Awad is a Developer Evangelist at R3, an enterprise blockchain software firm working with a global ecosystem of more than 350 participants across multiple industries from both the private and public sectors to develop on Corda, its open-source blockchain platform, and Corda Enterprise, a commercial version of Corda for enterprise usage. Follow David on Twitter here.

Leave a Reply

Subscribe to our newsletter to stay up to date on the latest developer news, tools, and articles.