Managed File Transfer

 View Only

Blockchain Integration with IBM B2B Sterling Integrator

By Tanvi Kakodkar posted Tue March 03, 2020 02:25 AM

  
Originally updated on 9th Feb 2019 by PV1P_Bipin_Chandra

BLOCKCHAIN INTEGRATION WITH B2BI

(USING HYPERLEDGER FABRIC & HYPERLEDGER COMPOSER)

 

Introduction

Blockchain

Blockchain is one of the emerging technologies in today's world and a lot of revolution and research has just began regarding this distributed technology – mostly reinventing the ways in which businesses are done. Blockchain technologies which have the ability to reshape and transform industries such as finance, healthcare, government, manufacturing, and supply chain.

The blockchain is a distributed database of records of all transactions or digital event that have been executed and shared among participating parties. Each transaction verified by the majority of participants of the system. It contains every single record of each transaction. Bitcoin is the most popular cryptocurrency an example of the blockchain.


Blockchain for Business

Large Corporations are spending time and resources to find out how much business they can gain by adopting Blockchain technology. Blockchain has the potential of a trans-formative technology. Blockchain technology allows solving two important issues, those of trust and the speed of business operations.

- Smart contracts: Perhaps the most relevant Blockchain feature, smart contracts are self-executing contractual states, stored on the Blockchain, which nobody controls and, therefore, everyone can trust. The code can control and restrict how the data is accessed and used.

- Irrevocability: There is an irrevocable trail (i.e., timestamping) of all the transactions that have ever been made, which makes attempts at hacking or fraud unsuccessful.
- Asset transfer: It allows property whose ownership is controlled via the Blockchain (i.e. physical property such as cars, phones or houses).
- Distributed: The ledger represents the truth because mass collaboration constantly reconciles, without having the need to trust because that’s built into the mechanism.

Utilizing the blockchain technology, one can seamlessly handle the process, involving along sending and receiving of cash, signing contracts, accepting the deposits and significantly more.

Blockchain and Sterling B2B integrator

“Blockchain for business” are typically private business networks, where all participants on the network are known and permissioned. In this document, Sterling B2B Integrator leverages the Hyperledger Fabric and connects with Blockchain. “

Sterling B2B Integrator is a B2B integration platform. It helps organisations transact business documents – such as purchase orders, shipping notices, and invoices – with their suppliers and partners. Using ‘Blockchain integration with B2Bi’ – any customer can not only read any transaction from the blockchain but can also perform CRUD operations on assets, partners and even execute transactions on its own.

Once a transaction happens on Blockchain, it can trigger a Business Process which gets executed on Sterling B2Bi. B2Bi can subscribe any event from Blockchain network and once the event gets triggered it can execute any predefined business process/es w.r.t. the type of transaction happened.

Blockchain brings trust back to B2B, provides efficient supply chains, provide safe and secure transactions. See the ‘Use Case’ section for more detail.


Implementation

Hyperledger

Hyperledger is an eco-system which incubates lots of project related to concept of Blockchain. The objective of the Hyperledger project is to advance cross-industry collaboration by developing blockchains and distributed ledgers, with a particular focus on improving the performance and reliability of these systems.

You can find list of Hyperledger Projects here - https://www.hyperledger.org/projects

