Permissioned Blockchain — User stories to Engineering (in Financial Planning) Part 1

Dev B
28 min readApr 21, 2018

--

Financial Planning AKA Wealth Management is a broad concept in the financial services industry. Client psychology, which frequently dictates the tone of financial planning comes from historical successes or failures in past investment. Such psychological makeup often drives the contents and quantum of an individual’s financial portfolio.

The profession involving financial planning is peppered with Money, Portfolio and Wealth Managers. Wealth Management is not just investment and private banking; it has definitions and boundaries of its own that call for a reference model, limited portions of which can partake in the blockchain technology.

As is evident, ‘blockchain-ed network’ is not one size that fits all, and this book steers clear of situations that do not warranty its use. Over the last twenty odd years, Wealth Management has evolved into a style of administering that requires good skills in financial planning. As Harold Evensky cites in his book, wealth management is the main discipline of financial planning. Any wealth management machinery therefore must aim to understand the client well — his or her dreams, goals and fears. Newer and stronger robotics and process-automation promises the possibility of advisory algorithms that can tailor for the client, a good, robust portfolio, but that is yet another matter. This book instead, cites a framework on how the blockchain technology manages financial portfolios, advisory interactions, tracks the goals and constraints with ease.

What is Wealth Management?

There always existed a practice of money management, focused and institutional. The impetus to such comes from a mindset where a person wants to make the most of financial returns.

This article introduces the wealth line of business to the aspiring blockchain architect, the experienced advisor and everyone in between. In consulting engagements, it comes as striking that as systems evolve through adoption of coarser and leaner technologies, much of the intrinsic knowledge and expertise in these specialized lines of businesses become lost. The book intends to offer wealth management and lending referenceable models enacted through the new world of networking as pertinent to blockchains only.

Blockchain and Distributed Ledger

Power of Blockchain comes from its ability to transfer assets and sustain an immutable history of such transactions. Distributed ledger technology, a critical module of blockchain fits the needs of a person who purports a portfolio of all his or her financial assets. When we add newer assets or revise the older ones, the ledger system maintains and manages the financial portfolio reflecting these changes. It however, can only do minimal client goal checking and constraints management.

Blockchain data can capture every committed transaction as chronological records, besides switching ‘on’ its ability to run “smart contracts. What gets implied by a smart contract is the ability to embed business rules within the blockchain architecture to transact assets between participants.

Blockchain and Distributed Ledger

Power of Blockchain comes from its ability to transfer assets and sustain an immutable history of such transactions. Distributed ledger technology, a critical module of blockchain fits the needs of a person who purports a portfolio of all his or her financial assets. When we add newer assets or revise the older ones, the ledger system maintains and manages the financial portfolio reflecting these changes. It however, can only do minimal client goal checking and constraints management.

Blockchain data can capture every committed transaction as chronological records, besides switching ‘on’ its ability to run “smart contracts. What gets implied by a smart contract is the ability to embed business rules within the blockchain architecture to transact assets between participants. Likewise.

Hyperledger Composer is an application development framework that helps you create applications that use the Hyperledger® Fabric™ blockchain. It contains APIs, a modeling language, and a programming model you define and deploy business networks and applications with, enabling participants to run transactions and exchange assets in such a network. Hyperledger Composer uses the construct of JavaScript programming language to express APIs that make the process of submitting transactions, standardized and easy. It also allows the participating user to create, retrieve, update, and delete assets within asset registries maintained by the system.

Blockchain applicable to wealth management

The proposed blockchain financial planning application consists of a consensus managed database of record for a customer, with no elaborate algorithms. A decidedly abstracted view of wealth management process breaks down into five different activities. Historically, as in the past, the five processes become the new way of running counsel, disclosures, portfolio management and reviews that can work flawlessly in the underworld of blockchain.

Managing and planning Finances

Extending the process of gathering data, the activities in financial planning extend to knowing the customer, knowing the fears and suspicions, managing expectations and collecting such information unobtrusively.

In the present day, we recognize a client through tax, credit, nationality and driving records. In the blockchain world, the signed certificates arrange the identification. This is by far a much better way than weaving through private and sensitive data. Certificates not only identify persons but also transactions, events and messages. Knowing the customer may come from a separate set of transactions. Required by regulations and law, identity verification is a precursor to a person’s participation in a permissioned network.

Transactions that occur during verification of a person are often transient and considered ‘significant’ only for a certain number of days. Therefore, the blockchain application beckons a quick set of activities external to itself.

