<h2>A two party trading protocol<aclass="headerlink"href="#a-two-party-trading-protocol"title="Permalink to this headline">¶</a></h2>
<p>We would like to implement the “hello world” of shared transaction building protocols: a seller wishes to sell some
<em>asset</em> (e.g. some commercial paper) in return for <em>cash</em>. The buyer wishes to purchase the asset using his cash. They
want the trade to be atomic so neither side is exposed to the risk of settlement failure. We assume that the buyer
and seller have found each other and arranged the details on some exchange, or over the counter. The details of how
the trade is arranged isn’t covered in this article.</p>
<p>Our protocol has two parties (B and S for buyer and seller) and will proceed as follows:</p>
<olclass="arabic simple">
<li>S sends a <codeclass="docutils literal"><spanclass="pre">StateAndRef</span></code> pointing to the state they want to sell to B, along with info about the price they require
B to pay.</li>
<li>B sends to S a <codeclass="docutils literal"><spanclass="pre">SignedWireTransaction</span></code> that includes the state as input, B’s cash as input, the state with the new
owner key as output, and any change cash as output. It contains a single signature from B but isn’t valid because
it lacks a signature from S authorising movement of the asset.</li>
<li>S signs it and hands the now finalised <codeclass="docutils literal"><spanclass="pre">SignedWireTransaction</span></code> back to B.</li>
</ol>
<p>You can find the implementation of this protocol in the file <codeclass="docutils literal"><spanclass="pre">contracts/protocols/TwoPartyTradeProtocol.kt</span></code>.</p>
<p>Assuming no malicious termination, they both end the protocol being in posession of a valid, signed transaction that
represents an atomic asset swap.</p>
<p>Note that it’s the <em>seller</em> who initiates contact with the buyer, not vice-versa as you might imagine.</p>
<spanclass="k">override</span><spanclass="k">fun</span><spanclass="nf">toString</span><spanclass="p">()</span><spanclass="p">=</span><spanclass="s">"The submitted asset didn't match the expected type: $expectedTypeName vs $typeName"</span>
<spanclass="p">}</span>
<spanclass="c1">// The buyer's side of the protocol. See note above Seller to learn about the caveats here.</span>
<li>It defines a several classes nested inside the main <codeclass="docutils literal"><spanclass="pre">TwoPartyTradeProtocol</span></code> singleton, and a couple of methods, one
to run the buyer side of the protocol and one to run the seller side.</li>
<li>It defines the “trade topic”, which is just a string that namespaces this protocol. The prefix “platform.” is reserved
by the DLG, but you can define your own protocols using standard Java-style reverse DNS notation.</li>
<li>The <codeclass="docutils literal"><spanclass="pre">runBuyer</span></code> and <codeclass="docutils literal"><spanclass="pre">runSeller</span></code> methods take a number of parameters that specialise the protocol for this run,
use them to construct a <codeclass="docutils literal"><spanclass="pre">Buyer</span></code> or <codeclass="docutils literal"><spanclass="pre">Seller</span></code> object respectively, and then add the new instances to the
<codeclass="docutils literal"><spanclass="pre">StateMachineManager</span></code>. The purpose of this class is described below. The <codeclass="docutils literal"><spanclass="pre">smm.add</span></code> method takes a logger name as
the first parameter, this is just a standard JDK logging identifier string, and the instance to add.</li>
</ul>
<p>Going through the data needed to become a seller, we have:</p>
<ulclass="simple">
<li><codeclass="docutils literal"><spanclass="pre">timestampingAuthority:</span><spanclass="pre">LegallyIdentifiableNode</span></code> - a reference to a node on the P2P network that acts as a trusted
timestamper. The use of timestamping is described in <aclass="reference internal"href="data-model.html"><em>Data model</em></a>.</li>
<li><codeclass="docutils literal"><spanclass="pre">otherSide:</span><spanclass="pre">SingleMessageRecipient</span></code> - the network address of the node with which you are trading.</li>
<li><codeclass="docutils literal"><spanclass="pre">assetToSell:</span><spanclass="pre">StateAndRef<OwnableState></span></code> - a pointer to the ledger entry that represents the thing being sold.</li>
<li><codeclass="docutils literal"><spanclass="pre">price:</span><spanclass="pre">Amount</span></code> - the agreed on price that the asset is being sold for.</li>
<li><codeclass="docutils literal"><spanclass="pre">myKeyPair:</span><spanclass="pre">KeyPair</span></code> - the key pair that controls the asset being sold. It will be used to sign the transaction.</li>
<li><codeclass="docutils literal"><spanclass="pre">buyerSessionID:</span><spanclass="pre">Long</span></code> - a unique number that identifies this trade to the buyer. It is expected that the buyer
knows that the trade is going to take place and has sent you such a number already. (This field may go away in a future
<li><codeclass="docutils literal"><spanclass="pre">acceptablePrice:</span><spanclass="pre">Amount</span></code> - the price that was agreed upon out of band. If the seller specifies a price less than
or equal to this, then the trade will go ahead.</li>
<li><codeclass="docutils literal"><spanclass="pre">typeToBuy:</span><spanclass="pre">Class<out</span><spanclass="pre">OwnableState></span></code> - the type of state that is being purchased. This is used to check that the
sell side of the protocol isn’t trying to sell us the wrong thing, whether by accident or on purpose.</li>
<li><codeclass="docutils literal"><spanclass="pre">sessionID:</span><spanclass="pre">Long</span></code> - the session ID that was handed to the seller in order to start the protocol.</li>
</ul>
<p>The run methods return a <codeclass="docutils literal"><spanclass="pre">ListenableFuture</span></code> that will complete when the protocol has finished.</p>
to either runBuyer or runSeller, depending on who we are, and then call <codeclass="docutils literal"><spanclass="pre">.get()</span></code> on resulting object to
<p>Finally, we define a couple of exceptions, and a class that will be used as a protocol message called <codeclass="docutils literal"><spanclass="pre">SellerTradeInfo</span></code>.</p>
</div>
<divclass="section"id="suspendable-methods">
<h2>Suspendable methods<aclass="headerlink"href="#suspendable-methods"title="Permalink to this headline">¶</a></h2>
<p>The <codeclass="docutils literal"><spanclass="pre">call</span></code> method of the buyer/seller classes is marked with the <codeclass="docutils literal"><spanclass="pre">@Suspendable</span></code> annotation. What does this mean?</p>
<p>As mentioned above, our protocol framework will at points suspend the code and serialise it to disk. For this to work,
any methods on the call stack must have been pre-marked as <codeclass="docutils literal"><spanclass="pre">@Suspendable</span></code> so the bytecode rewriter knows to modify
the underlying code to support this new feature. A protocol is suspended when calling either <codeclass="docutils literal"><spanclass="pre">receive</span></code>, <codeclass="docutils literal"><spanclass="pre">send</span></code> or
<codeclass="docutils literal"><spanclass="pre">sendAndReceive</span></code> which we will learn more about below. For now, just be aware that when one of these methods is
invoked, all methods on the stack must have been marked. If you forget, then in the unit test environment you will
get a useful error message telling you which methods you didn’t mark. The fix is simple enough: just add the annotation
and try again.</p>
<divclass="admonition note">
<pclass="first admonition-title">Note</p>
<pclass="last">A future version of Java is likely to remove this pre-marking requirement completely.</p>
with a <codeclass="docutils literal"><spanclass="pre">MessagingService</span></code> and iterate the right state machine when messages arrive. It provides the
send/receive/sendAndReceive calls that let the code request network interaction and it will store a serialised copy of
each state machine before it’s suspended to wait for the network.</p>
<p>To get a <codeclass="docutils literal"><spanclass="pre">StateMachineManager</span></code>, you currently have to build one by passing in a <codeclass="docutils literal"><spanclass="pre">ServiceHub</span></code> and a thread or thread
pool which it can use. This will change in future so don’t worry about the details of this too much: just check the
unit tests to see how it’s done.</p>
</div>
<divclass="section"id="implementing-the-seller">
<h2>Implementing the seller<aclass="headerlink"href="#implementing-the-seller"title="Permalink to this headline">¶</a></h2>
<p>Let’s implement the <codeclass="docutils literal"><spanclass="pre">Seller.call</span></code> method. This will be invoked by the platform when the protocol is started by the
<spanclass="n">logger</span><spanclass="p">().</span><spanclass="n">trace</span><spanclass="p">{</span><spanclass="s">"Received partially signed transaction"</span><spanclass="p">}</span>
the initial protocol message, and then call <codeclass="docutils literal"><spanclass="pre">sendAndReceive</span></code>. This function takes a few arguments:</p>
<ulclass="simple">
<li>The topic string that ensures the message is routed to the right bit of code in the other side’s node.</li>
<li>The session IDs that ensure the messages don’t get mixed up with other simultaneous trades.</li>
<spanclass="s">"transaction sends us the right amount of cash"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">wtx</span><spanclass="p">.</span><spanclass="n">outputStates</span><spanclass="p">.</span><spanclass="n">sumCashBy</span><spanclass="p">(</span><spanclass="n">args</span><spanclass="p">.</span><spanclass="n">myKeyPair</span><spanclass="p">.</span><spanclass="k">public</span><spanclass="p">)</span><spanclass="p">==</span><spanclass="n">args</span><spanclass="p">.</span><spanclass="n">price</span><spanclass="p">)</span>
<spanclass="c1">// There are all sorts of funny games a malicious secondary might play here, we should fix them:</span>
<spanclass="c1">//</span>
<spanclass="c1">// - This tx may attempt to send some assets we aren't intending to sell to the secondary, if</span>
<spanclass="c1">// we're reusing keys! So don't reuse keys!</span>
<spanclass="c1">// - This tx may not be valid according to the contracts of the input states, so we must resolve</span>
<spanclass="c1">// and fully audit the transaction chains to convince ourselves that it is actually valid.</span>
<spanclass="c1">// - This tx may include output states that impose odd conditions on the movement of the cash,</span>
<spanclass="c1">// once we implement state pairing.</span>
<spanclass="n">logger</span><spanclass="p">().</span><spanclass="n">trace</span><spanclass="p">{</span><spanclass="s">"Built finished transaction, sending back to secondary!"</span><spanclass="p">}</span>
<li>We create a cash spend in the normal way, by using <codeclass="docutils literal"><spanclass="pre">Cash().craftSpend</span></code>. See the contracts tutorial if this isn’t
<li>We access the <em>service hub</em> when we need it to access things that are transient and may change or be recreated
whilst a protocol is suspended, things like the wallet or the timestamping service. Remember that a protocol may
be suspended when it waits to receive a message across node or computer restarts, so objects representing a service
or data which may frequently change should be accessed ‘just in time’.</li>
<li>Finally, we send the unfinsished, invalid transaction to the seller so they can sign it. They are expected to send
back to us a <codeclass="docutils literal"><spanclass="pre">TimestampedWireTransaction</span></code>, which once we verify it, should be the final outcome of the trade.</li>
</ol>
<p>As you can see, the protocol logic is straightforward and does not contain any callbacks or network glue code, despite
the fact that it takes minimal resources and can survive node restarts.</p>
<divclass="admonition warning">
<pclass="first admonition-title">Warning</p>
<pclass="last">When accessing things via the <codeclass="docutils literal"><spanclass="pre">serviceHub</span></code> field, avoid the temptation to stuff a reference into a local variable.
If you do this then next time your protocol waits to receive an object, the system will try and serialise all your
local variables and end up trying to serialise, e.g. the timestamping service, which doesn’t make any conceptual
sense. The <codeclass="docutils literal"><spanclass="pre">serviceHub</span></code> field is defined by the <codeclass="docutils literal"><spanclass="pre">ProtocolStateMachine</span></code> superclass and is marked transient so
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.