Two important projects are:

  • Hyperledger Fabric – a framework to use a distributed ledger to create

    business application.

  • Hyperledger Composer – built on top of fabric – to ease the development of

    blockchain using fabric.


    HYPERLEDGER FABRIC

    Hyperledger Fabric is a framework to use a distributed ledger to create business applications. It is an open source designed for use in enterprise contexts. Its modular and versatile design satisfies a broad range of industry use cases. It offers a unique approach to consensus that enables performance at scale while preserving privacy.

    A smart contract, or what Fabric calls “chaincode”, supports - Java, Go and Node.js The Fabric platform is also permissioned, meaning that, unlike with a public permission-less network, the participants are known to each other, rather than anonymous and therefore fully untrusted.

    A Fabric Network comprises "Peer nodes", which execute chaincode, access ledger data, endorse transactions and interface with applications.


    HYPERLEDGER COMPOSER

    Hyperledger Composer is built on top of Fabric – to ease the development of blockchain using Hyperledger Fabric.

    Hyperledger Composer is a set of collaboration tools for building blockchain business networks that make it simple and fast for business owners and developers to create smart contracts and blockchain applications to solve business problems.

    It has following components as shown in the figure below:

  • ➢  Model File – Asset, Participants, Transactions -> .cto

  • ➢  Script File – Transaction logic function -> .js

  • ➢  Access Control rules -> .acl

  • ➢  Query Definitions -> .qry

  • ➢  Build a business network -> .bna

  • ➢  Business Network cards - combination of an identity, a connection profile, and

    metadata (business network name)

  • ➢  Historian registry - records successful transactions, participants etc.



Setting Up Hyperledger Composer

Pre-requisites

The Hyperledger Composer pre-requisites can be installed on Ubuntu or MacOS. To run Hyperledger Composer and Hyperledger Fabric follow the below url to install prerequisites:

https://hyperledger.github.io/composer/v0.19/installing/installing-prereqs


SETTING UP THE DEVELOPMENT ENVIRONMENT

Follow the below URL to obtain the Hyperledger Composer development tools (primarily used to create Business Networks) and stand up a Hyperledger Fabric (primarily used to run/deploy your Business Networks locally). https://hyperledger.github.io/composer/v0.19/installing/development-tools


CREATE YOUR BLOCKCHAIN APPLICATION

The Hyperledger Composer Developer Guide details instructions for getting a blockchain up and running locally on your machine, then exposing that Blockchain via REST API.

A blockchain is now running, and the Composer-REST-Server allows the deployed business network to be integrated with via REST API.

Follow the below URL to generate a REST API based on a business network.

https://hyperledger.github.io/composer/v0.19/tutorials/developer-tutorial


DEFINING A BUSINESS NETWORK

Model file: model/org.example.basic.cto
The first document to update is the model (.cto) file. This file is written using

the Hyperledger Composer Modelling Language. The model file contains the definitions of each class of asset, transaction, participant, and event.

/**
 * Write your model definitions here
 */
namespace org.example.basic

participant SampleParticipant identified by participantId { o String participantId
o String firstName
o String lastName

}

asset SampleAsset identified by assetId { o String assetId
--> SampleParticipant owner
o String value

}

transaction SampleTransaction {
  --> SampleAsset asset
  o String newValue
}
event SampleEvent {

}

--> SampleAsset asset
o String oldValue
o String newValue

Script file: lib/logic.js
This contains the transaction logic, specifying a relationship to an asset, and a

participant.

/**
 * Write your transction processor functions here
 */
/**
 * Sample transaction
 * @param {org.example.basic.SampleTransaction} sampleTransaction
 * @transaction
 */
async function sampleTransaction(tx) {
    // Save the old value of the asset.
    const oldValue = tx.asset.value;
    // Update the asset with the new value.
    tx.asset.value = tx.newValue;
    // Get the asset registry for the asset.
    const assetRegistry = await
getAssetRegistry('org.example.basic.SampleAsset');

// Update the asset in the asset registry. await assetRegistry.update(tx.asset);

    // Emit an event for the modified asset.
    let event = getFactory().newEvent('org.example.basic', 'SampleEvent');
    event.asset = tx.asset;
    event.oldValue = oldValue;
    event.newValue = tx.newValue;
    emit(event);

}

Adding access control: permissions.acl This contains access control rules.

/**
* Sample access control list. */

rule EverybodyCanReadEverything {

description: "Allow all participants read access to all resources" participant: "org.example.basic.SampleParticipant"
operation: READ
resource: "org.example.basic.*"

    action: ALLOW
}
rule EverybodyCanSubmitTransactions {
    description: "Allow all participants to submit transactions"
    participant: "org.example.basic.SampleParticipant"
    operation: CREATE
    resource: "org.example.basic.SampleTransaction"
    action: ALLOW

}