Once the application admits the person into the blockchain network, every other member of that network begins to trust the person as ‘genuine’, having the right credentials, and having the right empowerments for controlled access to many artifacts and assets.

The UML class model (as in Figure 2) illustrates the nuts and bolts of a client’s identification and verification in the traditional way of conducting business, and how it evolves in the ‘blockchain-ed’ world. Not just with blockchain, identity in future will no longer have to expose sensitive information. What used to be KYC or Know Your Customer changes to the Revealed Client in the Permissioned Blockchain-ed world.

The question hence goes deeper on how accurate is the person’s identity? Does the word ‘identity’ have any relevance in the blockchain world, the way we perceive identity today? Is the person and contract trustworthy enough? Or, is there a perceived security threat?

Even a concept like employment paraded in the model, simply gets outmoded in the future. Profession takes precedence over employment where reliability and trust come from how others perceive the client.

Figure 2 — Client Information

Regulatory requirements ask for a deeper insight into clients and planners before admitting them into the business network.

Figure 3 — An UML model to reveal the client and get insights

Client interactions

The UML class diagram (as in figure 4) shows the potential touch points where blockchain database fits in. The coin currency is presented as another investment; another application of blockchain, and an alternative means to making payments or increase savings.

Figure 4 — Financial Planning Structure

Interactions, activities and opportunities resulting from advisory or exploratory events form a part of the routine that surround investments. The ‘client family’ comprises an owner and other members of the household. Not every member wins access to the portfolio blockchain. Even if they do, their entitlements differ significantly from the owner. The portfolio harbors investments of different asset classes along with liabilities to suggest a well-rounded balance-sheet at any point of time.

Informing the client and gathering data

In the process of initiating a client or a customer, a remarkable amount of effort goes into gathering and sharing information, which can set the real tone in digitizing such material.

Figure 5 — Data Gathering

Informing the client while gathering data can come from human interactions or dealings through software media. Such conversational sessions are an important sign-off and can have a significant impact on the portfolio.

Constraints are an important aspect of data gathering. Knowing the constraints gives us an idea on how much the client is willing to invest, how much can he or she scatter the investments. Within the constraints lie the answers. Data gathering leads to a ‘smart contract’. The design in Figure 6 captures the client’s initial perspective of how the portfolio appears. As we progress through the making of the portfolio, the client’s expectations, risks and concerns decrease or get elevated; the contract begins to serve as an ongoing checklist. Coin Currencies besides offering the ability to ‘pay’ also offers rewards, where a digital coin can get minted as part of the portfolio. Policies are the key to success in meeting the client’s goals. Intrinsically, policies come about through an iterative process undergoing many modifications with lapses in time.

Figure 6 — Account Management

Portfolio account comprises the owner (single account holder or joint) along with the household. It maintains within its folds, the objectives and terms of investment as necessary. Other financial planning systems may want to group the accounts logically under different criteria like owner or household.

Account Management

The financial advisory system trudges along with the client to work its way through several evaluations. It starts with the process of selecting suitable goals and setting up a financial-account or multiple such accounts catering to these goals. See figure 6 on account management.

Figure 7 — Client review of plan and model

Client Review of Financial Plan and Model

What is needed by the system is the client’s buy-in into an implementation which may well be laced with his or her appetite for risk. Goals can only be real if the constraints are known upfront, but that is not what humans are known to be good at. Therefore, the data gathering. Hence, the process of determining the different goal types and ensuring the client understands that the system is meant to address his or her concerns on the goals by knowing the constraints and expectations.

Client needs help with goals

I have no reasons to downplay the fact that setting a pragmatic goal is an integral part of the financial planning process. While every goal-set is a mix bag, not every client can foresee its value at the onset. It is more practical to let a third party such as the system suggest what makes a composite goal. Some time-tested strategies that worked before, will presumably continue to work in the new age — Intermediate or tactical goals comprise expenses and borrowings like college funds, education, weddings, recreation homes and vehicles. Such tactical goals are heavily constrained, as Harold Evensky describes them, “constraints are the three-cardinal system of time, dollar and priority”. It is often hard to juggle the goals with even two of them. Strategic or lifetime goals plan for financial independence and retirement. Few clients may need cash flow for a few months, some for years, a small number may expect disability and life insurance, others may not. Contingent goals are what they are — unknown but occur at an unexpected time. Therefore, a few investments in insurance become essential. Fire, floods, accidents, loss of income are but a few in this category. Each different goal provisions for the withdrawals and amounts needed, the targeted savings for the withdrawals and the dates thereof. It is of no surprise that few people take advantage of this free and proven formula to success. In fact, Harvard Business School conducted a study on goal setting and found that 83% of the population have no clearly defined goals. 14% have goals but poorly articulated. Only 3% have goals they commit to in writing.

