0% found this document useful (0 votes)
5 views

DevDApps

The document serves as a developer's guide for creating decentralized applications (DApps) on the Oracle Blockchain Platform (OBP), highlighting the platform's capabilities and architecture based on Hyperledger Fabric. It emphasizes the benefits of using blockchain technology for secure, efficient, and automated business transactions while providing tools and APIs for developers to quickly build and deploy applications. Additionally, it outlines the transaction flow, endorsement, and commit processes essential for maintaining the integrity and performance of blockchain networks.

Uploaded by

kusumakumarchegg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DevDApps

The document serves as a developer's guide for creating decentralized applications (DApps) on the Oracle Blockchain Platform (OBP), highlighting the platform's capabilities and architecture based on Hyperledger Fabric. It emphasizes the benefits of using blockchain technology for secure, efficient, and automated business transactions while providing tools and APIs for developers to quickly build and deploy applications. Additionally, it outlines the transaction flow, endorsement, and commit processes essential for maintaining the integrity and performance of blockchain networks.

Uploaded by

kusumakumarchegg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Developing DApps on

Oracle Blockchain Platform


A Developer’s Guide

developer.oracle.com
Free SDK Free Cloud Trial

Developing DApps Blockchain’s use of distributed ledger technology,


multi-party consensus, and embedded
This community with representatives from multiple
technology companies and many industries ensures
on Oracle Blockchain cryptography for signing transactions and linking the transparency, longevity, and interoperability

Platform blocks, enables a single source of truth among


multiple participants with data integrity, high
necessary for growing blockchain adoption in
enterprise and government deployments around
availability and durability of data, resilience against the world.

M
any organizations are adopting blockchain
single point of failure and malicious attacks, and
technology to increase the speed of
process integrity. These attributes can be leveraged The benefits of blockchain are faster, more
business-to-business transactions and share
to optimize an ecosystem of participants via automated processes, which is a distinct benefit
data in a secure and tamper-proof system.
faster transactions with near real-time settlement, to developers. Instead of building the necessary
Blockchain, the ingenious technology behind
lower costs by avoiding intermediaries, and infrastructure on premises, get an accelerated
cryptocurrencies, has very broad applications
greater automation of verification, settlement, and start with Oracle’s comprehensive, enterprise-
in areas such as ERP, supply chain, healthcare,
downstream event triggers. grade Blockchain-as-a-Service offering, that adds
and financial services. The concept at the core of
a number of unique advantages to the open
blockchain is a distributed ledger consisting of a
In order to ensure blockchain can deliver these source foundation. With the Oracle Blockchain
current set of facts maintained in a world state
capabilities and support multiple participating Platform providing a complete, pre-assembled
key-value database and transaction history. This is
organizations relying upon it, the underlying blockchain platform with a comprehensive set of
maintained as a list of blocks, with the database
framework must have highly credible architecture. tools and APIs, developers are able to quickly get
changes and transaction history extended by
The Oracle Blockchain Platform (OBP) builds on a blockchain network up and running.
consensus via peer-to-peer protocols, and linked
Linux Foundation’s Hyperledger Fabric open-
and secured with cryptographic hashes.
source code, a global, cross-industry collaborative For development and testing, a free downloadable
effort to bring blockchain technology for business OBP SDK is also available with a time-limited
into the mainstream. license.

2 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

This allows developers to focus resources on


Contents Managing your Blockchain Network 19
19
building and integrating the application and its Dashboard Tab
Network Tab 20
underlying smart contract code specific to their 04
What is Oracle Blockchain Platform? 21
Nodes Tab
blockchain network, rather than spending a lot Understanding Blockchain Networks, Nodes,
Channels Tab 21
of time and effort on building and hardening the and other Components 05
Chaincodes Tab 22
infrastructure of the blockchain platform. The Transaction Flow 07 Developer Tools Tab 23
hardened, industrialized platform, its dynamic Endorsement 07
configuration and monitoring tools, and a Commit 07 Developing and Deploying Chaincodes 25
Query 08 Chaincode Development - Basics 25
powerful set of integrated enterprise features
Compiling Chaincode 29
helps to reduce the time to develop and integrate Provisioning a Blockchain Network 09 Installing & Instantiating Chaincode 29
applications, resulting in higher productivity and Oracle Blockchain Platform Console 10 Implementing Custom Chaincode Functions 30
significantly reduced operating costs. Developers Create a Blockchain Network (Founder) 10 Invoking Chaincodes via REST API 33
Adding Participating Organizations 11 Initializing the Ledger 35
can deliver faster results for rapid experimentation
Export Participant’s PKI Certificates 12 Invoking Operations 36
and leverage production-strength platform for
Add Participant Organization to Founder 13
mission-critical deployment of a trusted blockchain
Creating Channels 15 Advanced Topics 39
network that provides increased visibility, faster ABAC – Attribute Based Access Control 39
Developer Samples – Guided Walkthrough 17 Testing Chaincode Using Mockshim 41
settlement, and decreased risk of fraud for
Installing Samples 18 Logging 42
business-to-business transactions.
Instantiating Samples 18 Rich Queries in Chaincode 43
Invoking Samples 19 Events – Publish & Subscribe 45
Using Rich History Database for Analytics/BI 49

Summary 54

Reference and Resources 54

3 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

What is Oracle Blockchain can be very resource (compute,


memory, storage and network) intensive,
Smart Contracts (Chaincode) layer consists of
chaincode programs that contain the business
Blockchain Platform? so performance and scalability are critical logic for updating the ledger, querying data,
characteristics of a successful service. Blockchain and/or publishing events. Chaincodes can read

A
production-ready permissioned blockchain system can be visualized in three layers as the ledger data to verify conditions as part of
network consists of validating nodes, illustrated in the diagram below: any proposed updates or deletes and trigger
ordering service, and membership services for custom events. Note that updates and deletes are
enrolling organizations, supported by a broad proposed (or simulated) and are not final until
set of dependencies, including compute, storage, transactions are committed following consensus
event management, and identity management. and validation protocols.
It needs to provide the interfaces to maintain
ledgers, create channels, add participating New or Existing Applications, which can
organizations and nodes, invoke and monitor
Register/enroll organizations as members
smart contracts, browse the ledge, and have the
Submit transactions (invoke smart contracts) to
APIs necessary to build and run your applications.
update or query data

Oracle Blockchain Platform (OBP) provides Consume events emitted by the chaincodes or
by the blockchain platform
this comprehensive set of nodes and services Blockchain Platform includes
along with all the required dependencies and A network of validating nodes (peers)
APIs, architected to support highly scalable Distributed ledger (linked blocks, world state
and history DB)
distributed transaction processing required by
Ordering service (for creating blocks)
enterprise applications.
Membership services (for managing
organizations in a permissioned blockchain)

4 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Oracle Blockchain Platform (OBP) provides the Note that some Oracle ISV partners provide Understanding Blockchain Networks,
following capabilities for the lowest layer in complete solutions based on OBP, which include Nodes, and other Components
this diagram: smart contracts, new application components,
and integrations with Oracle and 3rd party The terms defined below are specific to
An ability to spin up one or more
applications (see some of their solutions on Hyperledger Fabric blockchain architecture on which
pre-assembled instances of a blockchain
Oracle Cloud Marketplace.) Oracle Blockchain Platform is based.
platform cloud service in Oracle Cloud
Infrastructure (OCI)
As a developer, once you have registered an Blockchain Network: Collection of member
A private cloud service deployable as
account on Oracle Cloud (you can start at organizations that can read and write to the
software appliance outside of OCI
cloud.oracle.com/blockchain), you can setup a blockchain ledger. Organizations can be
An ability to link instances into hybrid new instance of OBP and start developing your founders, which run the ordering service,
blockchain networks, spanning Oracle and chaincode and integrate applications within or participants, which join their peer nodes to
non-Oracle Hyperledger Fabric nodes minutes. You can easily integrate new or existing founder’s ordering service.
An administrative console and set of applications using the OBP REST API or broad

tools for administration and monitoring of portfolio of enterprise integration adapters Nodes: Distinct operating entities on the network.
OBP instances from Oracle Integration Cloud (OIC.) Enterprise Nodes include the orderer(s), certificate authority,
developers can securely extend existing business REST proxy, and peers.
Tools to deploy and manage smart contracts
processes with real-time data sharing across
APIs and SDKs for applications to interact existing Oracle ERP Cloud, SCM Cloud, HCM Cloud, Orderers: Node for creating new blocks from the
with chaincode and consume events CX Cloud, Netsuite Suite Cloud Platform, Flexcube transactions sent by the clients. Orderer can operate
core banking, and custom applications on premise by itself (Solo) or as part of an ordering cluster,
The creation of smart contracts and integration
or in a cloud. where they are also referred to as ordering service
with the applications that invoke them is left to
nodes or OSNs.
customers or system integrators.

5 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Peers: Participation validates notes of member Chaincodes are installed on and specific to a The pre-assembled nature of OBP reduces the
organizations. Peers are responsible for channel and its peers. The same chaincode can burden of building an open source environment
maintaining a copy of the ledger, running be instantiated and used on multiple channels, from scratch and provides a blockchain platform
smart contracts, and committing transactions. however, while executing a transaction request it you can provision with a simple request and a few
Organizations can have one or more peers on operates in the context of the specific channel and clicks in minutes using QuickStart templates sized
the network. Two peers per member is a common its ledger. for development and production needs.
configuration for operating performance
and availability. Certificate Authority: a node providing PKI The integration of Oracle Identity Cloud Service
functionality in the blockchain. CA is responsible in the OBP CS is a unique differentiator, which
Channel: A subnet within a blockchain network for registering member organizations, issuing provides strong identity management with
with an isolated ledger and an authorized group their enrollment and TLS certificates, and handling identity federation for authentication and adding
of member organizations represented by their certificate revocation and renewal. new members, protects secure access with
peer nodes. Peers executing a transaction behavioral authentication and single sign-on. For
targeting a specific channel can only access OBP is pre-assembled with all these components an overview of OBP Cloud Service please review
the ledger on that channel, but a single peer and their underlying dependencies required for the “Getting Started with Oracle Blockchain Cloud
can belong to multiple channels and execute out-of-the-box operation: event management Service” video.
independent transactions on each of them. (Kafka), identity management (IDCS), object store
(OSS), two manager VMs in high availability
Chaincode: a synonym for smart contract, the configuration for hosting all control nodes, agents
specific programming module that contains providing embedded backup and recovery and
business logic invoked on the channel to read and telemetry for cloud monitoring and management
write application data from/to the ledger, apply any operations, and a separate VM to isolate chaincode
validation logic, and trigger application events. execution containers running customer code.