rule OwnerHasFullAccessToTheirAssets {
description: "Allow all participants full access to their assets" participant(p): "org.example.basic.SampleParticipant"
operation: ALL

    resource(r): "org.example.basic.SampleAsset"
    condition: (r.owner.getIdentifier() === p.getIdentifier())
    action: ALLOW

rule SystemACL {
description: "System ACL to permit all access" participant: "org.hyperledger.composer.system.Participant" operation: ALL
resource: "org.hyperledger.composer.system.**"
action: ALLOW

}

rule NetworkAdminUser {
description: "Grant business network administrators full access to user

resources"
    participant: "org.hyperledger.composer.system.NetworkAdmin"
    operation: ALL
    resource: "**"
    action: ALLOW

}

rule NetworkAdminSystem {
    description: "Grant business network administrators full access to system
resources"
    participant: "org.hyperledger.composer.system.NetworkAdmin"
    operation: ALL
    resource: "org.hyperledger.composer.system.**"
    action: ALLOW

}

}


GENERATE A BUSINESS NETWORK ARCHIVE

$ composer archive create -t dir -n . Creates a .bna (business network archive file).

DEPLOYING THE BUSINESS NETWORK

Follow this document to deploy your .bna file -

https://hyperledger.github.io/composer/v0.19/tutorials/developer-tutorial


GENERATING A REST SERVER

To create the REST API run the following command:

$ composer-rest-server


INTEGRATION WITH STERLING B2B INTEGRATOR

Sterling Integrator is a B2B integration platform. It helps organisations transact business documents – such as purchase orders, shipping notices, and invoices – with their suppliers and partners. Sterling B2B Integrator will be used to interact with this blockchain via this REST API.

In this example, POST and GET statements are executed through B2Bi directly through the Hyperledger Composer REST API.
As we will be connecting via REST APIs, we use Sterling Integrators built in HTTP Adapters.

Below are the business processes (BPML), for connecting to a blockchain.

Once the end-to-end process has been defined you can then edit the underlying BPML (XML) to ensure the HTTP adapters point to the correct resources within blockchain.

You must provide

  1. IPAddress–IPAddressofthenoderunningBlockchain(Hyperledger Composer Rest Server)

  2. PortNumber–Portnumberexposedfor

  3. URI–Thiswillchangeperbusinessprocess,basedonwhatyouwishtodo.

I.e. whether you wish to Create/ Read/ Transact:

o Assets
o Participants o Transactions

Create Participant
BP to create a participant P001 on Blockchain from B2Bi. POST /SampleParticipant

{
"$class": "org.example.basic.SampleParticipant", "participantId": "P001",
"firstName": "Mickey",
"lastName": "Mouse"

}

<process name = "0001_hyperledger_demo_add_participant_P001"> <sequence name="Sequence Start">

<operation name="HTTP Client Begin Session Service">
<participant name="HTTPClientBeginSession"/>
<output message="HTTPClientBeginSessionServiceTypeInputMessage">

                <assign to="." from="*"/>

<assign to="RemoteHost">some.remotehost.com</assign> <assign to="HTTPClientAdapter">HTTPClientAdapter</assign> <assign to="RemotePort">3000</assign>

    </output>
    <input message="inmsg">
        <assign to="." from="*"/>
    </input>
</operation>

<!-- hardwire JSON data for REST call
to make the example a bit easier we are passing on a unique ID that would be generated by the DB -->

        <assign
to="JSONCreateString/BOOK/class">org.example.basic.SampleParticipant</assign>

<assign to="JSONCreateString/BOOK/participantId">P001</assign>

<assign to="JSONCreateString/BOOK/firstName">Mickey</assign> <assign to="JSONCreateString/BOOK/lastName">Mouse</assign>

<!-- Use an XSLT transformation to convert process data to JSON -->