Figure 8 models the goal service in UML.

Figure 8 — Goal modeling class diagram

Accounting for all the goals around financial independence, education, retirement income, improved cash flow, inheritance, estate taxes in the advisory plan and their inception or plan dates become useful in shaping the portfolio.

Figure 9 — Goals — core savings and excess

Often, a proposed financial plan may throw a scare, without the client expressing any discomfort. Though risk tolerance is unique to everyone, yet, people hide behind a mask and pretend to be risk averse. It is only when people open up to time and risk issues, optimizing the goal then for the client comes within easy reach.

Challenging the investment is yet another area where machines fall short of being the most convincing contender. Educating and challenging is a human trait that often comes through story-telling. It may still be hard to think how a machine could be imaginative, but it is clear, some algorithms will get “fuzzy” close.

Figure 10 — Advisory Functions

On the subject of stories, a user’s story of the requirements is the basis from which the architecture and engineering can proceed. User stories are a recognized way of capturing requirements. We can treat user stories as important development artifacts — as requirements expressed from the perspective of end-user goals. Often people refer to user stories as epics, themes or features but they all follow a comparable format. Think of a user story as a well-expressed set of requirements.

On the subject of stories, a user’s story of the requirements is the basis from which the architecture and engineering can proceed. User stories are a recognized way of capturing requirements. We can treat user stories as important development artifacts — as requirements expressed from the perspective of end-user goals. Often people refer to user stories as epics, themes or features but they all follow a comparable format. Think of a user story as a well-expressed set of requirements.

User Story

As a Portfolio Holder,
I would like to set my goals, expectations and constraints, express my investments, justify the asset allocation, plan for retirement and financial independence. The system must justify the financial risks involved. Knowing my tax situation now and later would be of tremendous help. Incidentally, I would like to review the portfolio at my convenience and with no time constraints. I’d like my identity and the portfolio to remain secure and yet be able to work with the portfolio without the fear of threat or other hassles.
Expected outcome:
A portfolio, I can monitor, any place, any time.

Failed outcome:
A portfolio that failed to meet the goals and expectations.

Knowing what is expected from the requirements, it is time to examine the prospects of designing a smart contract in both Hyperledger Fabric and Sawtooth. Realizing, the hammer can meet the nail in several unusual ways, our course of action starts with the Hyperledger Composer, from where we work our way into Sawtooth and inject Smart Contracts into different blockchain layers.

Hyperledger Fabric

Foremost, we must define and build a permission’d network — a network made of the client, an advisory system and reviewer. A business network definition has a file layout analogous to the one described beneath.

On a different terminal window, focus your attention on running Yeoman, which incidentally, commences the network. I would at this juncture spend a few minutes in answering these questions.

  • What is the use-case all about?
  • What name would I give to the business network?
  • Who is the author and what is his/her email?
  • What is the namespace to be used in the network?

Giving a proper business network name is all about the right semantics. I have suggested a very generic name. In a real application, proper naming and descriptions go a long way.

The namespace comes next. A proper namespace maintains the focus in the midst of many types of networks. The namespace allows similar functionality to exist in different namespaces. Hyperledger-composer uses Yeoman to generate the preliminary card assembly and a sample model.

$ yo hyperledger-composer

From the menu that emerges in the prompt, select Business Network. More prompts appear to define the network, a sample model and a folder structure.

Welcome to the Hyperledger Composer project generator
? Please select the type of project: Business Network
You can run this generator using: ‘yo hyperledger-composer:businessnetwork’
Welcome to the business network generator
? Business network name: financial-plan
? Description: Financial Planning
? Author name: Dev B
? Author email: devb@linux.com
? License: Apache-2.0
? Namespace: com.devb.wm
create index.js

create README.md

This generates a skeleton business network with an asset, participant and transaction, as well as a mocha unit test code. You may use the ‘composer archive create’ utility to generate a business network archive from the contents of such a directory. A smart contract file is normally found in the ‘model/’ folder created by Yeoman. It goes by the extension ‘.cto’ and begins with the name-space declared by you when you ran Yeoman.

namespace com.devb.wm