6 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Transaction Flow Endorsement


Endorsement is the process of executing
Commit
Commit is the process of validating and writing
chaincode and returning results to a client. The transactions to the ledger. During this step,

O
racle leverages Hyperledger Fabric, a
client request for particular chaincode invocation the client sends the response and all the peer
Linux Foundation open source project,
is sent to a number of peers (as defined by signatures to the orderers. Upon validating the
as the foundation of its blockchain platform. The
chaincodes endorsement policy) on a specific signatures, ordering service (a cluster of orderers)
transaction flow is defined by Fabric protocols
channel. The response includes the return code sequences transactions from all the clients and
between peers, orderers, fabric-ca, and clients as
and Read-Write set (RWset), which includes all group them in blocks, which are then delivered
detailed on page 8.
keys read and updated during the execution, to the peers on a relevant channel. Each peer
signed by the peer’s private key, with the signature then validates each transaction in the block by
Fabric transactions fall into two categories:
as transaction ID that provides proof of execution. checking for sufficient endorsements and verifying
invocations (usually updates) and queries. Both
Peers do not write the results into the ledger that the relevant data in the ledger have not
invoke smart contracts and request an endorsement
in this phase. If chaincode endorsement policy been changed by another transaction since the
– a digitally signed result of the execution. In
specifies multiple endorsements, the execution current one was executed in the endorsement
addition, invocations add a further stage – a
is performed on the multiple peers, and the client stage (i.e., if at endorsement time Alice has a
commit, where the transaction is included in a block
receives multiple responses. It is the client’s balance of $100 and transaction is to transfer
and, after verification, appended to the ledger by
responsible for comparing the results to ensure $70 to Bob, we need to know that there haven’t
all peers on the channel specified at the invocation
they match, and checking that appropriate number been intervening transactions that might have
time. Note that commit stage is at client’s
of responses has been received consistent with the reduced Alice’s balance before we commit the $70
discretion, and can be optionally added even for
endorsement policy. transfer.) Once these checks are complete, each
queries or failed invocations if it’s important to
peer writes the valid transactions to the world state
record them in the ledger.
database, updates the history database, and returns
transaction commit event.

7 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Note that the block is added to the chain with In summary, the end-to-end transaction flow as 6. Orderers validate the signatures and
transaction flag indicating commit status for each depicted in the diagram on page 9: sequence transactions into blocks, sending the
transaction. If verification step has failed, the new blocks to the peers for the specific channel.
transaction will be marked as failed in the block and 1. The client applications register and enroll 7. Committers in each peer validate the
failure notification returned to the client, which can with fabric-ca to obtain a certificate. transaction signatures and check if there’s
re-submit it if appropriate. 2. Client sends a signed transaction proposal a sufficient number of signatures to meet
request to endorsing peer nodes (one or more endorsement policy. They also verify that the
Query as specified in the endorsement policy). values of the keys read at endorsement time
Query is the process of reading the current ledger haven’t changed since endorsement time.
3. Endorsing peers verify the signature
state through chaincode query functions and And in OBCS they also verify that rich query
and execute the specified chaincode on the
returning an endorsed result payload. Queries do results haven’t changed. If everything’s valid,
specified channel.
not typically change the ledger state, so are not the transaction is committed, i.e., updated key
normally sent for commitment. However, client 4. Chaincode responses (RWSet) are signed
values are stored into the world state database,
applications can submit queries to be committed as by the peers and these endorsements are
the commit flag for the transaction is set in the
an auditable proof that a peer had knowledge of the returned to the client.
block added to the chain, and history database
ledger state at a specific point in time. 5. If responses are valid, results from the is updated with appropriate pointers. Note that
peers match, and sufficient number has been blocks are appended to the chain irrespective
received as per the chaincode endorsement of whether transactions are valid or not – a
policy requirements, the client assembles the commit flag for each transaction is used to
endorsements into a commit package and indicate if it has committed or failed.
sends it to ordering service to be included in
a block.

8 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

8. The peer emits transaction commit and new


block added events, as well as any custom
Gossip messages will identify available peers,
detect ones that are offline, update blocks to peers
Provisioning a
events declared in the chaincode logic and that are out of sync, and quickly bring new peers’ Blockchain Network
these are delivered to any subscribing client. ledger copy up to the latest state.

T
he key properties of a permissioned
This architecture imposes significant responsibilities blockchain implementation are that all
on a client to orchestrate the transaction flow, and members of the network see consistent data,
handle async events using an SDK. In order to that all records are immutable, and that only
simplify working with the blockchain, OBP provides invited members can read and write to the
a REST proxy (a.k.a. Gateway) that handles the ledger. Setting up a new blockchain instance with
orchestration and exposes RESTful endpoints a “Create a new Network” checkbox enabled
for applications to trigger transactions, query the identifies you as the founding member of the
ledger, and subscribe to events. See Invoking network. Other participants set up instances
Chaincodes via REST API below for more details. with this field unchecked and then join your
network by sharing their PKI certificates with the
In addition to the REST API for interacting with founder. The founder’s administrator can extend
In addition to the main transaction flow protocol,
transactions and events, OBCS also provides the network by adding the shared certificates to
the Fabric blockchain peers use a messaging
an extensive REST API for configuration and register the organizations as permitted members
protocol called gossip data dissemination protocol
monitoring of the blockchain network. These and enable them to participate in the designated
to continuously send messages to each other and
administrative functions can be integrated into channels. Other participants can also import
keep the ledger copies current.
any DevOps toolset, and enable deployment of member certificates when adding them in Create
chaincode, adding nodes, creating channels, adding Channel dialogue.
organizations, querying and setting configuration
attributes, starting/stopping components and many
other tasks.
9 Developing DApps on Oracle Blockchain Platform
Free SDK Free Cloud Trial

This eBook uses an example of an ecosystem Here we guide you through a few basic steps to set Select one of the three quick start templates
that includes a car manufacturer and a group of up the network and run included samples. by clicking on the Create button. The difference
car dealers to illustrate how a blockchain network between Developer and Enterprise templates
might be setup and blockchain application created Each OBP instance in your network has its own are detailed in the online documentation and
for this ecosystem. console that their respective admins can use summarized below:
to manage their organization and monitor the Enterprise templates include HA configurations
Oracle Blockchain Platform Console blockchain networks that they are included in. for production where all components are
User’s role and their instances function in the
The Oracle Blockchain Platform console helps you replicated for resiliency
network (founder or participant) determines
monitor the blockchain network and perform day to Enterprise templates support zero-downtime
the tasks you can do in your console. For
day administrative tasks. managed patching/upgrades
example, if you are the Founder, you can edit
the configuration of the orders used by the Developer template has a max of 7 peer nodes
After you provision your OBP instance, all of the
participants in the network. per instance while Enterprise templates have a
components and capabilities necessary to begin
max of 14 peer nodes per instance
work on your blockchain network are available in
the console Web UI or through the extensive REST Create a Blockchain Network (Founder)
The Enterprise X1 and X4 templates differ only
API. You can use the console to perform tasks such Developers can start creating the instance by
in the number of cores allocated to VMs. While
as managing nodes, configuring network channels selecting one of the network quick start templates.
throughput depends on many factors, generally
and policies, adding organizations and deploying Developers can click on the “Quickstart” button to
guidance is to use X1 template if you expect your
chaincodes. You can also monitor and troubleshoot see the templates.
transaction rates to be under 10K/hr (with payload
the network, view node status, view ledger blocks,
sizes around a few hundred KB), otherwise choose
and find and view log files. Detailed walkthrough
X4 template. As the result of the HA and capacity
of the Console tabs and capabilities is provided in
differences, the minimum charges for each
Managing your Blockchain Network chapter.
template are different.

10 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Click Next button in the top right corner to proceed


to the confirmations screen and if all the details are
correct, click Create button to submit the request.

See chapter Managing your Blockchain Network


below for a detailed walkthrough of the Console

Developers can also select Custom option to create tabs and capabilities.

their own instance configuration using the Create


The time to create an instance is typically under 10 Adding Participating Organizations
Instance dialogue shown below.
minutes and you will receive a confirmation email
A blockchain is more effective with multiple
once it’s been created. You can also return back
participating organizations. If you create
to the Blockchain Cloud Services dashboard and
additional instances, the founding member has the
monitor the status there.
authority to add their organizations to the network.
Provisioning is similar to the initial setup, with one
After the instance has been created, click on its
difference – the participating organization doesn’t
menu icon on the right of the row and select
need its own ordering service. If the instance
“Blockchain Console” to bring up the Admin UI for
you are creating is for an organization that will
your new blockchain instance.
join an existing blockchain network, do not check
the “Create a new Network” checkbox on the
provisioning screen.

11 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Export Participant’s PKI Certificates


Similarly, click Next, verify your inputs, and then Before the Founder or other members can add
a new organization, the new member needs to Exporting of the certificates can be done
click Create.
export its PKI certificate as a JSON file. The automatically following the participant setup

console of each non-founding member loads a wizard or by exporting the certificate manually.

simple wizard to assist with joining the network


on the Dashboard tab, which is the first view The developer can export the certificate

when you open the Blockchain Console. Once the automatically following the sequence in the

instance has completed the tasks in the wizard, participant setup wizard.

the Dashboard view changes to a normal set of