<operation name="XSLTService">
   <participant name="XSLTService"></participant>
   <output message="XSLTServiceInputMessage">
      <assign to="input_pd_xpath">/ProcessData/JSONCreateString</assign>
      <assign to="xml_input_from">ProcData</assign>
      <assign to="xml_input_validation">NO</assign>
      <assign to="xslt_name">SampleParticipantXSLT</assign>
      <assign to="." from="*"></assign>
   </output>
   <input message="inmsg">
      <assign to="." from="*"></assign>

</input>

</operation>

<!-- Set content type of the document to application/json -->

<operation name="SetContenType">
<participant name="GetDocumentInfoService"/> <output message="xout">

        <assign to="." from="*"/>
        <assign to="DocumentContentType">application</assign>
        <assign to="DocumentContentSubType">json</assign>
        <assign to="updateMetaDataOnly">true</assign>
    </output>
    <input message="xin">
        <assign to="docInfo" from="*"/>
    </input>
</operation>

<operation name="HTTP POST">
<participant name="HTTPClientPost"/>
<output message="HTTPClientGetServiceTypeInputMessage">

        <assign to="." from="*"/>
        <assign to="RawResponse">false</assign>
        <assign to="ShowResponseCode">false</assign>
        <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleParticipant</assign>
            </output>
            <input message="inmsg">
                <assign to="HTTPClientGetServiceResults1" from="*"/>
            </input>
        </operation>

<operation name="HTTP GET">
<participant name="HTTPClientGet"/>
<output message="HTTPClientGetServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleParticipant</assign>
    </output>
    <input message="inmsg">
        <assign to="." from="*"/>
    </input>
</operation>

<operation name="HTTP Client End Session Service"> <participant name="HTTPClientEndSession"/>

<output message="HTTPClientEndSessionServiceTypeInputMessage"> <assign to="." from="*"/>
<assign to="SessionToken"

from="/ProcessData/SessionToken/text()"/>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>

</input>

        </operation>
        <onFault>

<sequence name="Session close OnFault">
<operation name="HTTP Client End Session Service">

                    <participant name="HTTPClientEndSession"/>
                    <output
message="HTTPClientEndSessionServiceTypeInputMessage">
                        <assign to="." from="*"/>
                        <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                    </output>
                    <input message="inmsg">
                        <assign to="." from="*"/>
                    </input>
                </operation>
            </sequence>

</onFault>

    </sequence>
</process>

Create Asset
BP to create an asset iPhone001 with value of 1000 on the Blockchain from B2Bi

owned by participant P001. POST /SampleAsset

{
"$class": "org.example.basic.SampleAsset", "assetId": "iPhone001",
"owner":

"resource:org.example.basic.SampleParticipant#P001", "value": "1000"

}

 
<process name = "0002_hyperledger_demo_add_asset_A001">
    <sequence name="Sequence Start">

<operation name="HTTP Client Begin Session Service">
<participant name="HTTPClientBeginSession"/>
<output message="HTTPClientBeginSessionServiceTypeInputMessage">

                <assign to="." from="*"/>
        <assign to="RemoteHost">some.remotehost.com</assign>
        <assign to="HTTPClientAdapter">HTTPClientAdapter</assign>
        <assign to="RemotePort">3000</assign>
    </output>
    <input message="inmsg">
        <assign to="." from="*"/>
    </input>
</operation>

<!-- hardwire JSON data for REST call
to make the example a bit easier we are passing on a unique ID that would be generated by the DB -->

        <assign
to="JSONCreateString/BOOK/class">org.example.basic.SampleAsset</assign>

<assign to="JSONCreateString/BOOK/assetId">iPhone001</assign>

<assign to="JSONCreateString/BOOK/owner">resource:org.example.basic.SampleParticipant#P00 1</assign>

<assign to="JSONCreateString/BOOK/value">1000</assign>

<!-- Use an XSLT transformation to convert process data to JSON -->

        <operation name="XSLTService">
           <participant name="XSLTService"></participant>
           <output message="XSLTServiceInputMessage">