The namespace, per se has much less to do with the network but it’s re-use in different networks ensures the uniqueness of all resources in that model and even if different resources have the same name, the namespace sets them apart uniquely.

concept Allocation {
o Double moneyMarket
o Double bonds
o Double stock
o Double insurance
o Double realEstate
}

In the next few paragraphs, I shall describe the objects and components as they logically occur. In financial planning, “allocation” is a “concept” where the investment amount is distributed to money market, bonds, stocks, insurance and real estate through different mathematic models which we will discuss in the latter part of this chapter. Hyperledger composer comes with a pre-packaged, vocabulary of terms, where “concept” resembles a UML class. In the model, permitted is the use of “concepts” just the way UML classes support a participant, asset or transaction type. The concepts and other structures are held by braces supporting the “attributes” within. Attributes within the concept can use pre-defined types like String, Double, Integer and types defined or used within the model.

Example:

concept Percent {
o Double amount
}

Attributes and references start with a prefix. When prefixed by ‘o’, it specifies an object and ‘ →’ identifies an object by reference. A data-type such as “String” is a UTF8 encoded String, Double is a double precision 64-bit numeric value, Integer is a 32-bit signed whole number, Long is a 64-bit signed whole number, DateTime is an ISO-8601 compatible time instance, with optional time zone and UTZ offset; and Boolean is either true or false.

The model file is the template for the smart contract. Resources in the CTO file can range from Abstract types, Assets, Participants, Transactions and Events. Besides resources can be ‘Enumerated Types’ and ‘Concepts’. A key field is not associated with a concept because concepts are not stored in registries, and their presence cannot be referenced in other relationships. Incidentally, attributes can have ‘default’ values, they can be ‘optional’ and offer ‘ranges’. Using REGEX definitions to format the data type and control the data definition is an added feature. Resources and their properties may also have decorators attached. Decorators find use in annotating the model with metadata.

In the financial planning model, ‘rainy day’ or hidden goals are not explicit goals, they are more contingency — like an unfortunate, unforeseen auto accident. Intermediate are those with finite time objectives like college-education and wedding. Lifetime goals suggest the idea of retirement.

concept Goals {
o String clientId
o Allocation rainyDay
o Allocation intermediate
o Allocation lifetime
o Percent basicLivingExpenses
o Percent fixedTerminalExpenses
o Percent inflatableExpenses
}

Constraints are the client’s aversion to risk. Keeping a safe percent of investments in cash is probably the client’s safety net.

concept Constraints {
o String clientId
o Percent liquidity
o Percent marketability
o String threshold
}

Investment is about building an ecosystem where money is generated as part of the process. Expectations come from such investments and cash flows generated from them help meet the client’s livelihood.

concept Expectations {
o String clientId
o Double cashFlowBonds
o Double cashFlowStock
o Double cashReserve
}

Both market and cash flow projections must consider any anticipated inflation and in doing so, forecast the projected portfolio value.

concept Projections {
o String clientId
o Double anticipatedCashFlow
o Double anticipatedInflation
o Double anticipatedPortfolioValue
o Percent chanceSuccess
}

To capture the different parties and clients, enumerated are the different client types. Included in that list is the ‘Trust’ or ‘Trustee’.

enum ClientType {
o INDIVIDUAL
o PARTY
o TRUST
o POWEROFATTORNEY
}

Expression of a client or customer comes from an id. As explained earlier, the public cryptographic key or a PEM file could well be the only identifier needed for the client.

participant Client identified by clientId {
o String clientId
o ClientType clientType
o String firstname
o String midInitials optional
o String lastname
o String publicKey
}
enum AssetType {
o ASSET
o LIABILITY
}
asset Investment identified by assetId {
o String assetId
o String assetGroup
o String assetClass
o String assetSummary
o String taxJurisdiction
o String currency
o AssetType assetType
o Double value
o Double projectedValue
o Double interest
o Double dividends
o Double capitalGains
}

In the area of estate planning and management, provisions for distribution and directions are sustained within the asset.

asset Estate identified by assetId {
o String assetId
o String distributionUponDeath
o Double value
o Double estateTaxes
o Double probateFees
o String directionsForDisburtion
}

The enumeration data-type of ‘Recurring Basis’ has its usage with premium payments as they occur. Several premiums occur every day; many of them annually.

enum RecurringBasis {
o DAILY
o WEEKLY
o MONTHLY
o QUARTERLY
o ANNUAL
o ONETIMEONLY
}