Upon return to the Blockchain Cloud Service health and traffic gauges. The wizard is shown in
dashboard you will see the instances with status the following screenshot.
“Creating service.” You can also click on the Activity
tab above to monitor these requests which should
complete in about 10 minutes and generate an
email notification.

12 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

The developer can also manually export the In the Founder console go to the Network tab and Multiple organizations can be added in one step
certificate from the Network tab’s view using click Add Organizations button. In the wizard click using the + sign icon to add additional rows for
the Actions menu pulldown on the far right of Upload Organization Certificates control and select importing multiple certificates.
the organization’s row as shown in thefollowing the JSON file exported in the Participant’s wizard.
diagram. Participants peer(s) can communicate with the
network by connecting to the ordering service
provided by the Founder. To obtain the orderer
settings, after importing participant’s certificate
in to the founder network, click Export Orderer
Settings button to save Founder’s ordering service
information in a JSON file. This will be imported
later by the participating instance to complete the
process of joining the network.

After you click Finish button, the participant


Add Participant Organization organization is added to the Founder’s network
to Founder and you can see it listed in the Network table.
After the certificate of the participant organization
has been exported, Founder can add participant
organization by importing the certificate and
validating the connection using Add Organization
wizard on the Network tab of the Founder’s console.

13 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

You can also switch from the table view to topology Click on the Upload control and select the saved In the Network tab of the participant’s Console you
view by clicking on the topology icon ( ). JSON file with the ordering service information, can now see the entries for the Founder and your
then click Import button. Participant instance.

By the way, if you have to export Founder’s


Now return to the participant’s console and go to
After importing the ordering service information, ordering service information again in the future, it
step 3 in the wizard to import the ordering service
click on step 4 in the wizard to complete the is also available from the additional actions menu
information you’ve exported from the Founder.
process and exit from the wizard to a regular of the Founder in the Network tab.
dashboard view.

14 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Creating Channels You could have a completely open network with Like the other setup activities across the
all organizations and their peers belonging to one organizations, creating channels is a two-
The next step is connecting the peers on the
channel, or use a number of channels between step operation. First you authorize a member
channels. Channels is a sub network of the main
groups of participants to enable the appropriate mix organization to a channel and then each
blockchain network with isolated ledger and
of shared and confidential actions. For example, organization must explicitly join its peers. You can
authorized members. Once authorized to join a
you could keep a vehicle sales pricing information select the authorized members when creating a
channel, a member organization can add one or
on a private channel confidential to the transaction new channel using checkboxes in the Create a
more of its peer nodes to the channel. Peers can
participants, while keeping vehicle inventory status New Channel wizard (as shown above), or add a
participate in one or more channels, and for each
on a channel shared by all participating dealers. new members to an existing channel using Edit
channel have either read-only or read/write access
Channel Organizations option from the channel’s
to the ledger. Peers with read-only access can not
additional actions menu on the Channels tab as
run smart contracts for that channel, but do get the
shown below.
blocks and commit transactions in their copy of
the channel’s ledger. They can publish events and
respond to block queries from Fabric client SDKs.

Note that a channel named “default” is


created at provisioning time and all peers are
automatically joined to that channel. You can
continue to use the default channel or create
new ones for certain transactions, chaincodes,
and member organizations.

15 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Once the organization has been added to a channel, Import the remote peer to the Founder’s
the second step is to join its peers to that channel, An earlier practice of bilateral channels for configuration:
and this must be done in that organization’s console each pair of participants is not considered

using Join Peers to Channel option from the very scalable and is best avoided. Note that

channel’s additional tasks menu on the Channel tab. since OBP 19.1.3 (based on Hyperledger
Fabric 1.3) a new capability is available for
private collections to maintain fine-grained
confidentiality within a channel, where
multiple collections of organizations can
On the Nodes tab you can see remote peer nodes in
be defined within a channel and used for
the table below.
selectively sharing transaction data.

You can import and export information about


other participant’s peer nodes using
Export/Import button on the Nodes menu.
In our sample configuration, the founder’s two
Export the remote peer nodes configuration from
peers are connected with participants (remote)
the participant’s instance and then import in to
peers on a channel.
the Founder’s configuration:

16 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

You can also see them associated with specific


channels when you use the topology icon to switch
Developer Samples— to streamline its supply chain activities. Blockchain
provides a distributed inventory ledger of vehicles
to topology view. The fully provisioned blockchain Guided Walkthrough and vehicle parts to enable visibility and transfer of
network looks like this: vehicles and parts across this network. Developers

O
racle Blockchain Platform (OBP) includes can install, instantiate and invoke these samples
some chaincode samples to help you learn from the Developer Tools tab under Samples.
how to create, deploy, and invoke chaincode.

OBP console Samples page provides access to


these samples to help you quickly get familiar
with OBP and includes links to download
complete chaincode and configuration artifacts
for these samples. Two of the samples used in
this eBook are:

1. Balance Transfer – A simple chaincode Note the two areas below the samples: they
representing two parties with account provide an output display based on what
balances and operations to query the balances chaincode returns (e.g., Success, or actual
and transfer funds between parties. return values for queries), and a transaction log
2. Car Dealer Sample – Chaincode to manage with detailed transaction flow steps and
the production, transfer, and querying of related messages.
vehicle parts; the vehicles assembled from
these parts; and transfer of the vehicles. In this
sample, a large automaker and its dealers and
buyers have created a blockchain network

17 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

To explore the samples, follow the Install, Instantiating Samples the ledger with initial data. Note that the
Instantiate, and Invoke steps for each sample. For instantiation process involves compiling the
Next step is to click Instantiate button. This multi–
more detailed explanation of the first two steps, chaincode, creating a new execution container,
step process involves building (compiling) the
see Developing and Deploying Chaincodes chapter loading the binary, and executing the chaincodes
chaincode, binding it to a channel, starting new
below. Developers can also download the samples Init() function – this can take a couple minutes, so
chaincode execution containers initialized with
for learning chaincode programming. you may not see the Instantiated count updated
the compiled chaincode and linked to the peer
immediately. It is safe to exit the wizard after
nodes of an organization, and finally invoking the
Installing Samples this step and refresh the Samples page later to
chaincode’s Init() function to initialize any ledger
Click Install button and the chaincode will be copied see if the chaincode instantiation count has been
values (this could be a null function if developer
to the peer nodes you specify. In the wizard you can updated. You can also check it under Chaincodes
so chooses.) This step also automates the process
select the peers to install it on. tab or under Channels tab.
of creating a REST end point for this chaincode
in the REST proxy. In the wizard you can select
the channel to use, input parameters for the
ledger initialization (optional depending on the
chaincode), and rest proxy to use for the REST
end point.

When instantiating Balance Transfer sample, the


chaincode expects to initialize the ledger with
initial account balances, so you need to specify the
input values for A and B accounts. However, in the
Car Dealer sample, the ledger is not initialized and
so no input fields are provided. Instead, the first
action selected in the Invoke Chaincode wizard
must be “Produce vehicle part”, which populates
18 Developing DApps on Oracle Blockchain Platform
Free SDK Free Cloud Trial

Invoking Samples In the Car Dealer sample, the ledger maintains


the inventory of vehicle parts and vehicle
Managing your
After chaincode has been instantiated, we are ready
to execute the chaincode on the network peers of
assemblies. The chaincode provides actions to Blockchain Network
O
add parts or vehicles to the inventory, transfer
an organization. When you get to the Invoke step, racle’s blockchain console provides all
these to other owners, assemble parts into
the wizard offers a selection of actions to choose of the tools necessary for you and the
vehicles, and query the ownership or transaction
for that specific chaincode and input fields for any other member organizations to monitor and
history of parts and vehicles.
parameters they require. manage blockchain network participation. Each
organization will have their own console UI
In the Balance Transfer sample, the ledger where they can monitor network health, add
maintains values for two accounts denoted A and organizations (if authorized), view node status,
B, and the chaincode provides actions to transfer examine channels and ledger activity, and
funds between them and query the balance of manage chaincodes.
each account.
Dashboard Tab
The Dashboard tab provides a summary of the
network health and transaction metrics, with a
banner summarizing the number of operating
After running these transactions, let’s review the
components, such as peers, channels, and
rest of the Console to understand the information
chaincodes. A health monitor displays the
it provides about the blockchain network and the
number and percentage of running nodes, while
latest transactions.
the transaction charts show the most used
channels and peers during the selected time
frame. Note that Peers charts can be switched to
show endorsement or commit transaction counts.

19 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

After the sample transactions have been executed, 2. Channel Activity: Network Tab
the transaction metrics on the default channel and
Number of blocks that have been created. The network tab lists all of the organizations
on some of the peers should’ve increased to reflect
Number of transactions that have been currently participating in your blockchain
the most recent transactions.
executed and number of blocks created. Note network. Network views are available in tabular

that system transactions, e.g., configuration ( ) or graphical topology ( ) formats and

changes, chaincode deployment or update will provide additional details on each organization’s

increase the number of blocks, but will not role. You can also use Add Organizations button

show up in user transactions. In addition, a on this tab to launch a wizard used to add and

block can have multiple transactions based on remove organizations from your network.

ordering service configuration settings.

Graphic depiction of the most active channels.

3. Peer Activity:
Information Provided in the Dashboard: Number of endorsement and commits
1. Health of the Network: completed by the network’s peer nodes.

Percentage and number of running and Graphic depiction of the most active peer
stopped nodes (any stopped nodes can be nodes with success and failure metrics, and a
started from Nodes tab.) toggle between Endorsements and Commits.

Partition Utilization showing CPU, Memory,


and Disk used in each of the two OBP manager
VMs. You can toggle the view between the
partitions by clicking 1 and 2 buttons.