<assign to="input_pd_xpath">/ProcessData/JSONCreateString</assign> <assign to="xml_input_from">ProcData</assign>
<assign to="xml_input_validation">NO</assign>
<assign to="xslt_name">SampleAssetXSLT</assign>

              <assign to="." from="*"></assign>
           </output>
           <input message="inmsg">
      <assign to="." from="*"></assign>
   </input>
</operation>

<!-- Set content type of the document to application/json -->

<operation name="SetContenType">
<participant name="GetDocumentInfoService"/> <output message="xout">

        <assign to="." from="*"/>
        <assign to="DocumentContentType">application</assign>
        <assign to="DocumentContentSubType">json</assign>
        <assign to="updateMetaDataOnly">true</assign>
    </output>
    <input message="xin">
        <assign to="docInfo" from="*"/>
    </input>
</operation>

<operation name="HTTP POST">
<participant name="HTTPClientPost"/>
<output message="HTTPClientGetServiceTypeInputMessage">

        <assign to="." from="*"/>
        <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleAsset</assign>
            </output>
            <input message="inmsg">
                <assign to="HTTPClientGetServiceResults1" from="*"/>
            </input>
        </operation>

<operation name="HTTP GET">
<participant name="HTTPClientGet"/>
<output message="HTTPClientGetServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleAsset</assign>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>

<operation name="HTTP Client End Session Service">
<participant name="HTTPClientEndSession"/>
<output message="HTTPClientEndSessionServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>
        <onFault>

<sequence name="Session close OnFault">
<operation name="HTTP Client End Session Service">

                    <participant name="HTTPClientEndSession"/>
                    <output
message="HTTPClientEndSessionServiceTypeInputMessage">
                        <assign to="." from="*"/>
                        <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                    </output>
                    <input message="inmsg">
                        <assign to="." from="*"/>
                    </input>
                </operation>
            </sequence>
        </onFault>
    </sequence>
</process>

Execute a Blockchain Transaction

POST /SampleTransaction

BP to execute a transaction on the Blockchain from B2Bi to reduce the asset value to 800 for participant P001.

{
"$class": "org.example.basic.SampleTransaction", "asset": "iPhone001",
"newValue": "800"

}

<process name = "0003_hyperledger_demo_transaction">
<sequence name="Sequence Start">
    <operation name="HTTP Client Begin Session Service">

<participant name="HTTPClientBeginSession"/>
<output message="HTTPClientBeginSessionServiceTypeInputMessage">

            <assign to="." from="*"/>
            <assign to="RemoteHost">some.remotehost.com</assign>
            <assign to="HTTPClientAdapter">HTTPClientAdapter</assign>
            <assign to="RemotePort">3000</assign>
        </output>
        <input message="inmsg">
            <assign to="." from="*"/>
        </input>
    </operation>

<!-- hardwire JSON data for REST call
to make the example a bit easier we are passing on a unique ID that would be generated by the DB -->

        <assign
to="JSONCreateString/BOOK/class">org.example.basic.SampleTransaction</assign>

<assign to="JSONCreateString/BOOK/asset">iPhone001</assign> <assign to="JSONCreateString/BOOK/newValue">800</assign>

<!-- Use an XSLT transformation to convert process data to JSON -->

<operation name="XSLTService">
   <participant name="XSLTService"></participant>
   <output message="XSLTServiceInputMessage">
      <assign to="input_pd_xpath">/ProcessData/JSONCreateString</assign>
      <assign to="xml_input_from">ProcData</assign>
      <assign to="xml_input_validation">NO</assign>
      <assign to="xslt_name">SampleTransactionXSLT</assign>
      <assign to="." from="*"></assign>
   </output>
   <input message="inmsg">
      <assign to="." from="*"></assign>
   </input>
</operation>

<!-- Set content type of the document to application/json -->

<operation name="SetContenType">
<participant name="GetDocumentInfoService"/> <output message="xout">

        <assign to="." from="*"/>
        <assign to="DocumentContentType">application</assign>
        <assign to="DocumentContentSubType">json</assign>
        <assign to="updateMetaDataOnly">true</assign>
    </output>
    <input message="xin">
        <assign to="docInfo" from="*"/>
            </input>
        </operation>