Care, like estate planning provisions for elderly, child or disability that may occur in the future, necessitates a different set of investments.

concept Care {
o String careId
o String referenceNum
o String description
o Double cost
o RecurringBasis basis
o Double monthlyPremium
o DateTime expirationDate
}
concept Insurance {
o String insuranceId
o String referenceNum
o String description
o String insuranceType
o Double value
o RecurringBasis basis
o Double premium
o DateTime expirationDate
}

A divorce plan is just another contingency and like ‘care’ or ‘insurance’ may not even apply to the client. The reader will notice, they become optional in the portfolio.

concept DivorcePlan {
o String divorcePlanId
o String referenceNum
o String description
o DateTime expirationDate
}

The portfolio has a status-lifecycle. Initially, the portfolio stays dormant in a de-activated state, and then activated or merged with another at a later stage.

enum PortfolioStatus {
o ACTIVATE
o DEACTIVATE
o MERGE
}
asset Portfolio identified by portfolioId {
o String portfolioId
--> Investment[] investments
--> Client[] clients
--> Estate[] estates
o Boolean reviewed
o Goals goals optional
o Constraints constraints optional
o Expectations expectations optional
o Projections projections optional
o String[] disclosures optional
o Care[] care optional
o Insurance[] insurances optional
o DivorcePlan[] divorcePlans optional
}

Composer allows you to declare any data-type in the model as an array using the [] notation. Care, Insurance and Divorce plans often occur as multiple investments and consequently expressed as arrays.

enum AccountStatus {
o ACTIVE
o INACTIVE
o DORMANT
}
asset Account identified by accountId {
o String accountId
o AccountStatus status
o Client client
o Portfolio[] portfolio optional
o String[] Notes optional
o DateTime beginningDate
}

Transactions are operations within a contract that result as entries in the ledger. By definition, the primary aim of a ledger is to ease the assets between people. Many such transactions are stored in pockets of blocks in a blockchain.

transaction SetGoals {
--> Client client
--> Investment investment
o Goals goals optional
o Constraints constraints optional
o Expectations expectations optional
o Projections projections optional
}
transaction Optimize {
--> Portfolio portfolio
}
transaction ModifyPortfolio {
--> Portfolio portfolio
o Allocation newAllocation
}
event ChangeAccount {
--> Client client
--> Portfolio portfolio
}
event ChangePortfolioValue {
--> Portfolio portfolio
o Double oldValue
o Double newValue
}
transaction ClientReview {
--> Portfolio portfolio
o Boolean review
o Boolean machineReview
}

This calls for implementation of separate functional logic for each of the transactions declared in the ‘lib’ folder. The model file just declares the transaction, it does not tell Fabric or Composer what must go in there. Thus, the need for a separate JavaScript file. All transactions — their internal workings go into the logic.js. Think of the contract as made of two different parts — first, the declarative structure and the second, transactional behavior. Since transactions involve participants and assets, the JavaScript code fetches participants from their registry, assets from their registry and complete the contract between them. You will notice that such is the case with the client review function and changing the portfolio value.

Every transaction on successful completion and consensus gets lodged in blocks within the blockchain, enriching the ledger with pertinent historical data on ‘who said what, who did what’ within the network.

As part of the next steps, we must generate a Network Card using either a certificate, or user id and password. Compare this to an access card that’s needed to enter a controlled and monitored physical building or premises. This network access card is similar in concept, except it is virtual.

$ cd financial-plan
$ composer card create --file fp.card --businessNetworkName financial-planning --connectionProfileFile connection.json --user financialadvisor --enrollSecret secret

Hyperledger composer has a unique bundling process where all artifacts come together as an archive. Generating the network archive is next in our list of activities. The network archive gives you the flexibility of distributing the application to different peers and nodes. Later, when modifications come in and the model moves through its lifecycle of changes, newer archive versions take their place.

$ cd financial-plan
$ composer archive create --sourceType dir --sourceName . -a financial-planning.bna

Once the archive is generated, it is ready to be deployed to the running instance of Hyperledger Fabric.

$ composer network start -a financial-planning.bna -A financialadvisor -S secret -c fp.card -f financialadvisor@fp

If the above command fails to succeed, you may resort to using the pre-bundled sample card as a fallback.

$ composer runtime install –card PeerAdmin@hlfv1 –-businessNetworkName financial-planning

And deploy the Network Card.

$ composer network start --card PeerAdmin@hlfv1 --networkAdmin admin — networkAdminEnrollSecret adminpw --archiveFile financial-plan@0.0.1 --file fp.card