20 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Nodes Tab Clicking on the node name itself brings up a node- Channels Tab
specific set of views, including health gauges and
The Nodes tab has a summary banner displaying The Channels tab provides a view of each channel,
Logs view. You can check peer node logs by going
counts of each node type, including your peers, which is a blockchain subnet, including its creator
to Nodes tab, double clicking on a peer node (e.g.,
orderers, certificate authorities, REST proxies, organization, the number of peers and instantiated
peer0) and selecting Logs from the nav bar on the
and remote peers. This tab also lists details for chaincodes. Note that only the channels you
left. In the Logs select Peer or Chaincode logs to
each node, including the full name, nod type, created or have been authorized to join will be
view and then click Current Log button to see the
and current status. You can use the Actions menu visible in your instance. If you don’t see a channel
entries related to the sample transactions you’ve
( ) on the right-hand side of each node’s row you expect to see listed, check in its creator’s
just executed. The logs are rotated (snapped and
to start, stop, and restart nodes, join a node to console (Edit Channel Organization on the Actions
zipped) at midnight UTC daily, and by setting the
a channel, or edit its configuration. Add Node menu in the Channels tab) if your organization has
time window you can view and download the logs
button enables you to create additional Peer been authorized as indicated by the checkbox.
for previous days.
nodes, and Export/Import Peers button provides
access to wizards used to export and import peer You use this tab to add new channels and upgrade
node information between instances. chaincodes on a channel. This tab also enables
you to drill down on the channel to view detailed
ledger activity for each channel.

21 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Drill down on the default channel to use ledger Chaincodes Tab For detailed chaincode execution logs, drill down
browser view to explore the added blocks. on v0 for obcs-cardealer chaincode, then click on
The Chaincodes tab lists the chaincodes installed
Highlighting a block will show its transactions Logs link for any of the listed peers, and on Logs
on your network and their versions. You can
below, and expanding the triangle icon to the left of view click the Current Log button or one of the
use this tab to determine which peers and
a transaction will show its details. rotated archived logs and scroll down to see the
channels have chaincodes installed and to deploy
entries related to most recent transactions.
new chaincodes. The Install chaincode button
provides access to two wizards: Quick Deploy and
Advanced. The former is a single dialogue wizard
that handles chaincode installation, instantiation
(building and binding to a channel), and creation
of a REST end point through the REST
proxy—all with very few inputs from the user.
The Advanced wizard takes you through a
The drill down page also provides access to view
three- step dialogue for these operations,
the other information related to this channel:
providing an opportunity to specify detailed
instantiated chaincodes, peer nodes
settings for the peers to install on and define
and organizations that have been authorized on
chaincode’s endorsement policy, transient map,
this channel.
and private collections as well as to choose the
REST proxy to use to expose this chaincode.

22 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Developer Tools Tab Samples Instantiate Sample Chaincode


This page has options to install, instantiate & test Select the channel to instantiate the chaincode,
The developer tools are used to learn how to
the sample chaincode. then Select the REST proxy server to enable & test
develop chaincode, develop applications on Oracle
the instantiated chaincode. Enabling instantiated
Blockchain Cloud Service. This tab also provides
chaincode on the rest proxy will assist the
samples to install, instantiate & test the chaincode
application developer with the API to invoke.
samples Oracle Blockchain Cloud Service Console.

Chaincode Development
This includes chaincode samples written in Go and
Node.js to help you learn how to implement and
manage your network’s chaincodes.
Install Sample Chaincode
Select the sample that you want to install on the
peer(s) of the organization. You can install the
chaincode on one or more peers. Invoke and Test Sample Chaincode
Invoke and pass the default payload defined by
click on the invoke button. Transaction Results
are returned with values, and the API details field
displays the detailed log of all blockchain processes
performed from invoking the transaction.

23 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Application Development Once downloaded, client SDKs will need


connection profile info to interact with the
In addition to the REST APIs provided by OBP,
current OBP instance, and certificates to validate
applications can use a software development kit (SDK)
signatures of fabric-ca, peers, and orderers. To
to access the APIs that permit queries and updates
simplify the configuration, OBP provides a pre-
to the ledger. You can install and use the Hyperledger
Developers can go to the channels tab and click on assembled developer package with connection
Fabric SDKs to develop applications connecting
the ledger to view the transaction invoked. information you can download from the
to OBP and invoking its chaincodes. This includes
Console’s Developer Tools tab under Application
development SDKs to build client applications in
Development page. This includes all the
Go (preview), Java, or Node.js, which you can
blockchain connection information and relevant
download from Hyperledger Fabric site or from the
certificates as shown below.
OBCS Console’s Developer Tools tab under Application
Development page. The SDKs on this page are the
same as those provided by Hyperledger.
Note: the SDKs provided with Fabric require
minor adaptation to their underlying network
libraries in order to work with the load balancer
infrastructure in Oracle Cloud Infrastructure.
Follow documentation to download the scripts
to automate these adaptations or to perform
them manually.

24 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Developing and Chaincode Development - Basics The role of the application chaincode is to evaluate
the input parameters and current ledger values or
Deploying Chaincodes Chaincode programs written in Go, Node.js, or
Java use the basic Hyperledger Fabric
historical data and produce output results, which
are captured and signed by the peer as RWSet that
stub interface functions available in OBP to create,

O
BP supports Smart Contracts using is returned to the client.
read, update, and delete records in the ledger.
application chaincodes, which are the
Note that this is not the same as adding blocks.
specific programming modules that a peer can Only after the client examines the results and
Existing blocks are unchangeable and new blocks
invoke on transaction request. The chaincode sends them to the ordering service, then orderers
are generated by the ordering service and are
defines the assets and business logic for the validate and include transaction in a block sent
appended by the peers. Each block contains new
desired transactions. Chaincodes are deployed in to the peers, and peers validate and commit the
transactions, including their results, endorsement
two steps. First they must be installed by each transaction will the output results be committed
signatures, timestamps, and other metadata.
organization on one or more of its peers, which in the ledger. At commit time the updated values
copies the chaincode package with the source code are written to the world state DB, and commit flag
The ledger changes performed through the
to the specified peers. Then they must be is set for the transaction in the block that’s been
stub interface are captured by a peer into the
instantiated, which is a Hyperledger Fabric process appended to the chain, which together with other
transaction Read-Write Set (RWSet) and are
that builds the chaincode from the source (which blocks provides the transaction history log.
considered simulated until transaction commits.
was copied to the peer during the install step),
Before the commit, there’s no finality, and no
binds it to a channel, starts a chaincode execution
other peer will see these changes in their copy of
container for this chaincode and initializes by
the ledger.
calling its Init() method.

25 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

OBP chaincode can be written in Go, node.js, and, stub *shim.ChaincodeStubInterface provides Typical chaincode operates on the ledger records
Java. For the examples below we use Go. The functions to access state and transaction history that represent some sort of “asset”, for example,
chaincode modules are required to implement two data via calls to peer as well retrieve invocation a document and its related metadata, electronic
interface functions that can be invoked by a peer parameters, e.g.: record, like an invoice or purchase order, or a
node: digital representation of some physical assets,
function, args := stub.
like cars, buildings, art works, etc. The business
GetFunctionAndParameters()
Init(stub ChaincodeStubInterface) logic in the chaincode will generally implement
Then using function you can dispatch the
pb.Response CRUD (Create, Read, Update, Delete) functions
execution to a specific functional routine:
This is used to set up any initial state on the assets, and in the process examine certain
information in the ledger (e.g., starting // Handle different functions conditions and optionally trigger events.
account balance, starting inventory, etc.) – if function == “initLedgerA” { // set
called at instantiate and upgrade time, but it initial state of ledger
can be a null function if the chaincode doesn’t return t.initLedgerA(stub, args)
require an initial state. } else if function == “initLedgerB” { //
set initial state of ledger
Invoke(stub ChaincodeStubInterface) return t.initLedgerB(stub, args)
pb.Response } else if function == “initVehiclePart”
This is used to extract chaincode method { //create a new vehiclePart
being invoked and arguments passed to it, return t.initVehiclePart(stub, args)
and then dispatch to the appropriate function } else if function ==
in the chaincode. “transferVehiclePart” { //change owner
of a specific vehicle part
return t.transferVehiclePart(stub,
args)
}
26 Developing DApps on Oracle Blockchain Platform
Free SDK Free Cloud Trial

To perform the CRUD functions, the chaincodes In our Car Dealer sample, when the chaincode serialNumber key in the PutState() API will be
do not read or write ledger directly, rather they adds a new part to the inventory ledger it uses included by the peer in the RWSet along with all
use Hyperledger Fabric shim API to invoke PutState() API in the code snippet below: the attribute values.
these operations in a peer node as shown in the // ==== Create vehiclePart object and
diagram below. marshal to JSON ==== Read
objectType := “vehiclePart” Read functions are queries on the ledger.

//vehiclePart := Chaincodes typically implement a variety of

&vehiclePart{objectType, serialNumber, queries, from reading values from a specific asset

assembler, assemblyDate, name, owner} to returning all assets that match certain criteria.

vehiclePart := &vehiclePart{objectType, For example, the chaincode could enable reading

serialNumber, assembler, assemblyDate, the value of a specific account, return all vehicles

name, owner, recall, recallDate} of a particular type or color, list all properties that

vehiclePartJSONasBytes, err := json. contain certain keywords in the description, or all

Marshal(vehiclePart) contracts with a particular vendor.

if err != nil {
To read the ledger, chaincode uses GetState() API
Create return shim.Error(err.Error())
} as shown in the code snippet below where we
Create or Init functions add assets to the ledger.
// === Save vehiclePart to state === read information for a specific vehicle by referring
Depending on the nature of the business network,
err = stub.PutState(serialNumber, the key chassisNumber:
create functions could add an asset such as a new
account, invoice, vehicle, real estate property, or vehiclePartJSONasBytes)
contract. Create functions can include additional err != nil {
info, such as the owner, opening value, location, return shim.Error(err.Error())
and other relevant attributes. }

27 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Update We change the Owner attribute to the value


