DevDApps
DevDApps
developer.oracle.com
Free SDK Free Cloud Trial
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.
Summary 54
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)
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.
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.
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.
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.
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.
Developers can also select Custom option to create tabs and capabilities.
console of each non-founding member loads a wizard or by exporting the certificate manually.
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 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.
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.
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
assembler, assemblyDate, name, owner} to returning all assets that match certain criteria.
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
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. }
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:
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)
vehicleJSONBytes, _ := json.Marshal(vehicleAsBytes)
err = stub.PutState(chassisNumber, vehicleJSONBytes)
readVehiclePart Part ID
This queries on part ID and returns vehicle info related to
the part 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)
startKey := args[0]
endKey := args[1]
resultsIterator, err := stub.GetStateByRange(startKey,
endKey)
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.
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.
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.
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”
}
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”
}
{ “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”, }
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
}
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.
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.
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.
(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.
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
“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.
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.
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.
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.
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.
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
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