Now, when you start the REST server, you have access to the network, contract and blockchain.

$ composer-rest-server

When prompted, enter the name admin@financial-planning

The composer rest server comes along with a client through which you can invoke the operations. The Node.JS middleware running at port 3000 is accessible through http://localhost:3000/explorer.

A different architectural approach to the same problem through the lens of lightweight and nimble Sawtooth opens yet another possibility. Sawtooth Core includes SETH (Sawtooth-Ethereum integration) the counterpart of GETH for addressing the nuances of Ethereum Virtual Machine. Seth also makes it easy to port existing EVM smart contracts and DApps.

In the Sawtooth world, the Smart Contract is akin to Transaction Families. Seth has three components, client, transaction processor and the RPC server. The “seth-rpc” server is an HTTP server that acts as an adapter between the Ethereum JSON RPC API and the client interface provided by Sawtooth. Sawtooth’s Seth is Hyperledger Sawtooth and Burrow running the Ethereum Virtual Machine enabling Solidity created Smart Contracts to run in that environment. The Seth client is the user-facing CLI tool for interacting with a Sawtooth-Seth network.

You will see a few container instances of Seth and Sawtooth running. Now you can run a few tests. Open the browser and then type ‘http://localhost:8080/blocks’.

If you receive a JSON response reporting on the blocks used up in the Blockchain, you can be assured Sawtooth is up and running. Sawtooth REST API Server uses port 8080, 3030 stays captured by the Seth-RPC Server. If you are using a cloud instance — AWS EC2 or Azure, please keep those ports accessible. You may now try your hand at “shelling” into one such container and running blockchain transactions within. Incidentally, you do not have to rebuild the containers every time you fire up Sawtooth.

$ cd sawtooth-seth
$ docker-compose up
$ docker exec -it seth-rpc bash

While you are transported into the seth-rpc container, you are confronted with completely new surroundings where you appear as root. “seth-rpc” container lets the CLI run transactions that are involved with smart contracts. Since all transactions accessible through its RPC interface are required to come from a verified and certified source, the first thing within the Docker shell is to generate a PEM file that holds the credentials. The command below generates a new, password-encrypted key.

$ openssl ecparam -genkey -name secp256k1 | openssl ec -out alias.pem -aes128

The newly generated ‘alias.pem’ file is quite unique. Assign this public encrypted file to an ‘alias’. Interacting with Seth, requires us to create an account on the network. This account is associated with the new private key. You can use any encryption cipher by changing the final -aes128 flag or omitting the flag to generate the key.

$ seth account import alias.pem alias

Hence, you open an account with the credentials and assign to a variable ‘alias’; the alias name could be anything alias1 or myalias. It stays unique to this account. Copying the key to an internal directory and creating an alias for the key makes the key reference-able for future commands. What remains in completing the account is accomplished by running the command seth command create and obtaining the address used by the process. In the Blockchain world, a nonce helps in generating a unique address where there are possibilities of conflicts.

$ seth account create --nonce=0 --wait alias

One thing I am sure that strikes you odd is the “ — wait” instruction appended to the account creation command. The asynchronous wait ensures you receive an acknowledgment when the operation is complete. The response you receive may resemble the one below, the hash codes that appear may be different.

Transaction Receipt: { “TransactionID”: “36140169f684da471acc4a75ced7e…”,
“Address”: “659f1526b3a62a81039ab840d71eac5751370b36” }

The command should display the address of your brand-new account upon success of the command. Please store the “address” returned by the Transaction Receipt. The next step is an important and often forgotten or missed, which requires the account be unlocked. Shell into the “seth-rpc” container if you have not already and copy the PEM file to /root/.sawtooth/ folder and restart the server unlocking the alias(es).

Tip — Hyperledger Sawtooth documentation is not perfect. Much of seth-rpc setup came from my conversations with the folks working for Hyperledger Sawtooth. We went through a series of Jira tickets and iterations before we got this right.

$ docker exec -it seth-rpc bash
$ cp alias.pem /root/.sawtooth/
$ seth init http://rest-api:8008
$ seth-rpc — connect tcp://comp-seth-rpc:4004 --bind 0.0.0.0:3030 --unlock alias

Now you can test the API by posting the JSON.