vehicleAsBytes, err := stub. of newOwner, masrhal the vehicleToTransfer
Update functions simply change values on an already
GetState(chassisNumber) structure again and use PutState() to save
existing key or set of keys. For example, an update
if err != nil { updated values for the chassisNumber key.
could deposit or withdraw funds to an account,
return “Failed to get vehicle:”,
change the condition of a vehicle, transfer ownership
err Delete
of a property, or modify the status of a contract. In our
} else if vehicleAsBytes == nil { The delete function doesn’t really delete the data,
Car Dealer example, we transfer vehicle ownership to
return “Vehicle does not exist”, but just marks the key as “deleted”, indicating
a new owner by adding the following code after the
err that the specified asset is no longer available.
snippet above:
} This could represent the closing of an account,
vehicleToTransfer.Owner = newOwner // selling a product out of inventory, or completing
vehicleToTransfer := vehicle{} a contract. In the Car Dealer chaincode, we have
change the owner
err = json.Unmarshal(vehicleAsBytes, the following example using DelState() API on
&vehicleToTransfer) //unmarshal it aka serialNumber key:
vehicleJSONBytes, _ := json.
JSON.parse()
Marshal(vehicleToTransfer)
if err != nil { err = stub.DelState(serialNumber) //
err = stub.PutState(chassisNumber,
return “”, err remove the vehiclePart from chaincode
vehicleJSONBytes) //rewrite the vehicle
} state
if err != nil {
return “”, err if err != nil {
Note that after we get vehicleAsBytes, return shim.Error(“Failed to
}
we unmarshal it into a JSON structure delete state:” + err.Error())
return “”, nil
vehicleToTransfer. }

28 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Compiling Chaincode Installing & Instantiating Chaincode


Chaincode is a program, written in Go, node.js, or Chaincodes are installed on specific peers and
Java that implements a prescribed interface, and then instantiated on specific channels, giving
therefore it needs to be compiled before you run you complete control over which transaction
it. When deploying it on OBP, the compilation is types are visible and available to which peers on
automatically taken care of during deployment. any channel. In this example, the name of the
But it’s a good idea to compile it locally first to chaincode is cartrace and its version is v1.
ensure there are no compilation errors before
installing the chaincode in OBP. Using a local
compile environment you can quickly check for
any errors since it’s much easier to check the
compiler messages and make corrections in
the local environment. For local compiles you
need to download all the necessary packages After installing the chaincode on the founder
of the chaincode’s programming language and organization’s nodes, you need to decide which
Hyperledger Fabric. Every chaincode program channels to expose it on. Each channel can have
implements chaincode shim API. As a good multiple chaincodes, and each chaincode can be
practice, you chaincodes should be compiled instantiated on multiple channels depending on
locally to ensure there are no compilation errors the needs of your blockchain network.
before installing them in OBP. Developers can
setup their development environment and start
developing chaincode by following the steps
mentioned in Hyperledger Fabric documentation.

29 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Finally, you can enable access to chaincode via However, if an organization wants to have the Implementing Custom
REST proxies. chaincode accessible via their own REST proxy, Chaincode Functions
they need to edit the proxie’s configuration (Edit
Let’s take a simple use case and explore its custom
Configuration option on the proxie’s Actions
chaincode functions.
menu in the Nodes tab) and select the appropriate
channel, chaincode, and peer nodes to expose as
Use Case
REST end point.
In this use case, a large automaker and its dealers
have created a blockchain network to streamline
their inventory management activities. Blockchain
helps them reduce the time required to reconcile
shared inventory information with the vehicle and
parts audit trail.
In a blockchain network with multiple instances
and organizations, each organization’s blockchain
The sample includes a chaincode to manage the
instance administrator must install the chaincode
production, transfer, and querying of vehicle parts;
on their local peers. However, once chaincode has
the vehicles assembled from these parts; and
been instantiated for a particular channel, when
transfer of the vehicles.
the same chaincode is installed on any peer on
that channel, the instantiation is automatically
To locate and download the sample, please visit
extended to that peer – that is, the chaincode is
https://cloud.oracle.com/blockchain/additional-resources.
compiled and loaded into a chaincode execution
container linked to that peer. No explicit
The cartrace chaincode includes some
instantiation is required in this case.
custom methods for managing manufacturer-to-
dealer transactions:

30 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Methods Arguments & Key Code


initVehicle Chassis ID number, Make, Model, Assembly timestamp, Owner, Recall status,
Add a new vehicle to the ledger Recall timestamp

This creates a new vehicle with the attributes provided by Sample code to add a new vehicle to the ledger:
the arguments, e.g., "mer1000001", "mercedes", "c class", vehicle := &vehicle{objectType, chassisNumber, manufacturer,
"1502688979", "ser1234", "mercedes", "false", "1502688979" model, assemblyDate, airbagSerialNumber, owner, recall,
recallDate}
vehicleJSONasBytes, err := json.Marshal
(vehicle)

readVehicle Chassis ID number


Read the status of a vehicle
Sample Code to retrieve the vehicle info from the ledger:
Vehicles This retrieves the vehicle status based on the chassis
number in the arguments, e.g.,: “mer1000001”
chassisNumber = args[0]
valAsbytes, err := stub.GetState(chassisNumber)

transferVehicle Chassis ID number, Current owner, New owner


Change the ownership value of vehicle
Sample Code:
This transfers the vehicle from one owner to another chassisNumber := args[0]
based on the arguments, e.g.,: currentOwner := strings.ToLower(args[1])
Sample arguments are: newOwner := strings.ToLower(args[2])
“mer1000001”,
“SamDealer”, Get the vehicle based on the chassis Number and update the vehicle info
“JudeDealer” vehicleAsBytes, err := stub.GetState(chassisNumber)

vehicleJSONBytes, _ := json.Marshal(vehicleAsBytes)
err = stub.PutState(chassisNumber, vehicleJSONBytes)

31 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Methods Arguments & Key Code


initVehiclePart Part ID, Assembler, Assembly timestamp, Owner, Recall status, Recall timestamp
Add a new part to the ledger. This adds a new part to
the vehicle Sample Code similar to initiVehicle

readVehiclePart Part ID
This queries on part ID and returns vehicle info related to
the part Sample Code similar to readVehicle

transferVehiclePart Part ID, Current owner, New owner


This transfers the vehicle part from one vehicle to other
Sample Code similar to readVehicle

getHistoryForRecord RecordID
Vehicle This returns all the transactions for a given key of a record
Sample Code to retrieve the history of the transaction from the ledger
Parts
recordKey := args[0]
resultsIterator, err := stub.GetHistoryForKey(recordKey)

getVehiclePartByRange PartID, StartDate, EndDate


This performs a range query based on the start and end
keys provided Sample Code to retrieve the history of the transaction from the ledger

startKey := args[0]
endKey := args[1]
resultsIterator, err := stub.GetStateByRange(startKey,
endKey)

32 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Invoking Chaincodes via REST API Find the row for one of the REST proxies and copy Querying REST Proxy Version
the contents of the Route column as shown below:
OBP includes a REST proxy to enable chaincode View Version
functions to be accessed via RESTful APIs. The APIs Check connectivity to the REST proxy (gateway)
are configured in the REST proxy when chaincodes and verify its version number.
are deployed using OBCS wizards, or can be added Endpoint: https://{obcsRestURL}/bcsgw/
independently using Edit Configuration menu rest/version
pulldown from the REST proxy Actions menu on Returns: gateway’s version
the Nodes tab. See documentation for full REST
API details. The API functions described below are Transactions and Queries
provided by the REST proxy for querying gateway Invoke a Query
versions, invoking transactions and queries, and Resource-path depends on the specific API and is Execute a chaincode function that returns
subscribing to events. In addition, OBCS provides a shown below. Note: to distinguish the application information, without committing the transaction.
comprehensive set of REST APIs for configuration REST API endpoints from the administration ones, Endpoint: https://{obcsRestURL}/bcsgw/
and monitoring that handle the administration the resource-paths below start with /bcsgw/rest, rest/v1/transaction/query
functions similar to those in the Console web UI. while the administration and statistics APIs start Returns: response payload from the query function
with /console/admin/api. Following sections and its encoding
Each REST API requires an endpoint, header, describe application operations APIs for querying
Invoke a Method (Synchronous)
and credentials for authentication. Most also the ledger, invoking transactions, and subscribing
Execute a chaincode function and commit the
require a JSON body. The REST endpoints to events. For administration and statistics APIs
transaction to the ledger.
contain two components in the form of https:// see the relevant Task categories in the navigation
Endpoint: https://{obcsRestURL}/bcsgw/
{obcsRestURL}/{resource-path}. The bar in the online documentation. To use a visual
rest/v1/transaction/invocation
obcsRestURL is in the form <rest_server_ API explorer to test drive these APIs, visit Oracle
Returns: response payload from the function and
url:port/restproxy#>, which you can get from Blockchain Platform API Catalog and select either
transaction ID
the Nodes tab in the Console. Console or Gateway API spec in the dropdown.

33 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Invoke a Method (Asynchronous) Events In a command line these REST calls look like this:
Execute a chaincode function in asynchronous
Subscribe
mode and commit transaction to the ledger. curl -i -u <user>:<pwd> -H Content-
Register a subscription to an event, specifying an
Endpoint: https://{obcsRestURL}/bcsgw/ type:application/json -X POST -d @
event type, event name, channel, callback URL,
rest/v1/transaction/asyncInvocation body.json https://<rest_server_
and expiration time.
Returns: transaction ID created for this transaction url:port>/<restproxy#>/bcsgw/rest/v1/
Endpoint: https://{obcsRestURL}/bcsgw/
transaction
rest/v1/event/subscribe
View the Status of a Specified Transaction
Returns: subscription ID
Check the status of a previously submitted where parameters inside <> need to be replaced
transaction and retrieve the response payload. with actual values and body.json referenced by –d
Unsubscribe
Endpoint: https://{obcsRestURL}/bcsgw/ parameter is a text file that needs to contain the
Remove subscription registration for one or more
rest/v1/transaction JSON body with the details of the request, e.g.:
events using subscription ID.
Returns: transaction status and response payload
Endpoint: https://{obcsRestURL}/bcsgw/
from chaincode function {
rest/v1/event/unsubscribe
“channel”: “dealernet”,
Returns: subscription ID and status
GetTransactionID “chaincode”: “end2end”,
Request an asynchronous mode transaction ID by “method”: “myfunc”,
To test REST APIs before using them from
channel name for a transaction you will invoke “args”: [“a”,”b”,”3”]
applications, you can use command line tool curl
later in asynchronous mode. }
or GUI tools, such as Postman.
Endpoint: https://{obcsRestURL}/bcsgw/
rest/v1/transaction/getTxID In this JSON body, we are requesting invocation of
Returns: transaction ID and nonce end2end chaincode on the channel dealernet and
passing to the chaincode method myfunc and an
array of arguments.