<operation name="HTTP POST">
<participant name="HTTPClientPost"/>
<output message="HTTPClientGetServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleTransaction</assign>
            </output>
            <input message="inmsg">
                <assign to="HTTPClientGetServiceResults1" from="*"/>
            </input>
        </operation>

<operation name="HTTP GET">
<participant name="HTTPClientGet"/>
<output message="HTTPClientGetServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>

<assign to="SessionToken" from="/ProcessData/SessionToken/text()"/>

                <assign to="URI">/api/SampleTransaction</assign>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>

<operation name="HTTP Client End Session Service">
<participant name="HTTPClientEndSession"/>
<output message="HTTPClientEndSessionServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>
        <onFault>
            <sequence name="Session close OnFault">

<operation name="HTTP Client End Session Service"> <participant name="HTTPClientEndSession"/> <output

message="HTTPClientEndSessionServiceTypeInputMessage">
                        <assign to="." from="*"/>
                        <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                    </output>
                    <input message="inmsg">
                        <assign to="." from="*"/>
                    </input>
</operation>
            </sequence>
        </onFault>
    </sequence>
</process>
 

Read List of Transactions

GET /SampleTransaction
BP to view the list of transactions from the Blockchain.

<process name = "0004_hyperledger_demo_get_list_of_txn ">
    <sequence name="Sequence Start">
        <operation name="HTTP Client Begin Session Service">

<participant name="HTTPClientBeginSession"/>
<output message="HTTPClientBeginSessionServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RemoteHost">some.remotehost.com</assign>
                <assign to="HTTPClientAdapter">HTTPClientAdapter</assign>
                <assign to="RemotePort">3000</assign>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>

<operation name="HTTP GET">
<participant name="HTTPClientGet"/>
<output message="HTTPClientGetServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="RawResponse">false</assign>
                <assign to="ShowResponseCode">false</assign>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                <assign to="URI">/api/SampleTransaction</assign>

</output>

            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>

<operation name="HTTP Client End Session Service">
<participant name="HTTPClientEndSession"/>
<output message="HTTPClientEndSessionServiceTypeInputMessage">

                <assign to="." from="*"/>
                <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
            </output>
            <input message="inmsg">
                <assign to="." from="*"/>
            </input>
        </operation>
        <onFault>

<sequence name="Session close OnFault">
<operation name="HTTP Client End Session Service">

                    <participant name="HTTPClientEndSession"/>

<output message="HTTPClientEndSessionServiceTypeInputMessage">

                        <assign to="." from="*"/>
                        <assign to="SessionToken"
from="/ProcessData/SessionToken/text()"/>
                </output>
                <input message="inmsg">
                    <assign to="." from="*"/>
                </input>
            </operation>
        </sequence>
    </onFault>
</sequence>

</process>

Publish & Subscribe Events - Websocket Listener

Setup a Websocket Listener on B2Bi to subscribe the events from Blockchain network.

Implement a listener service to listen for events through web socket from your Blockhain private network.

For eg.:

BP:

<process name="StartWebSocketListener">
        <sequence name="listenWebSocket">

<operation name="Blockchain Web Socket Listener Service"> <participant name="BlockchainWebSocketListenerService"/> <output message="Xout">

              <assign to="." from="*"></assign>
            </output>
            <input message="Xin">
              <assign to="." from="*"></assign>
            </input>
          </operation>
</sequence>

</process>

Java Implementation to connect to the websocket.

package com.ibm.websocket.client;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
public class WebsocketClientEndpoint {
    Session userSession = null;
    private MessageHandler messageHandler;
    public WebsocketClientEndpoint(URI endpointURI) {
        try {
            WebSocketContainer container =
ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

}

    /**
     * Callback hook for Connection open events.
     *

* @param userSession the userSession which is opened.

     */
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

/**
* Callback hook for Connection close events.
*
* @param userSession the userSession which is getting closed. * @param reason the reason for connection close
*/

    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

/**
* Callback hook for Message Events. This method will be invoked when a

client send a message.
     *

* @param message The text message

     */
    @OnMessage
    public void onMessage(String message) {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);

} }

    /**
     * register message handler
     *
     * @param msgHandler
     */
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;

}

    /**
     * Send a message.
     *
     * @param message
     */
    public void sendMessage(String message) {
        this.userSession.getAsyncRemote().sendText(message);

}

