This material from a series of articles on Russia's first projects developed on the basis of blockchain technology is a bit unusual. You will learn about the technical implementation of the platform for mutual pet insurance, which was launched only today. Now you can test the bot
Lexi Bot in Telegram. We welcome your comments.

The series of articles "Immersion in technology blockchain"
1. A series of materials on Emer technology:
1.1.
The secrets of EmerCoin .
1.2.
Decentralized uncensored domain name system .
1.3.
Worldwide public key infrastructure .
1.4.
Decentralized password-free security system .
2.
Fast and secure transactions .
3.
Ecosystem of digital dentistry .
4.
Combating counterfeit goods .
5.
Mutual insurance of animals .
6.
What is ICO and how to conduct it .
7. Loading ...
What is ReGa Risk Sharing and Lexi
ReGa Risk Sharing has developed a platform for mutual pet insurance using smart contract technologies, photo identification and scoring.
Lexi Bot, a risk management robot, helps a client to join the Lexi Club pet assistance club and, after transferring a membership fee of about 350 rubles per month, receive up to 80% reimbursement of the cost of veterinary services in case of a sudden illness or an accident . Each member of the Club receives a virtual Lexi Card, which is the identifier of a smart contract that manages the account of the Club member in the Ethereum blockchain.
')
Distributed Financial Products
ReGa Risk Sharing platform implements distributed financial products - products that can be produced and serviced without the participation of centralized financial institutions - banks and insurance companies. For financial products with a low investment size (loan), which can be called micro financial products, the existing banking system cannot provide an adequate balance of cost and quality at a given level of risk. This is primarily due to the fact that the general principles of regulation do not allow the use of modern technologies to optimize business processes. An example of such a class of products is micro-insurance, where the average bill is about 1,000 rubles, and at the same time the settlement of losses requires significant costs from the insurance company. As a result, the contract with the client is usually drawn up in such a way as to practically exclude cases of payments for insured events. The solution could be the use of mutual insurance approaches, when the clients themselves merge into a virtual insurance company, form the capital of such an insurance company from their contributions (insurance premiums) and make payments for insured events from the mutual insurance fund.
The platform of distributed financial products is essentially an automated banking / insurance system for such a mutual bank / insurance company and provides a number of services, including accounting and storing funds in the blockchain, risk assessment and management, automation of business processes and workflow, selection and risk assessment of service providers to settle insurance claims and settlements between participants. The blockchain is a repository of capital of a mutual insurance company, while access to the account is controlled by a smart contract that defines the rules for replenishing and spending the funds agreed and “signed” by all participants.
Distributed Financial Products Architecture
The architecture of distributed financial products can be represented as a model consisting of 4 levels: blockchain, financial primitives, financial products and applications.
The Blockchain level provides a set of basic services to the rest of the model, including the mechanism for creating and executing smart contracts, accounts, financial messages, private messages, cryptocurrency, and the blockchain itself as a distributed and reliable data repository. It is assumed that the blockchain has two types of accounts - external or personal accounts that are controlled by the private key and contract accounts that are controlled by the program - a smart contract stored in the blockchain along with the account balance and the state of its internal variables. Transfer of funds between accounts is carried out by sending financial messages. The initiator of the sequence of financial messages or transactions can only be the owner of the external account. The recipient can be either an external account or a contract account. As a result of processing a financial message, a smart contract can create a new financial message. Thus, a transaction may consist of a whole sequence of messages or, more precisely, of the results of their processing and involve a whole multitude of accounts, both external and contract accounts. Each transaction is associated with the cost of its implementation and this value will be debited from the account of the initiator of the transaction.
The “Financial Primitives” level is a set of “building” blocks for the next level of financial products. Some of these services are implemented on the basis of the “Blockchain” services, and some are off-line primitives that are not related to storing information in a distributed database. So, we cannot store the scoring model (card) on the blockchain, since in this case it becomes accessible to everyone, including potential customers.
Photo scoring
To build a scoring model based on customer photography, technologies provided by Microsoft were used: Microsoft Cognitive Service and Azure Machine Learning. With the help of the Microsoft Face API (MS Cognitive) service, about 15,000 photos of potential borrowers who were denied a consumer loan were processed or approved by at least one of the banks connected to the scoring and underwriting system. They obtained a complete set of possible parameters: Face Landmarks and Face Attributes (
age
,
gender
,
headPose
,
smile
,
facialHair
and
glasses
). Then, photographs were dropped where no individuals were found, or more than one was found. About 3% of photos were sifted out in this way.
The remaining dataset was normalized, that is, the
Landmarks
were converted with regard to the head rotation (
Roll
and
Yaw
parameters), and then all the “faces” were proportionally reduced to a single size - 100x100, which made it possible to compare the parameters of the individuals with each other. Each of the processed photos was assigned a sign
Result = {0 - | 1 - }
Result = {0 - | 1 - }
. After this preprocessing and normalization, the array was converted to a CSV file and uploaded to Azure Machine Learning.
A number of filters were applied to the resulting table, including
Project
— selection of a subset of features and
SMOTE
— addition of a sample with negative results (
Result = 0
). As a result, the number of rows in the sample increased to 18,754, and the number of features (columns) was 64.
Two-Class Boosted Decision Tree
used as a model, trained in 70% of digitized photographs of borrowers and refusers selected randomly from the original array (13,000 lines). After learning, the remaining part of the array (about 6,000 lines) was used for scoring and evaluating the accuracy of the model.
The following results were obtained:


Hierarchical structure of risk groups
To manage risks, the ReGa Risk Sharing platform uses a three-level hierarchical structure of equivalence groups by range of scoring values. The upper level - “Superpool” defines the minimum acceptable level of scoring value for all community members. The next level - “Pool” “splits” the maximum range into several subranges, and the next level “Subpool” finally defines the groups according to risks.

For any new member of the community, the scoring value is calculated and, based on this value, the position of the smart contract of the community member in the hierarchical structure is calculated. The main idea of ​​risk grouping is to isolate various categories of risks from each other and the ability to track the effective value of risk at different levels of the structure. In this case, if one of the groups exceeds the target values ​​for risks and the estimated cost of maintaining the group is higher than the residual value, then the group can be disbanded and community contributions returned to those members who leave the community.
The structure of pools is implemented in the form of smart contracts in the Solidity language for the Ethereum virtual machine. An online version of the compiler
is available on GitHub . It is worth noting that Solidity allows multiple inheritance. Below are the class interfaces that organize the hierarchical structure.
The poolAccounts class implements the accounting for the movement of funds according to the internal structure of accounts for organizing bank accounting. pragma solidity ^0.4.6; contract poolAccounts { address public owner; int[11] public accounts; function changeBalance(int _amount, an _account) internal; function getBalance(an _account) internal constant returns(int _balance); function isValid() public constant returns(bool _valid); function posting(an _dr, an _cr, int _amount) public; function update(int _number, int _case) public; }
riskManager is an auxiliary class of risk management service. pragma solidity ^0.4.6; contract riskManager { uint public risk;
The poolMember class is a member of the pool, which can be both a community member and a mid-level pool. pragma solidity ^0.4.6; contract poolMember is poolAccounts { pool public parent; int public limit; function getPool(uint _level) public constant returns(pool _pool); function posting(an _dr, an _cr, int _amount); function update(int _number, int _case); function setParent(pool _parent) public; function loan(int _amount) public; function checkLimit(int _loan) public constant returns(bool); }
The pool and poolOfPools classes implement methods for working with a pool and a pool of pools.Pool pragma solidity ^0.4.6; contract pool is riskManager, poolAccounts { bytes32 public name; poolMember[] public members; function insert(poolMember _member) public; function isMember(address _member) public constant returns(bool); function update(int _number, int _case); function getPool(uint _level) public constant returns(pool _pool); function lendingCheck(int _loan, poolMember _member) public constant returns(bool); function lend(int _loan, poolMember _member) public; function loan(int _amount, uint _level) public; }
POOLOFPOOLS contract poolOfPools is pool { function insert(poolMember _member) public; function push(pool _pool) public; function isMember(address _member) public constant returns(bool); function accept(regaMember _member) public constant returns(bool _accept, pool _pool) }
REGASUPERPOOL pragma solidity ^0.4.6; contract regaSuperPool is poolOfPools { function regaSuperPool(uint _minScore, address _owner) }
REGAPOOL pragma solidity ^0.4.6; contract regaPool is poolOfPools, poolMember { function regaPool(uint _minScore, address _owner); function getPool(uint _level) public constant returns(pool _pool); function loan(int _amount, uint _level) public; }
REGASUBPOOL pragma solidity ^0.4.6; contract regaSubPool is pool, poolMember { function regaSubPool(uint _minScore, address _owner, uint _cases); function getPool(uint _level) public constant returns(pool _pool); function loan(int _amount, uint _level) public; function insert(poolMember _member) public; }
Products
The following hierarchy is used to describe products.

Each distributed financial product (LEVEL 1) is described by a class with the following attributes:
- product parameters and calculator
- product selection rules for the requirements (
needs
) and customer restrictions - business process of contracting (
underwriting process
) - product
support process
business support process
- business process contract termination (
closure process
) risk management rules
scoring cards
accounting rules
- hierarchical pool
pools structure
For each product, the rules for the selection of this product under the requirements and restrictions of the client are determined. The contract signing process describes the sequence of actions that must be performed by the system to enter into a contract with a client. For each client we can calculate the terms of the contract using the parameters of the product and a calculator. For example, for the case of mutual insurance of an animal, depending on whether it is a cat or a dog, the product calculator will calculate the contract value - Lexi Card Standart per month: 333 rubles - a dog, 289 rubles - a cat.
Application implementation on Microsoft Azure
The level of application for mutual pet insurance is implemented in the form of a bot - Lexi Bot, which helps a client to join the Pet Owners Mutual Assistance Club and, after transferring the membership fee, receive up to 80% reimbursement of the cost of veterinary services in case of a sudden illness or an accident with a pet . In addition, Lexi Bot will help the owner to find the animal from the photos on social networks, if it is lost, and organize an online consultation with a veterinarian. To get a Lexi Card Club Card, the owner simply needs to open a dialogue with the robot in Facebook Messenger, Telegram, Slack or on the robot's website, upload his own photo, photo of a pet, get a tariff and transfer money to the smart contract of a Club member.
For reimbursement, it is enough to make an appointment with the vet through the Lexi Bot, re-photograph the animal in the clinic and send the robot photos of the invoice and check. The robot will automatically compare the data received from the owner with the data obtained from the veterinary clinic, and will reimburse from the Fund of the Club to the account of the Club member. The user interface of the Lexi Bot robot is designed using the
Microsoft Bot Framework and allows you to support several channels of communication with clients using a single application server. Animal identification is performed by a neural network based classification algorithm, which allows comparing different photos of the same animal with an accuracy of about 95%.
Below is the solution architecture.

Consider some of the technical aspects of the implementation of the bot using the Microsoft Bot Framework on the Microsoft Azure Bot Service.
Ethereum consortium blockchain
Despite the fact that the architecture described above interacts with the Ethereum bot via the application server, consider a possible way of interaction between the bot and the Ethereum platform directly. First of all, we needed to implement the generation and storage of keys for signing the transaction directly in the bot. To do this, you can use the
eth-lightwallet
module with the
web3
module -
an example on GitHub .
var Web3 = require('web3'); var web3 = new Web3(); var lightwallet = require('eth-lightwallet'); var HookedWeb3Provider = require("hooked-web3-provider"); var keyStore = lightwallet.keystore; var seed = <seed> var host = <ethereum transaction host>; var pswd = <passowrd> var contractAddr = <contract addr>; var abi = <contract interface>
Now we can implement the method of investing in the account of a smart contract member of the club.
blockchain.prototype.invest = function(acc, amount, success) { if(web3 == null) throw new Error('invest: Web3 provider is null'); var contract = web3.eth.contract(abi); var instance = contract.at(contractAddr); var gas = 500000; var gasPrice = web3.toWei(20, "gwei"); var address = acc; var value = web3.toWei(parseInt(amount), "ether"); instance.invest.sendTransaction(value, {gas: gas, gasPrice: gasPrice, value: value, from: address}, function(err, tnx) { if (err) throw err; else success(tnx); }); }; module.exports = new blockchain();
Before testing, you need to access the Azure Ethereum Blockchain Consortium transaction machine (in our case,
regakrlby-tx0
), run
geth
on it and create a contract structure.
Microsoft Cognitive Services
For the initial recognition of the type of pet (cat or dog),
Microsoft Cognitive Services was used . For integration, you can take a
cue from GitHub . Below is a part of the dialogue on getting a photo of an animal.
bot.dialog('/image', session => { if (hasImageAttachment(session)) { var stream = getImageStreamFromUrl(session.message.attachments[0]); captionService.getCaptionFromStream(stream) .then(caption => handleSuccessResponse(session, caption)) .catch(error => handleErrorResponse(session, error)); } else if(imageUrl = (parseAnchorTag(session.message.text) || (validUrl.isUri(session.message.text)? session.message.text : null))) { captionService.getCaptionFromUrl(imageUrl) .then(caption => handleSuccessResponse(session, caption)) .catch(error => handleErrorResponse(session, error)); } else { session.send("Did you upload an image? I'm more of a visual person. Try sending me an image or an image URL"); } });
Result processing:
const handleSuccessResponse = (session, caption) => { if (caption) { session.send("I think it's " + caption); } else { session.send("Couldn't find a caption for this one"); } session.beginDialog('/'); }
Yandex money SDK
To exchange rubles for a cryptocurrency, it is necessary to integrate a bot with a ruble electronic wallet. In our case, the Yandex Money service was selected and the
yandex-money-sdk
module was used. It is worth noting that installing this module from the npm repository using the
npm install yandex-money-sdk
command
npm install yandex-money-sdk
we get a library with an error that needs to be fixed:
Wallet.getAccessToken = function (clientId, code, redirectURI, clientSecret, callback) { var full_url = base.SP_MONEY_URL + "/oauth/token"; request.post({ "url": full_url, "form": { "code": code, "client_id": clientId, "redirect_uri": redirectURI, "client_secret": clientSecret, } }, base.processResponse(callback) ); };
In the prototype of the
getAccessToken
function of the
getAccessToken
module, add the line:
Wallet.getAccessToken = function (clientId, code, redirectURI, clientSecret, callback) { var full_url = base.SP_MONEY_URL + "/oauth/token"; request.post({ "url": full_url, "form": { "code": code, "client_id": clientId, "redirect_uri": redirectURI, "client_secret": clientSecret, "grant_type": "authorization_code" } }, base.processResponse(callback) ); };
The following complexity of integration with Yandex Money arises from the fact that the bot in the Microsoft Azure Bot Service is an
Azure Function . To integrate with
yandex-money-sdk
to the standard
messages
function, you need to add a new HTTP trigger
yandex
. This function will be called by Yandex when passing two-factor authentication. To add a new function to the root directory of the bot, you need to add a new directory in our case,
yandex
in which you need to place the following files:
drwxr-xr-x 5 sevriugin staff 170 Feb 13 12:16.
drwx ------ @ 12 sevriugin staff 408 Feb 13 12: 15 ...
-rwxr-xr-x @ 1 sevriugin staff 258 Feb 15 11:12 function.json
-rwxr-xr-x @ 1 sevriugin staff 1426 Feb 15 11:13 index.js
-rw-r - r-- 1 sevriugin staff 530 Feb 13 21:05 package.json
It is important to correctly describe the new function in the
function.json
file. For an incoming call, you must set the authentication level to
anonymous
. The fact is that Yandex does a callback: it passes the
code
value and if the authentication level is not equal to
anonymous
, then this parameter will be interpreted by the Microsoft Azure Bot Service, and not by your handler.
{ "disabled": false, "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req" }, { "type": "http", "direction": "out", "name": "res" } ] }
For transfer of messages between functions we use service of queues of Azure Storage.
"use strict"; var config = require('../messages/config'); var azure = require('azure-storage'); var queueService = azure.createQueueService(config.azure_storage.account, config.azure_storage.key1); queueService.createQueueIfNotExists('myqueue', function(error) { if (!error) {
Now, in the main function that is responsible for the bot operation, it is necessary to make several calls to bind the e-wallet to the bot (bot user). First of all, it should be noted that the
messages
function should save the state of the dialog with the user before calling
yandex-money-sdk
. To do this, it will be enough to record
session.message.address
in the database and, when you call Yandex, to transfer
session.message.address.id
. This ID will be returned by Yandex when the callback function
yandex
. Unfortunately, the queue service in Azure Storage Service works without blocking when checking for a message in the queue, for this it was necessary to implement polling in the messages function:
function getMessage(error, serverMessages, id, cb) { if (!error) { if(((serverMessages && Array.isArray(serverMessages)) && serverMessages.length > 0) && serverMessages[0].messageText.startsWith(id)) { var code = serverMessages[0].messageText.slice(id.length); cb(code); queueService.deleteMessage('myqueue', serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) { if (!error) {
Why Microsoft Azure
To quickly launch a new product on the market, it is difficult to come up with a better cloud service. It is clear that there are problems and some of the Azure services are still not working as consistently as we would like. For example, Microsoft Azure Bot Service - while it exists in the preview mode, but a huge number of services that are available quickly and in almost any configuration, cover these minor inconveniences. For our project, the availability of blockchain services was particularly important, and
Ethereum Blockchain as a Service fully met our expectations - quick activation and configuration, easy integration with other parts of the project. In total, the project used the following services:
Azure Bot Service ,
Azure Storage ,
Microsoft Cognitive Service ,
Azure Machine Learning ,
Azure Ethereum Blockchain Consortium .
Conclusion
The article was written at the moment when the animal mutual insurance service was tested. The industrial configuration will differ slightly from the architecture described above; in particular, the Azure App Service will be used instead of the Microsoft Azure Bot Service. Our project on
github .
about the author
Sergey Sevryugin - CEO of Bellwood Systems. In the past, DeltaBank CEO and COO DeltaCredit. Currently Sergey is Co-Founder ReGa Risk Manager. In 2015, he started developing solutions on the Ethereum platform, created the first prototype of the product in early 2016: smart contracts in the Solidity language, NodeJS application server, Web App — JavaScript with AngularJS, Swift iOS mobile application. From the end of 2016, I made a prototype of a new product - mutual insurance of animals on Azure using the Microsoft Bot Framework.
We remind you that you can try Microsoft Azure for free
here .