{url: ‘http://127.0.0.1:3030', method: ‘POST’,
json: {“jsonrpc”: “2.0”, “id”: 19, “method”:
“eth_sendTransaction”, “params”: [
{“from”: “0x90e77c172a….”, “gas”: “0x6691b7”,
“gasPrice”: “0x174876e800”, “data”:5260200160….
}

The syntax of a Smart Contract for SETH comes from Solidity. It has an Object-Oriented flavor where the term contract encapsulates a UML class. It is left to us to declare and realize the attributes and operations within the body of the contract. In the lines of financial planning, I introduce a simple portfolio design for SETH. We can now use Truffle to compile and deploy the contract. To begin with, we create a separate folder and run the truffle command to initialize the smart contract design.

$ truffle init

Truffle like Yeoman initializes the folder by creating a few sub-folders and necessary code. In one of the sub-folders ‘contracts, you will find a ‘Migrations.sol’ pre-populated by Truffle. Our contract, ‘Portfolio.sol’ will reside alongside it.

pragma solidity ^0.4.17;contract Portfolio {  struct Client {
uint investing;
bool isInvested;
bool isIdentified;
InvestmentAsset inasset;
}
struct InvestmentAsset {
uint stockId;
bytes32 name;
uint number;
uint marketValue;
}
mapping(address => Client) public client;
InvestmentAsset[] public investment;
function invest(uint stockId) public returns (bool) {
Client storage investor = client[msg.sender];
require(!investor.isInvested);
require(investor.isIdentified);
investor.isInvested = true;
investor.inasset = investment[stockId];
...
return true;
}
}

The code written in Solidity declares a client, an investment asset and a function that conjoins the client to the investment. Truffle achieves in transporting the code to Sawtooth-Burrow running on Docker containers. In most cases, a good practice is in keeping the Solidity code small and breaking the Smart Contract into smaller chunks to avoid large ‘gas’ usage. With Sawtooth-Seth, ‘gas’ prices and consumption do not matter as software and hardware expenses carry no price value but controlled through network permission-ing. To execute this code, we will need the ‘Address’ as shown to us before. Truffle needs to know it will no longer communicate with ‘Ganache’ — its own Blockchain implementation, but with Sawtooth-Burrow.

The folder used in truffle initialization has a file called “truffle.js”. Please alter this file and validate it points to the Sawtooth instance.

const Web3 = require('web3');
const web3 = new Web3(new
Web3.providers.HttpProvider('http://127.0.0.1:3030/'));
module.exports = {
networks: {
'sawtooth': {
network_id: '19',
host: '127.0.0.1' ,
// address of the alias
from: '659f1526b3a62a81039ab840d71eac5751370b36',
port: 3030
}}}

Truffle requires the Web3 libraries to access seth-rpc running at port 3030. The ‘from’ parameter carries the address of the alias. Using proper configuration, we can use Truffle to compile and deploy the code to Sawtooth. You may receive an error when deploying. This customarily happens if the running node has no accounts. From its documentation, Truffle appears to deploy contracts using the first account available, the ‘from’ property in the ‘configuration’ ensures the framework works intimately with the account just generated.

$ truffle compile
$ truffle deploy --network sawtooth –reset

You may also use additional CLI parameters to obtain more information when deploying the contract.

$ truffle migrate — network sawtooth --reset --verbose-rpc

As explained before, you could use either Truffle, Seth CLI or a custom app in Python or Node-JS to deploy the contract. The contract in our case is relatively large and the ‘gas’ consumed may be significant.

I have had my share of success and failures in deploying them to the container. There is always room for reducing the contract to smaller chunks. Knitting the pieces into one contract achieves the purpose of this book.

Node.JS Express allows route handling and middleware supervision of RESTful invocations. With Sawtooth-Seth and Fabric running as services, we introduce a separate middleware server that manages the functions and optimizations for the financial planning application but also provides posts to the RPC server running on Sawtooth.

Figure 11 — Technology Stack

The middleware runs through callbacks that sit on top of the actual request handlers as shown in Figure 11. It takes the same parameters to re-route the request. Much like a delegate. To upload the smart contract written in Solidity, a client written for Seth-RPC in Node.JS can serve the purpose.

/*sethrpclib.js*/
/*jshint esversion: 6 */
let request = require('request');

The service at “seth-rpc” accepts JSON-RPC posts only. Though used are parameters such as gas and gas price, Sawtooth does not care about them, they are targeted for other Ethereum networks.

function postSethRPC() {
request({url: 'http://localhost:3030',
method: 'POST',json: {"jsonrpc": "2.0",
"id": 19,
"method": "eth_sendTransaction", "
params": [{"from":
"0x659f1526b3a62a81039ab840d71eac5751370b36",
"gas": "0x6691b7",
"gasPrice": "0x174876e800",
"data": "0x60606040523415600e57600080fd5b609a8061001c6000396000f300606060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663c6888fa181146043575b600080fd5b3415604d57600080fd5b60566004356068565b60405190815260200160405180910390f35b600702905600a165627a7a723058206f4a604d7fb9f559014a48b1e2be9ab50644a5984e8bbb1b6496425aa59f1ee00029"
}]}
}, function(error, response, body){
console.log('Seth RPC Response', body);
})};

You can test the instance of this code by running sethrpclib.js on Node.JS or by exposing the library for other clients to use.

postSethRPC();
module.exports = postSethRPC;

For the node client to run, the ‘request’ library is needed. Besides, if the computer operating system fails to support the new Docker and you are using the older Docker Toolbox, then run the Docker Quickstart Terminal and carry out the commands in the preconfigured terminal.

Ensure you make a note of the Docker IP address which appears when the shell starts. In the JavaScript code, the URL will change to url: ‘http://192.168.99.100:3030’

$ npm install request

The code body is a single function ‘postSethRPC’ that requires two important parameters — the ‘from’ address or the address of the account and the application binary code of the solidity compiled code. To compile the Portfolio.sol created earlier, run the following command.

$ solcjs Portfolio.sol --binary
$ cat Portfolio_sol_Portfolio.bin

You must copy the code as it appears in hex to the place in the code shown as data to run this Node-JS application. The code is ready to be run now. In fact, you can spend some time to complete the rest of the middleware code that listens to the requests coming from an HTML or PHP client. If the post requires the data to be transmitted to Sawtooth-Seth, the method postSeth will route it to the URL.

/*jshint esversion: 6 */let express = require('express');
let app = express();
let router = express.Router();
let postSethRPC = require('./sethrpclib');
// seth rpc client logger

let sethclientLogger = function(req, res, next){
console.log('Log Request: ', req);
console.log('Log Response: ', res);
next();
}
// No mount path on this middleware operation
// This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Start Time:', Date.now());
next();
})