34 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Inside the chaincode an Invoke dispatcher function In the Authorization tab you must specify your Initializing the Ledger
will retrieve the method name and arguments and credentials for access to the REST proxy. These
Now, let’s start using the API’s to trigger the
dispatch the call to the requested method. could be the administrator’s credentials of the
chaincode functions.
OBCS accounts (the same ones you use to login
If you prefer to use a visual API test tool, similar to the Console), or different credentials that have
Before you can start trading assets or executing
request using Postman would look like this: been added to the IDCS app of this OBCS instance
other business transactions, you may need
and configured for the RESTPROXY<N>_User role.
to establish the initial state of the ledger. For
Refer to Set Up Users and Access Roles in the
example, setting up your account balances, initial
online documentation for detailed steps
inventory, or open contracts.

The Header tab must specify Content-Type header


Continuing the car dealer example, we will
with application/json value as shown below.
initialize the ledger with a variety of vehicles and
In this UI the left pane contains a Collection – a parts. The channel is ebookchannel, the chaincode
library of pre-defined APIs. The main pane shows is still cartrace, the custom function is initVehicle,
POST request type in the grey bar and next to it the and the arguments include the chassis ID number,
REST endpoint with {{hostname}}:{{port}} indicating make, model, assembly timestamp, airbag serial
these are variables pre-set for this OBCS Workshop number, owner, recall status, and recall timestamp.
And the Body tab must contain the JSON body
configuration to point to my OBCS Rest proxy
with details of the request, which is the same as
instance. Below the grey bar is a series of tabs:
the contents of the body.json file used in the curl
example above.

When everything’s set, click the Send button to send


your request and the response will be shown below.

35 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