/**
* Message handler.
*
* @author Jiji_Sasidharan */

    public static interface MessageHandler {

public void handleMessage(String message); }

}

Below is the actual service – BlockchainWebSocketListenerService.java

package com.sterlingcommerce.fg.services;
import com.ibm.websocket.client.WebsocketClientEndpoint;
import com.sterlingcommerce.fg.FileGatewayConstants;
import com.sterlingcommerce.fg.exception.FileGatewayException;
import com.sterlingcommerce.fg.util.FileGatewayLogFactory;
import com.sterlingcommerce.fg.xapi.services.Reprocessor;
import com.sterlingcommerce.woodstock.mailbox.MailboxFactory;
import com.sterlingcommerce.woodstock.mailbox.repository.IRepository;
import com.sterlingcommerce.woodstock.services.IService;
import com.sterlingcommerce.woodstock.util.FlatUtil;
import com.sterlingcommerce.woodstock.util.frame.Manager;
import com.sterlingcommerce.woodstock.util.frame.jdbc.Conn;
import com.sterlingcommerce.woodstock.util.frame.jdbc.JDBCService;
import com.sterlingcommerce.woodstock.workflow.WorkFlowContext;
import com.sterlingcommerce.woodstock.workflow.WorkFlowException;
import com.yantra.ycp.core.YCPContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.sterlingcommerce.fg.util.BPLauncher;
import java.net.URI;
import java.sql.*;
import java.util.*;