The help.html though declared in the ‘public’ folder, has no listing in this article. It is a standard static html and I leave it to the reader to design and develop it.

// handler for help path, which renders a special pagerouter.get('/help', function (req, res, next) {
res.render('help.html');
next();
})

When the “postseth” operation is invoked through the command http://localhost:9999/postseth, the corresponding “postSethRPC” exported by the previous sethrpclib.js file is called upon.

// Post function that calls Seth RPC
router.post('/postseth', postSethRPC);
// POST method route
router.post('/postsethrpc', function (req, res, next) {
postSethRPC();
res.send('POST request to the homepage');
next();
})
// mount the router on the app
var options = {
dotfiles: 'ignore', etag: false,
extensions: ['htm', 'html'],
index: false, redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
app.use('/', router);
app.use(sethclientLogger);
console.log('Seth RPC Client Listening at port 9999');
app.listen(9999);

The middleware running on Node-JS ‘express’ provides the necessary isolation and cushion to the back-end database or blockchain.

As the reader, you experienced Hyperledger with its several blockchain implementations offering a strong choice of architecture, let me summarize the features we covered. Hyperledger composer lets the parties define their “business network”, a judiciously chosen gathering of people and machines whose goal serves the contract or agreement. The business network owes its definition to the artifacts and rules which are collected and digitized for different deployments. Several participants access the “business network”, some even undertake to maintain it.

The maintainer of the network runs a good deal of hardware “peer nodes”, sustaining the system. To prevent a crash, Hyperledger Fabric replicates the distributed ledger across such peer nodes. Composer modeling language expresses the domain model of the business network.

The model, once constructed, allows developers to capture “smart contracts” as ‘executable transaction processor functions’, written in JavaScript.

Hyperledger Sawtooth is the strong choice among nimble implementations with a powerful Burrow combination to enable the use of many Smart Contracts written for Ethereum. This chapter treated both architectures covering their strong points, besides extending into micro-services and other useful code. As this chapters comes to a close and we move into the new chasms of lending and mortgage, the next chapter though shorter in description, is not short on content. Much of Hyperledger Fabric and Sawtooth-Seth engineering and architecture were portrayed in this chapter.

Checkout GitHub.com/devbnj and the book in Amazon.com for more details.

— -

--

--