In REST format this looks like: To bulk load multiple vehicles and vehicle parts in Invoking Operations
the ledger, you can put the curl commands into
Once the ledger is initialized with some assets,
curl -u <user>:<pwd> -H Content- a script and use multiple body.json files or inline
the participants are ready to execute authorized
type:application/json -X POST –d @ json using a single quoted string after curl’s –d flag
transactions. The first step would be querying a
body.json https://<rest_server_ instead of a file reference like this:
vehicle chassis ID to see if it is available using the
url:port>/<restproxy#>/bcsgw/rest/v1/
query API (resource-path for queries is /bcsgw/
transaction/invocation curl -u $USER:$PASSWORD -H “Content-
rest/v1/transaction/query in the endpoint):
type:application/json” -X POST -d
The JSON body in body.json file: ‘{“channel”:”’”ebookchannel”’”,
{
{ “chaincode”:”’cartrace’”,”method”:
“channel”: “ebookchannel”,
“channel”: “ebookchannel”, ”initVehiclePart”,
“chaincode”: “cartrace”,
“chaincode”: “cartrace”, “args”:[“abg1234”, “panama-parts”,
“method”: “readVehicle”,
“method”: “initVehicle”, “1502688979”, “airbag 2020”,
“args”: [“porsche1000001”]
“args”: [“porsche1000001”, “porsche”, “’”$MANU_NAME”’”, “false”,
}
“cayenne”, “1541542934”, “ser1234”, “1502688979”]}’
“detroit-autos”, “false”, “1541542934”] https://<rest_server_
The response comes back with all of the
url:port>/<restproxy#>/bcsgw/rest/v1/
details from the asset’s ledger entry (edited for
The response is a simple success message, with transaction/invocation
readability):
the resulting transaction ID.
{
“returnCode”: “Success”,
“txid”: “9d0489543542e2ef53cc155dbdb52
31d5770640b15afc0b236a3089f2ed0835c”
}

36 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Detroit Autos then transfers the vehicle’s ownership On the Console’s Channels tab click to select
{ from the manufacturer to the dealership: ebookchannel and you can see in the ledger
“returnCode”: “Success”, browser the blocks that have been created with
“result”: { { these transactions.
“payload”: “{ “channel”: “ebookchannel”,
“docType”:”vehicle”, “chaincode”: “cartrace “,
“chassisNumber”: porsche1000001”, “method”: “transferVehicle”,
“manufacturer”:”porsche”, “args”: [“porsche1000001”, “detroit-
“model”:” “cayenne”, autos”, “johns-dealership”]
“assemblyDate”:1541542934, (Date in }
Epoch format)
“airbagSerialNumber”:”ser1234”,
“owner”:”detroit-autos”, The response is again a simple success message
“recall”:false, and a new transaction ID: The Get History Record for that chassis number
“recallDate”:1541542934}”, now gives a compound result, linking the two
“encode”: “UTF-8” { ledger entries:
}, “returnCode”: “Success”,
“txid”: “b56c45db0dd61a4d7a3421bd44 “txid”:
251891c9ee312429df918c32187bd20aa20176” “073c500739cc14b806867ac8eab3a75b9
} 04dc149a0965f99c48474ff91b800ee”
}

37 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

{ “IsDelete”: “false” ],
“returnCode”: “Success”, }, “encode”: “UTF-8”
“result”: { { },
“payload”: [ “TxId”: “txid”:
{ “073c500739cc14b806867ac8eab3a75b9 “5409c942d8c7c46466d7693dcdab2313c9
“TxId”: 04dc149a0965f99c48474ff91b800ee”, 8e220dc781fbff77c3abac645ef319”
“9d0489543542e2ef53cc155dbdb5231d5 “Value”: { }
770640b15afc0b236a3089f2ed0835c”, “docType”: “vehicle”,
“Value”: { “chassisNumber”: Finally, when the dealer sells the car they transfer
“docType”: “vehicle”, “porsche1000001”, the ownership again, which writes a new block to
“chassisNumber”: “manufacturer”: “porsche”, the ledger:
“porsche1000001”, “model”: “cayenne”,
“manufacturer”: “porsche”, “assemblyDate”: 1541542934, {
“model”: “cayenne”, “airbagSerialNumber”: “channel”: “ebookchannel”,
“assemblyDate”: 1541542934, “ser1234”, “chaincode”: “cartrace “,
“airbagSerialNumber”: “owner”: “johns-dealership”, “method”: “transferVehicle”,
“ser1234”, “recall”: false, “args”: [“porsche1000001”, “john-
“owner”: “detroit-autos”, “recallDate”: 1541542934 dealership”, “clark-and-sons”]
“recall”: false, },
“recallDate”: 1541542934 “Timestamp”: “2018-11-06
}, 22:43:38.548 +0000 UTC”,
“Timestamp”: “2018-11-06 “IsDelete”: “false”
22:37:36.205 +0000 UTC”, }

38 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

This action returns a new transaction ID: The chaincode library provides functions such as:
{ Full details for the REST API Endpoints are
GetID() (string, error)
“returnCode”: “Success”, available on the documentation site at
https://docs.oracle.com/en/cloud/paas/ GetMSPID() (string, error)
“txid”: “87d78d01a6cd0a79aa53f9f
c0caaaf40e5db529f182d0899a77cc blockchain-cloud/rest-api/rest-endpoints.html GetAttributeValue(attrName string) (value

3346cb33665” string, found bool, err error)

}
Advanced Topics GetX509Certificate() (*x509.Certificate, error)

AssertAttributeValue(attrName, attrValue
The ledger browser in the Console shows that this
string, error)
latest transaction has completed:
ABAC – Attribute Based
Access Control
Reference:

D
evelopers can utilize Hyperledger Fabric
(https://github.com/hyperledger/fabric/blob/
client identity chaincode library (cid) to make
release-1.3/core/chaincode/lib/cid/interfaces.go)
authorization decisions based on an attribute value
and/or the MSPID (Memership Service Provider Id)
Steps to setup CID module in chaincode
associated with the client. This library provides APIs
development environment:
that allow chaincode to retrieve the MSP ID used
1. Download Golang protobuf and errors
to issue the certificate of the invoker and all the
packages from golang github to your
attributes associated with the certificate provided
local environment
Additional detail for event subscription and when it was being issued via SDK’s register() and
a. https://github.com/golang/protobuf
callbacks are shown in Events – Publish & enroll() API calls to fabric-ca. Attributes are key
b. https://github.com/pkg/errors
Subscribe section under Advanced Topics chapter. value pairs like [email protected]. For
example, this can be used to allow or disallow
a specific operation in the chaincode like search
based on the attribute and value of the MSP.
39 Developing DApps on Oracle Blockchain Platform
Free SDK Free Cloud Trial

2. Download the cid modules and Now, let’s see how a developer can use the library
dependencies from hyperledger github to your defined above and create sample function in the
local environment from chaincode:
a. Download cid.go, interfaces.go from In your chaincode program, import the
https://github.com/hyperledger/fabric/tree/ necessary packages
release-1.3/core/chaincode/lib/cid crypto/x509
b. Download attrgr.go from https://github.
shim – github.com/hyperledger/fabric/core/
com/hyperledger/fabric/tree/release-1.4/
chaincode/shim
common/attrmgr
cid – using cidabac/cid path to refer to the
3. Setup your chaincode development
relative resource path of cid under vendor
environment based on go vendor dependency
directory as shown below
model as shown below.
a. Create a vendor directory under your
go project.
b.Under the vendor directory unzip the
4. Package (zip) the root (parent) folder into
downloaded packages from step 1 (github.
cartrace.zip and deploy the chaincode in OBP
com/golang/protobuf and gitbub.com/pkg/
using Quick or Advanced deploy wizards on the
errors) as shown in the screen shot below.
Chaincode tab.
c. Under the vendor directory unzip the
cid & attrmgr packages as shown in the
screenshot below.
d. cid & attrmgr module refers protobuf
packages.

40 Developing DApps on Oracle Blockchain Platform


In REST format this looks like:
Free SDK Free Cloud Trial

Now you can write functions to retrieve Identity getTransactionSubmitter Testing Chaincode Using Mockshim
in your code as shown below, using cid library
To speed up the development and testing lifecycle
to retrieve the identity of the Invoker in their
of the chaincode and enable local debugging, you
implementation as shown below.
may want to run some unit testing locally. This is
possible using a mock version of the stub shim.
ChaincodeStubInterface, which provides a local
While you might use these functions internally
mechanism to simulate responses for GetState/
as part of your business logic, you can
PutState/DelState ledger access functions
test the Identity Functions from Postman
getMSPID without connecting to a peer node. It enables a
client using the REST API. For example, for
test module for unit testing the basic functionality
GetTransactionSubmitter method, the REST call
of your chaincode before deploying it to Oracle
from Postman and the expected response are
Blockchain Platform. You can also use this library
shown below.
to build unit tests for your chaincode.

Import package “github.com/hyperledger/


getCertificateOwner fabric/core/chaincode/shim” and use shim.
NewMockStub to create smart contract and test
your procedures with debugging and without
having to connect to a blockchain network.

41 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Create a unit test function for the chaincode you c. Execute from Terminal go test (As These logging levels are provided as part of peer
want to test as shown below. shown in the screenshot below) configuration by the platform and are accessible
by clicking on a peer node in the Nodes view and
going to Logs view on the left hand side menu.
The logs are rotated and are listed in the date
order. Current log can be accessed by clicking on
Current Log button.

Logging in chaincode is performed by integrating


and exposing chaincode instance via the peer.
The chaincode shim package provides API’s for
the chaincode. This package will allow chaincode
to create and manage logging objects. These
Logging
logs will be formatted and printed in the logs of
Execute the Unit Test Logging is one of the ways to detect problems the peer based on the logging levels and also
1. Open the terminal window and go to the in chaincode logic or data. OBP provides logging accessible under Chaincodes menu once you drill
directory of the chaincode program using capabilities at Peer level and Chaincode level. down to a particular chaincode version. These logs
mock shim are similarly rotated and listed in the date order.
2. Using your go environment to execute the Peer logs can be configured through the Oracle Current log can be accessed by clicking on
test code Blockchain Cloud Service console. The logging Current Log button.
a. Open a new terminal or command line levels can be controlled based on severity levels
window (CRITICAL | ERROR | WARNING | NOTICE | INFO |
b. Browse to the cartrace_test.go code folder DEBUG).

42 Developing DApps on Oracle Blockchain Platform


In REST format this looks like:
Free SDK Free Cloud Trial

The following API’s are available for


chaincode logging:

NewLogger(name string) *ChaincodeLogger -


Create a logging object for use by a chaincode

(c *ChaincodeLogger) SetLevel(level Rich Queries in Chaincode


LoggingLevel) - Set the logging level of the Blockchain state DB is a key-value (KV) store.
logger . Logging levels are LogDebug, LogInfo, To view the custom logger entries in OBP Peer Querying KV store by value attributes rather than
LogNotice, LogWarning, LogError, LogCritical Console, go to Nodes tab and select the peer keys is termed “rich queries”. In Hyperledger

(c *ChaincodeLogger) IsEnabledFor(level where the chaincode is instantiated. On the Fabric open source, there’s an option to use

LoggingLevel) bool - Return true if logs will be peer drill-down menu select the Log option CouchDB to support rich data queries via

generated at the given level and set “Log for” selector to Chaincode, then proprietary query language. With Oracle

clock Current Log button. In the log you will see Blockchain Platform, the underlying KV store
LogLevel(levelString string) (LoggingLevel,
entries prefixed with your custom logger, e.g., uses Berkeley DB (BDB), which supports SQL-
error) - Convert a string to a LoggingLevel
[AutoTraceChaincode] as shown below. based rich queries in addition to Couch DB JSON
Query Language (for compatibility.) Using widely-
Example to create logging objects inside the
known SQL simplifies chaincode programming,
chaincode is shown below.
and can significantly reduce the amount of code
in addition to other benefits as shown in the
comparison table below.

43 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Comparison of rich data queries using Oracle Berkeley DB vs Couch DB:

44 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

In addition to the advantages above, Berkeley DB Query using complex SQL: Events – Publish and Subscribe
operates an order of magnitude faster than Couch SELECT json_extract(t.valueJson, Oracle Blockchain Platform provides publish
DB due to a number of architectural differences. ‘$.owner’) AS owner, json_extract(t. and subscribe mechanism for event-based
Berkeley DB enabled with transactions allows valueJson, ‘$.color’) AS color, applications. Events are asynchronous operations
definition of transactional boundaries. Once COUNT(*) AS count that are communicated via the peer. These
committed, data is persisted to disk. To enhance FROM <STATE> t WHERE json_extract(t. events can be subscribed by the entities outside
performance, one can use non-durable commits, valueJson, ‘$.docType’) = ‘marble’ the peer’s organization. For example, if OBP
where writes are committed to in-memory log files GROUP BY json_extract(t.valueJson, application performs a 3-way match of PO, Invoice,
and later synched with the underlying file systems. ‘$.owner’), json_extract(t. and Shipping information to trigger payments,
valueJson, ‘$.color’) ORDER BY json_ the match can be used to trigger a payment event
With Berkeley DB there’s also significantly reduced extract(t.valueJson, ‘$.owner’) conveyed to an ERP Financials system. OBP
number of roundtrips to DB for complex queries
supports subscription to different event types via
due to lazy evaluations of query results. Returns list of owners, color, and count of each REST Proxy:
color owned, sorted by owner.
“transaction”: Events for a particular
Examples of using SQL-based rich queries in OBP
transaction ID
chaincode:
“txOnChannel”: Events for every new
Query against JSON fields in values:
transaction on a particular channel
SELECT key FROM <state> WHERE json_
“txOnNetwork”: Events for every new
extract(valueJson, ‘$.docType’)
transaction in the entire network
= ‘vehiclePart’ AND json_
extract(valueJson, ‘$.owner’) = “blockOnChannel”: A Block header event for
‘Detroit Auto‘ every new block on a particular channel

45 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

“blockOnNetwork”: A Block header event on For two-way SSL authentication (mutual TLS), Steps to Subscribe to Events:
creation of a new block in the entire network callback server’s CA should issue a new certificate
Most useful type of events for subscribing are
and private key for Rest Proxy. This would be
“chaincodeEvent”: Custom events emitted by chaincode events. There is also a good use of
included as part of the callback parameters in the
chaincode logic subscribing to block and transaction events, but
Subscription REST API call.
majority of the useful events are chaincode events.
Clients or client applications can Subscribe and Let’s walkthrough step by step to subscribe to
Unsubscribe to all the events using the REST Publish Events:
events using Rest Proxy API’s. Developers can use
Proxy or Hyperledger Fabric SDKs. Unlike Chaincode events all the other event types Postman or other tools to perform RESTful API
like transaction & block events are provided by the calls. Screenshots below for performing REST API
Subscription REST API details are shown in the framework and do not require any programming use Postman.
table below. to publish the events. Chaincode events are
1. Setup authentication using Basic Auth.
published by setting up the events (programming)
REST Endpoint https://<rest_server_url:port/restproxy#>
in chaincode using stub.SetEvent() method and
Resource Path /bcsgw/rest/v1/event/subscribe deploying the chaincode on to the network.

Http Method POST


Example:

To ensure security, RESTt Proxy supports both


one-way and two-way SSL authentication to
connect Proxy with client callback server. To access 2. Setup http headers for subscribing events.

one-way SSL authentication, client needs to pass


the callback server’s CA certificate, and a valid
client certificate (only for mutual authentication) to
the REST Proxy.

46 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

The eventName corresponds to the name used in openssl pkcs12 -in client.p12 -out
setEvent() API in the chaincode. The expires field client.pem to convert it to PEM format.
specifies the time until event subscription expires
keyPassword (optional): only required when
and can be provided in one of the formats below:
client cert is concatenated with an
xxM: months
encrypted private key. If used it should be
3. Setup the request body to subscribe for the xxw: weeks
base64 encoded.
events by configuring the callback URL and other xxd: days
required parameters in the JSON body of the http xxh: hours
4. If the subscription was successful, developer
POST request as shown below. xxm: minutes
will receive a subscription id.
{
“requests”: [
The callbackTlsCerts structure contains one
{ “response”: {
“eventType”: “chaincodeEvent”, mandatory file and two optional fields:
“returnCode”: “Success”,
“callbackURL”: “http://ebookclientapp-webhook/
evtSender1”, caCert (mandatory): and is the callback “subid”: “75d8cc12-7673-4712-
“callbackTlsCerts”: {
server’s CA certificate in PEM format. It will be ba42-715adb69e6b1”
“caCert”: “-----BEGIN CERTIFICATE-----
\....\n-----END CERTIFICATE-----”, verified by the REST proxy before registering }
“clientCert”: “-----BEGIN CERTIFICATE-
----\....\n-----END CERTIFICATE-----\n-----BEGIN
the subscription.
ENCRYPTED PRIVATE KEY-----\....\n-----END ENCRYPTED 5. After subscription, the callback URL mentioned
PRIVATE KEY-----\n”,
clientCert (optional): refers to the certificate
“keyPassword”: “T3JhY2xl” REST proxy should use during the callback. in the body of the subscription will receive all the
},
It’s only needed when mutual authentication events generated when the chaincode is executed
“expires”: “1m”,
“chaincode”: “cartrace”, is required. It must be in PEM format and with even name as specified and event payload
“eventName”: “ebookTransferVehicle”,
assumed the certificate and private key are message used in setEvent() API in the chaincode:
“channel”: “ebookchannel”
}
concatenated. If you have PKCS#12 format
]
} certificate, use Linux command.

47 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

If your callback is for a packaged application that Request body to Unsubscribe


{ has its own REST API format, you can use REST
“eventType”: “chaincodeEvent”, connector in Oracle Integration Cloud (OIC) to map {
“subid”: “<UUID for the event the callback data to the desired inbound REST call. “request”:
subscription>”,
{
“channel”: “ebookChannel”, Steps to Un-Subscribe to Events: “subid”: “75d8cc12-7673-4712-ba42-
“eventMsg”: {
715adb69e6b1”
“chaincodeId”: “cartrace”, Endpoint URL https://<rest_server_url:port/restproxy#>
}
“txId”: “asdfgshjyjnmytrbndxvdfg
Resource Path /bcsgw/rest/v1/event/unsubscribe }
txid”,
“eventName”: “ebookTransferVehicle”, Http Method POST
Response for Unsubscribe Call
“payload”: {
“type”: “UTF-8”, 1. Follow steps 1 & 2 from subscribe events to
{
“data”: [“porsche1000001”, “john- retrieve the subscription id
“response”:
dealership”, “clark-and-sons”]
2. Setup http headers for subscribing events {
}
similar to subscribe “returnCode”: “Success”,
}
3. Setup the request body as shown below to “subid”: “f5505ce8-54c5-41c7-8ae8-
} 8077f630af9b”
Unsubscribe an event using its subscription ID
}

If you are calling back into a custom application,


it will need to parse this response and extract
relevant payload information.

48 Developing DApps on Oracle Blockchain Platform


In REST format this looks like:
Free SDK Free Cloud Trial

Using Rich History Database for In Oracle Blockchain Platform, neither of these are For example, using the rich history database,
Analytics/BI necessary. OBP provides a built-in mechanism to you could create an analytics report to learn the
shadow rich history updates to an Oracle database average account balance of all of the customer
The transaction history in Hypeledger Fabric
service, such as Autonomous Data Warehouse accounts over some time interval, or an interactive
and OBP is maintained in the linked blocks of
or DBaaS that can be specified by the user. This dashboard to monitor how long it takes to ship
transactions stored in the peer’s filesystem and
can be configured per channel, and the database different types of merchandise from a wholesaler
indexed by history DB pointers. When accessing
would contain state and transaction history for to a retailer.
transaction history, chaincode uses a shim API
the selected channel’s ledger. This configuration
to request transactions for particular key, and
option can be specified as a checkbox in Create a Developers can use an Oracle database such as
peer nodes retrieve this information based on
New Channel wizard or selected from the channel’s Oracle Autonomous Data Warehouse (ADW) or
the history DB pointers into the blocks. While this
actions menu on Channels tab. When enabled, any other Oracle DBaaS to create your rich history
works well for retrieving transaction sequence for
the peer will asynchronously write the latest state database. Once created, any BI tools or cloud
a few keys, it is a cumbersome way to aggregate
and history data to the associated Oracle DB as services, such as Oracle Analytics Cloud (OAC) can
data for analytics. You are also forced to retrieve
transactions are committed by the peers. Please be used to create reports and dashboards.
all the transactions in the history sequentially
refer to the Oracle schema documentation for
rather than being able to only retrieve the ones
how state and history data is mapped in RDBMS. In this configuration setup, we will be using DBaaS
matching certain attributes, like you can do with
Note the use of JSONValue fields, which can with OAC service. You will need DBaaS connection
rich queries for world state database. Creating
be unpacked into their own relational columns string parameters or a wallet to setup the history
reports on analytics dashboards would require
using JSON support in Oracle Database. You can DB connections in OBP and OAC.
many query transactions creating additional load
use any BI tools to create reports and interactive
on the network. Another alternative is to have a
dashboards for visualization about the data in your Steps to configure and use rich history DB:
client subscribe to all new block events and have
ledger based on rich history DB. 1. Create a DB service in Oracle Cloud, such as
the client applications parse the blocks and load
their data into a data warehouse. Autonomous Data Warehouse or DBaaS.

49 Developing DApps on Oracle Blockchain Platform


In REST format this looks like:
Free SDK Free Cloud Trial

2. In OBP use the Actions menu on the right of 3. Once the connection is established, switch 4. Now let’s do some analytics. You can
the blue service bar and select Configure Rich to the Channels tab and use a channel’s use any BI tools, but we will create Oracle
History. Fill in DB connection information as action menu to select Enable Rich History for Analytics Cloud (OAC) instance, which you
shown below. that channel. can do from MyServices dashboard. Once an
OAC instance is ready, use the actions menu
to select Oracle Analytics Cloud URL option to
open up the OAC home page.

That’s all you need to do. Now when any


transactions are committed on this channel,
5. Complete documentation for OAC is
OBP will automatically shadow them into a pre-
available at https://docs.oracle.com/en/cloud/
defined relational schema in the associated Oracle
paas/analytics-cloud/index.html, where
database. Run a few transactions and check that
you can refer to detailed instructions on
your database is getting an update.
defining connections, datasets, and creating
visualizations. The material below provides
a basic illustration of these steps using the
cartrace rich history database as an example.

50 Developing DApps on Oracle Blockchain Platform


In REST format this looks like:
Free SDK Free Cloud Trial

Select Oracle Autonomous Data Warehouse 7. Select the ADMIN user profile after the
Cloud or Oracle Database depending on which connection is successful.
kind of DBaaS service you are using and fill in
connection information.

You will see the history and state tables:


6. Click Create Connection button to configure <OBP instance>_<OBP channel>_hist for
the Analytics service to connect with DBaaS transaction history data
Service created in step 1.
<OBP instance>_<OBP channel>_state for
world state data

There’s also an <OBP instance>_<OBP channel>_


last table shown. You can’t query this table for
analytics since it’s used internally by OBP for
tracking the block height recorded in the rich
history database. It determines how current
the rich history database is and if all of the
chaincode transactions were recorded in the rich
history database.

51 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Note the VALUEJSON column that contains all the Note the use of “h” as an alias in the from clause
interesting attributes of the transaction. To enable to enable us to refer to JSON fields in the form of
full use of this data in your analytics dashboard <table-alias.column-name.field>.
or report, this column will need to be unpacked
into relational format when defining your dataset. The result dataset might look like the one shown
Oracle database provides built-in JSON support below and is now ready to be used in interactive
that makes this trivial. dashboards or visualizations as they are called
8. Click Enter SQL selector on the right to in OAC.
9. Replace the select above with the one below
perform a SQL query to view the contents
to extract JSON values into relational form
of history or state tables. Start with select
along with a few other fields:
* from “<OBP instance>_<OBP channel>_
hist” substituting ebookfounderorg for OBP
select h.key,
instance and ebookchannel for OBP channel.
h.valueJson.chassisNumber,
10. Define a project and create visualizations
h.valueJson.manufacturer,
based on this dataset. In a project view you
h.valueJson.model,
can right click the dataset and select Inspect
h.valueJson.owner,
option to see various details. Note the last
h.valueJson.recall,
field enables you to switch between Live
h.valueJson.recallDate,h.valueJson.
access to data (as its being updated from the
assemblyDate,
blockchain peer node) or Cached mode.
h.valueJson.airbagSerialNumber,
h.TXNTIMESTAMP,
h.TXNID
from “ebookfounderorg_ebookchannel_hist” h
where h.valueJson.manufacturer IS NOT NULL

52 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

To make this visualization using a few clicks we: 3) Dragged the following fields into the
Stacked Bar components:
1) Defined an aggregate cntofchassis under
a. OWNER to Category (X-Axis)
My Calculations
b. cntofchassis to Values (Y-Axis)
2) Selected Donut visualization for the Canvas
c. MANUFACTURER to Trellis Rows
3) Dragged the following fields into the Donut
4) And again, customized the chart using
components:
controls on the bottom left
a. TXNTIMESTAMP to Category
b. cntofchassis to Values
The results are shown in the screenshot below.
c. MANUFACTURER to Trellis Columns