/** *

 * @author Bipin Chandra

*/
public class BlockchainWebSocketListenerService implements IService {

protected static final Logger LOG = FileGatewayLogFactory.getLogger(); private static final String CLASS_NAME = "StartWebSocketListenerService";

/**
* This method is entered when a Service is invoked during a business * process.
* <P>
*
* @return Updated WorkFlowContext after Service processes
*/

public WorkFlowContext processData(final WorkFlowContext wfc) throws WorkFlowException {

        final String METHOD = ".processData() - ";
        if (LOG.isDebugEnabled())
            LOG.debug(CLASS_NAME + METHOD + "Starting ...");
        try {

// open websocket

final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("ws://some.remotehost.com:3000"));

            // add listener
            clientEndPoint.addMessageHandler(new
WebsocketClientEndpoint.MessageHandler() {

public void handleMessage(String message) { System.out.println("message Bipin:"+message); if (LOG.isDebugEnabled())

LOG.debug(CLASS_NAME + METHOD + "message Bipin before bp

exec: "+message);

BPLauncher bpLauncher = new BPLauncher("00_Blockchain_CustomBP");

                                 try {
                                        bpLauncher.startNow(true);
                                 } catch (FileGatewayException e) {
                           if (LOG.isDebugEnabled())
bpLauncher.startNow:" + e);

LOG.debug(CLASS_NAME + METHOD + "catch execption }

exec:");

} });

if (LOG.isDebugEnabled())
LOG.debug(CLASS_NAME + METHOD + "message Bipin after bp

// send message to websocket

//clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}
");

// wait 5 seconds for messages from websocket Thread.sleep(600000);//10 min

} catch (Exception e) { wfc.setBasicStatus(WorkFlowContext.ERROR); wfc.setWFStatusRpt("Status_Report", wfc.getServiceName() + ":

Something bad" +e ); LOG.error(wfc.getServiceName(), e);

} finally {
if (LOG.isDebugEnabled())

                LOG.debug(CLASS_NAME + METHOD + "Finally block.");
            wfc.setBasicStatusSuccess();

}

        if (LOG.isDebugEnabled())
            LOG.debug(CLASS_NAME + METHOD + "Exiting.");

return wfc; }

}


EXECUTE THE BUSINESS PROCESSES

Once the business process has been configured, saved, and checked into B2Bi, you can execute the business process. Clicking an icon in the “Document” column will show the raw JSON data returned back from the blockchain, and a response code 200 – indicating the connection was successful.

Output from Sterling Integrator – Blockchain transactions, written to file system

Step By Step:
Step 1: Execute the BP to create a participant P001

Following participant can be verified on hyperledger blockchain n/w

Step 2: Execute the BP to create an asset iPhone001 with value of 1000 on the Blockchain from B2Bi owned by participant P001.

Following asset can be verified on hyperledger blockchain n/w

Step 3: Execute the BP to perform a transaction on the Blockchain from B2Bi to reduce the asset iPhone001 value to 800 for participant P001.

Following transaction can be verified on hyperledger blockchain n/w

Step 4: Events gets triggered from Blockchain network based on any action happened. Subscribe these events from Sterling B2B Integrator. Execute a custom BP from B2Bi once certain events are received on B2Bi side.

Execute the StartWebSocketListener to listen for any events happened on blockchain network – event subscription.

As configured in the above implementation – to execute BP – when any event happened on blockchain network:

Same can be seen below once the event happened on blockchain network the event triggers following BP in B2Bi.

Note:

To subscribe these blockchain events from any other system(other than B2Bi), execute following command.

$ wscat -c ws://some.remotehost.com:3000

You will have to install Websocket client – wscat.

USECASES

USE CASE 1

B2Bi Integration with the Blockchain using ‘Blockchain Client Adapter’ (as demonstrated in the demo)

Description: Idea is to have a fully managed ‘Blockchain Client Adapter’ in B2Bi. This will be based on the demo shown above.

This blockchain adapter helps customer to talk to any of their blockchain business network.

  • Creates/modifies resources on customer’s blockchain business network.

  • Triggers any BP(business process) based on any event triggered on their

    blockchain business network.

    USE CASE 2

    Shadow chain in Filegateway to validate the file transferred.

    Description: Idea is to implement non-repudiation on the 'file' transferred. So, that the sender cannot deny sending a particular file and receiver also get to verify if the file is not tampered over the traffic.

Sender, before sending the file, generates the hash of the file and store it on blockchain network.

Receiver, after receiving the file, generates the hash again.

If both the hash matches - this implies that the file has not been modified over the traffic.
Filegateway file upload and many other protocols like AS2, FTP, FTPS and SFTP do not address non-repudiation. Once we have this feature into the product it will be a great security addition.

USE CASE 3

Description: B2Bi plays a major role in integration between external world (partners) and internal departments within an organization through adapters and services.

Blockchain is going to be used not only with external partners but within the organisation among different departments as well - to establish trust.

Said that, an organization is going to be part of multiple blockchain networks (external and internal).

And there could be need to share permission-able information from one blockchain network to another blockchain network.

USE CASE 4

B2B Integration & Blockchain-era EDI system

From a supply chain perspective, much of the hype surrounding blockchain lays within its promise and ability to relieve many of the problems of traditional B2B Integration and EDI.

Electronic Data Interchange (EDI) made transaction processing digital and automated. EDI replaced manual, paper based business documents. It has been the gold standard for integration between businesses and exchange business documents such as purchase orders, invoices, and shipping notices.

However, EDI has been plagued by the ever-growing number of standards and ways of doing business. Document formats such as: EDIFACT, ANSII X12, CSV, and XML, and communication protocols such as: SFTP, Connect:Direct, HTTP, and AS2 – have become a plethora of “standards” which are inconvenient and time consuming for organizations to maintain. It is costly and complex to build systems which can transform data from Company A’s format to Company B’s.

Blockchain however, has the ability to provide a single standard, framework, and database – which will provide one single view of transactions, simplifying:

• Visibility
• Auditability
• Dispute resolution


Pics:




#IBMSterlingB2BIntegratorandIBMSterlingFileGatewayDevelopers
#DataExchange
0 comments
36 views

Permalink