As an example, let’s create some dashboards 4) Customized the chart using controls on the
counting the number of vehicles added to the bottom left
inventory by hour of day based on transaction
timestamp and grouped by the manufacturer The same dataset can be used for multiple
using a Donut visualization style. visualizations. Let’s create another one where
we are looking for how many vehicles have been
delivered to different dealerships (owners)
by manufacturers. Many powerful analytics capabilities can be

To make this visualization using a few clicks we: supported using rich history database enabled
by OBP, and in particular if this data is used in
1) Added a new Canvas at the bottom
conjunction with other data sources.
2) Selected Stacked Bar visualization for this
Canvas

53 Developing DApps on Oracle Blockchain Platform


Free SDK Free Cloud Trial

Summary References and


Resources
T
he Oracle Blockchain Platform is a
comprehensive blockchain platform for Oracle Blockchain Platform product page
building trusted networks that securely and reliably
accelerate business-to-business transactions. This Oracle Blockchain Platform developer site
production-ready service includes admin console,
Oracle Blockchain Platform documentation
membership service, peer nodes, orderer service,
and REST proxy. Once provisioned, you can link
Hyperledger Fabric open source documentation
instances into a network and begin to build custom
chaincodes to extend business applications such Oracle Blockchain News & Opinion
as payments, contracts, invoicing, shipping, and
accounting. Integrate blockchain with existing Oracle Blockchain Platform Getting

applications via REST APIs or client SDKs, and Started video

publish events, trigger notifications, or incorporate


Oracle Blockchain Platform Tutorials
existing business logic. Easily control access and
privileges with channels that facilitate scalability Downloadable free Oracle Blockchain Platform
and enable confidentiality. With Oracle Blockchain SDK for time-limited development and test
Platform you can quickly and securely connect your
organization to others in your ecosystem for a wide
range of automated business transactions.

54 Developing DApps on Oracle Blockchain Platform


Copyright © 2019, Oracle and/or its affiliates.
All rights reserved. Oracle and Java are
registered trademarks of Oracle and/or its developer.oracle.com
affiliates. Other names may be trademarks of
their respective owners.

You might also like