📜 ⬆️ ⬇️

Blockchain platform for trade contracts transactions based on smart contracts


On June 22, 2017, at Blockchain & Bitcoin Conference in St. Petersburg, our blockchain analyst, Marina Smancer, reported on the results of a research project to create an integrated platform for trade financing transactions based on smart contracts.

The 20-minute report format did not allow detailed technical aspects. Therefore, Raiffeisenbank’s access to habrahabr is a great opportunity to talk about our results in all details.

I note that the article is intended for the reader to understand the main aspects of the blockchain technology and the principles of operation of smart contracts. Since the review on each topic is a volume for a separate article, we look forward to understanding the community.

The first part will tell about the case with letters of credit, which we used, and how the platform was designed for the blockchain.
')
The second part is most saturated with technical details: the implementation of the platform (selection and integration of its components) and smart contracts for the letter of credit will be considered in detail. It will also describe step by step the process of settling the letter of credit through smart contracts.

In the third part, a lot of code: separate methods of smart contracts, the specification of its own provider of external requests (oracle) and a bonus for the community: an open API for testing it. Summarizing this section, we will talk about the problems with the components of the platform that we had to overcome.

In the final, let us dwell on the results of the project with the letter of credit, and on what the study of the development of decentralized technologies has shown regarding their use in banking.

We made the decision to highlight in detail our experience with the blockchain. Blockchain is a story about interaction and collaboration. A lot of projects appeared and developed thanks to the efforts of enthusiasts. All technologies are new, and there are enough difficulties with their use. We will be happy if our story becomes a useful source of knowledge.

Gelbplaneten actively participated in the preparation of the article .

Briefly about goals and results


At the end of 2016, the blockchain was in the zone of interest of our R & D department. It took some time to dive into the theory, after which we decided that it makes sense to make a practical implementation.

We considered several areas of the banking business as potential options: from optimizing internal business processes to managing collateral for transactions. In the area of ​​trade finance, we found an immediate interest from corporate businesses and customers, so it was decided to work it out in detail.

Specifically, we decided to stay on the letter of credit. In its simplest form, it implements a fairly simple to understand logic, while covering many aspects of transactions from a selected area.

Letter of Credit: Theory and Business Process
If we abstract from the terms of trade finance, a letter of credit is a form of cashless payment. The Bank undertakes to make a payment in favor of the Seller, if he presents documents on the execution of his part of the terms of the transaction.
A letter of credit solves the problem of lack of trust between the Buyer and the Seller and reduces some of the risks: for example, those associated with the financial condition of the Buyer at the time of settlement.

In a simplified form, the calculation algorithm can be represented as follows:
  1. The parties enter into a contract for the supply of goods, which indicate the letter of credit as a method of payment.
  2. The buyer submits an application for opening a letter of credit to his bank.
    The bank carries out internal checks (for example, the availability of funds in the account). If a positive result, the Bank issues a letter of credit.
  3. After issuing a letter of credit, the Bank notifies the Seller about the opening of a letter of credit under certain conditions. The seller has the right to reject the letter of credit.
  4. When the goods are delivered, the Seller sends the documents specified in the terms of the letter of credit (invoice, trade invoice, etc.) for consideration by the Bank.
  5. The bank checks the documents and with a positive result makes the payment.

In this description, many points are simplified.

The goal of the project is to investigate how technologically ready the blockchain is for real business cases from the field of trade finance. This also applies to the maturity of technology in its pure form, and the ability to transfer the process from corporate business to the blockchain, while maintaining its level of complexity. The second includes both the legal component for conducting transactions and the requirements for the reliability and security of the system.

We focused on open solutions, in particular, public Ethereum was chosen as the blockchain. Other technologies will be discussed in detail later in the article.

As a result, we developed a software platform that combines blockchain, decentralized repositories, external data sources and an API level to internal bank systems into a comprehensive solution. A detailed analysis of the most diverse applications of the blockchain in the bank, which we carried out before the launch of the project, helped design a modular and easily adaptable system. And although we were developing, focusing on a very specific business case (letter of credit), the modularity of the platform allows it to be used for other business solutions that use standardized terms of transactions (stocks, bonds, registration of pledges, exchange derivatives).

Tasks of a research project


As already mentioned, the study was tasked to determine the possibility of implementing trade finance transactions in the existing blockchain-ecosystem. By ecosystem we mean a set of technologies, including as a base both the implementation of the blockchain itself and various add-ons to them: interaction protocols and file exchange, libraries, distributed storages, etc.

In this case, it was intended to use solutions that came out in a stable version or are at the readiness stage close to the implementation. In the course of the study, it was intended to determine the conditions for successful integration of the selected technologies in a single platform together with the bank’s accounting systems, as well as to identify the obvious and hidden problems of such integration.

To determine the necessary functionality for the implementation of the platform, the following initial conditions were set:


The general scheme of the platform and the interaction of its elements


Architecture and interaction of platform components



image

The analysis of the baseline implies the need to use the following functional components:


Considering that the basic calculations and analysis of documents in the realities of today are performed outside smart contracts, only data that they are able to process are transferred directly into smart contracts. The remaining information (justifying and administrative documents) is attached in the form of ordinary (for manual processing) or formalized (for automatic processing) documents signed by a strengthened qualified electronic signature to ensure legal significance.

In this case, the following logic may be assigned to the internal logic of a smart contract:


The following registration information was associated with each user of the platform:


The simplest explanation of the concept of oracles: blockchainhub.net/blockchain-oracles
There was no good article on DFS, I’ll leave a link to the Swarm documentation: swarm-guide.readthedocs.io/en/latest/introduction.html
And Storj: storj.io

Practical implementation


The figure below shows the general scheme of the platform and the main data exchange flows between its functional components (with green marked “alien” components, purple - certified, white - Bank software):

image
In the process of preparing and executing a transaction, the components of the platform interact as follows:


Implementation of smart contracts for letter of credit


It was decided to start designing the platform in parallel with the development of a business case for implementation.

A simplified scheme of the process on the blockchain is presented in the figure, and a detailed description of the process is given below.

image

The participants in the transaction are the Buyer, the Seller and the Bank. The buyer and the seller enter into a contract for the provision of certain services or goods, and the fact of their provision can be identified automatically. For example, if a letter of credit is opened for settlements when transferring ownership of real estate, shares, shares, etc., information will be checked in submitted documents against information in external sources (for example, in the unified state register of real estate). Further operational support of the transaction is carried out through the Platform.

  1. The buyer creates a smart contract "Application for letter of credit" (hereinafter referred to as "Application"), which receives the status of New .

    The address of the Application is placed in the Mailboxes of the Buyer and the Bank.

  2. The buyer attaches to the Application a formalized document describing the details of the transaction and the necessary non-formalized documents, for example, a scanned copy of the contract for which the letter of credit is opened.

    After attaching all the necessary documents, the Buyer transfers the Application to InBank status.

  3. The bank automatically (for formalized ED) or with the use of experts (for unformalized ED) checks the transaction. For example, a request is sent to the bank systems for checking client details in the client data catalog, for confirming the account balance and reserving funds for other checks (for example, checks for compliance, currency control, etc.)

    If the Bank has any claims regarding the content of the transaction or the attached documents, it refuses to accept the Application and establishes the status Rejected .

    If the Bank agrees to accept the application for execution, the Confirmed status shall be established.

  4. On the basis of a formalized ED describing the transaction, the Bank’s accounting systems perform the necessary manipulations (transfer of the amount of the letter of credit from the client account to the “coverage account”, charge-off, etc.)

    The Bank issues a smart contract "Letter of Credit" (hereinafter referred to as Letter of Credit), which receives the status of New .

    The address of the letter of credit is placed in the mailboxes of the Bank and the Seller.

    The Letter of Credit preserves the address of the Application, which allows you to automatically “mirror” the key statuses of the Letter of Credit on the Application, so that the Buyer can monitor the status of the transaction.

  5. The Bank attaches to the Letter of Credit a formalized ED (automatically generated from the conditions of the Application) with a description of the details of the transaction, other necessary documents and establishes its Released status.

    The status of the L / C Application is also switched to Released .

    When switching to Released status, the Letter of Credit automatically places two requests into the External Request Provider's queue:

    • Request to control the expiration of the Letter of Credit (triggered when the current date exceeds the term of the Letter of Credit)
    • Request to wait for the execution of the contract (the specific request template is determined by the content of the transaction)
  6. The seller, after studying the issued Letter of Credit, may refuse to accept it: in this case, he transfers it to Invalid status, the letter of credit is canceled, and further manipulations with it become impossible.

    The status of the L / C Application is also switched to Invalid .

  7. If the event of expiration of the Letter of Credit is the first to be triggered, then it receives the status of Overdue and further manipulations with it become impossible.

    The status of the L / C Application is also switched to Overdue .

    In this case, automatic orders are sent to the accounting systems of the Bank to initiate transactions that correspond to the cancellation of the letter of credit (return of coverage, termination of the bank’s obligations, etc.)

  8. If the first event is the execution of the contract (or when the Seller attaches the ED, stipulated by the conditions of the Letter of Credit) - the Letter of Credit switches to InBank status. When switching to InBank status, the Letter of Credit automatically places a request in the External Request Provider's queue to wait for payment and removes the expiration control request from the queue.

    The Bank, on the basis of a formalized ED attached to the Letter of Credit, makes a payment in favor of the Seller by submitting the order to its settlement system and executing the Payment outside the blockchain (information on the actual execution of the Payment is returned to the blockchain).

  9. After the execution of the payment execution event, the Letter of Credit switches to Closed status.

    The status of the L / C Application is also switched to Closed .

  10. The transaction is completed.

Selection of platform components


When choosing the functional components of the platform, we focused on open solutions (Ethereum, Swarm, Storj). This is due to the following advantages:


image
Thus, the choice was made in favor of the following implementations:


Infrastructure


To deploy the necessary components:


2 servers were allocated.

On the first server, the Ethereum node of the base blockchain of smart contracts was deployed. Initially, the Ropsten test network was used as the base blockchain, but in the final stages we switched to a more stable Rinkeby. The reason for this was the March incident with the DDOS attack on Ropsten , during which several days there were problems with the addition of transactions.

On the second server, the infrastructure was deployed to work with the files:


In addition, for reasons of convenience, the integration core of the platform was deployed there.

The provider of external requests was deployed on each of the servers and could, if necessary, run on any of them.

The UI application could be launched either on any of the servers, or use a special proxy protocol for working over the Internet.

Integration of components


Ethereum


Integration with the Ethereum blockchain was carried out using the RPC API JSON-RPC , Management-APIs .

There were no technical problems with its use.

As an external arbitration resource, ropsten.etherscan.io or rinkeby.etherscan.io was used , depending on the test network used.

Swarm


Integration with Swarm was carried out using the HTTP API: Swarm-guide , gist.github.com .

An HTTP PUT / bzz request was used to upload the file to SWARM : $ PATH $ ($ PATH $ is the path to the downloaded file).

in response to which came the 16th identifier of the manifest of the file that was used to extract it from the SWARM.

To retrieve a file from SWARM, an HTTP GET / bzzi request was used: / $ MANIFEST $ / ($ MANIFEST $ is the hexadecimal identifier of the manifest of the extracted file).

There were no problems with uploading / uploading files.

Unfortunately, no external monitoring tool (such as Etherscan for Ethereum) was found for Swarm, which in some way made it difficult to evaluate the success of file manipulations.

Storj.io


Integration with Storj using the proposed API by the developer turned out to be extremely difficult and inconvenient. As a result, the Storj node console was used to work with files.

To download the file, use the storj upload-file $ BUCKET $ $ PATH $ command (where $ BUCKET $ is the “basket” identifier, and $ PATH $ is the path to the file being downloaded).
Upon successful upload, the identifier of the uploaded file was given in response.

To upload the file, use the storj command download-file $ BUCKET $ $ FILE $ $ PATH $ (where $ BUCKET $ is the “basket” identifier, $ FILE $ is the file identifier, and $ PATH $ is the path to the local copy of the file).

The peculiarities of Storj include the fact that more than one file with the same name cannot be put into one “basket”, which requires the use of a mechanism for generating unique names when loading.

You can use https://api.storj.io as an external arbitration resource, which supports the API.

CryptoARM


Integration with CryptoARM was carried out using the COM-service it provides. For quick implementation, integration scripts were written on vbs.

External Request Provider


The interaction of smart contracts with the External Requests Provider is performed as follows.
image


Detailed description of the implementation of the query provider
Before describing the process, it is necessary to define some basic concepts:
  • The request identifier is a 32-character value (64-digit hex), which contains the first 20 (40 hex) characters of the contract address, and then arbitrary information that allows the contract to build a proper response to the request when it receives a response.
  • The response identifier is a unique 32-character value (64-digit hex), which allows the External Request Provider to uniquely identify the response message.


To use the External Request Provider, the smart contract must support a special interface consisting of the following methods: GetExternalRequest , SetExternalResponse and CheckExternalResponse .

The order of interaction of a Contract that wants to receive an “outside” answer to a certain request with the External Event Provider is as follows:
  1. Contract by transaction through the AddRequest method sends the request identifier to the smart contract RequestsQueue , whose address is fixed.
  2. The external request provider (PRP) periodically polls the RequestsQueue smart contract via the GetRequests method and gets the current list of requests to be executed.
  3. Upon receipt of a new request, the PRS through the GetExternalRequest method refers to the Contract and receives the request parameters by the request ID:
    • Periodicity of request execution (for example, “DAILY 10:00” or “PERIOD 20”)
    • Request pattern identifier (for example, "CALENDAR" or "DADATA_NAME_EXISTS")
    • Additional parameters, if required (for example, the name of the organization for the “DADATA_NAME_EXISTS” template)
  4. In the order of general management of the PVZ queue with the periodicity specified for this request, it polls external resources in accordance with the request template and the attached parameters.
  5. If, according to the logic embedded in the template, it is considered that the response to the request has been received, the EAP transmits it to the Contract via the SetExternalResponse method in conjunction with the request identifier and the response identifier.
    In this case, the Contract must perform the appropriate processing of the received response and record the response identifier for further control.
  6. Next, the PFH requests from the Contract via the CheckExternalResponse method whether the response was received and processed and what the fate of the corresponding request was.
    The contract may offer one of the following options:
    • FAIL - no response, not processed or incorrect - you must repeat the request and send the response
    • REPEAT - the answer is accepted, it is necessary to continue the execution of the corresponding request with the same parameters
    • DELETE - the answer is accepted, the request must be removed from the queue.
    • DELETE_ALL - the answer is accepted, it is necessary to delete from the queue all requests received from this Contract
  7. In the event that in the previous paragraph the Contract sent the answer DELETE (DELETE_ALL) - the PVZ deletes the request (s) from the RequestsQueue smart contract via the DeleteRequest method.


If necessary, the Contract itself can delete requests that have become unnecessary, using transactional methods DeleteRequest of the smart contract RequestsQueue.

Here it is necessary to pay attention to the fact that the query template can use a rather complicated logic to interpret the response receiving event. For example, the answer can be considered as received only if the request gave only a certain result - and only for this result will be sent a response to the Contract that ordered the request. All other results will be ignored and the query will continue to be executed. Similarly, a template may involve referring to several external sources at once and receiving from them a specific combination of private answers.

To exclude "unauthorized" sources of requests, a smart queue contract contains a managed list of addresses that must be source (txn.origin) addresses of transactions queuing the request.

Description of Contract Methods Requests Queue



AddRequestAdd request to queueInput parameters:
  • Request ID (bytes32)

DeleteRequestRemoving a request from a queueInput parameters:
  • Request ID (bytes32)
CheckRequestCheck for a request in the queueInput parameters:
  • Request ID (bytes32)

GetrequestList the queue request IDsNo input parameters.
Output Parameters:
  • List of identifiers (bytes32 [])

AddbankAdd an address to the list of authorized addressesInput parameters:
  • Address

CheckBankCheck whether the address in the list of authorized addressesInput parameters:
  • Address



Description of required interface methods for Contracts



GetExternalRequestGet query parametersInput parameters:
  • Request ID (bytes32)
    Output (as a bytes32 [] array):
  • Timing specification (when or how often the request should be executed)
  • Name of the query implementation pattern
  • Request parameters (may be missing or there may be several)

SetExternalResponseAccept the response to the requestInput parameters:
  • Response ID (bytes32)
  • Request ID (bytes32)
  • Response data (bytes32 array)
CheckExternalResponseVerify that the response to the request was processedInput parameters:
  • Response ID (bytes32)
  • Request ID (bytes32)

Output:
  • Response processing status
  • For response processing status, one of the following options is possible:
  • FAIL - no response was received or processed.
  • DELETE - response received and processed, delete request from the queue.
  • DELETE_ALL - response is received and processed, all requests from this contract are deleted from the queue
  • REPEAT - response received and processed, continue to execute the request



Implementation example


Below is an example of the implementation of the methods in the contract.
The contract involved calls for two external requests — a date delay (the OVERDUE pattern) and an organization’s registration check (DADATA_EXISTS_WAIT).
Code that is not directly related to working with external queries is excluded.

Description of stored variables


bytes32 Status ;
bytes32 ExpireDate ;
bytes32 OrgName ;
address Queue ;
bytes32[] Request_1 ;
bytes32[] Request_2 ;
bytes32 Request_id_1 ;
bytes32 Request_id_2 ;
bytes32 Response_id_1 ;
bytes32 Response_id_2 ;


Contract constructor


function SomeContract(..., bytes32[] logics)
{
Owner =msg.sender ;
ExpireDate=logics[0] ;
OrgName =logics[1] ;
Status ="New" ;
Queue =0xd9b076d0b559f70782f379582bd3d54b85fc42cb ;
Request_1.length= 3 ;
Request_1[0] ="DAILY 00:10" ;
Request_1[1] ="OVERDUE" ;
Request_1[2] = ExpireDate ;
Request_2.length= 3 ;
Request_2[0] ="PERIOD 10" ;
Request_2[1] ="DADATA_EXISTS_WAIT" ;
Request_2[2] = OrgName ;
}

Registration of requests in the queue (in case of transition of the contract to the appropriate status)


function SetStatus(bytes32 status_, ...)
{
address self_addr ;
Status=status_ ;
if(status_=="Released_") {
self_addr=this ;
Request_id_1=bytes32(bytes20(self_addr)) | "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x001" ;
Request_id_2=bytes32(bytes20(self_addr)) | "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x002" ;
Queue.call.gas(0x30000).value(0)(bytes4(sha3("AddRequest(bytes32)")), Request_id_1) ;
Queue.call.gas(0x30000).value(0)(bytes4(sha3("AddRequest(bytes32)")), Request_id_2) ;
}
}

Get query parameters


function GetExternalRequest(bytes32 request_id_) constant returns (bytes32[] retVal)
{
if(request_id_==Request_id_1) return(Request_1) ;
if(request_id_==Request_id_2) return(Request_2) ;
}


Accept the response to the request


function SetExternalResponse(bytes32 response_id_, bytes32 request_id_, bytes32[] response_)
{
if(tx.origin!=Owner) return ;
if(Status!="Released_") return ;
if(request_id_==Request_id_1) {
Response_id_1=response_id_ ;
Status ="Overdue__" ;
}
if(request_id_==Request_id_2) {
Response_id_2=response_id_ ;
Status ="ToBank___" ;
}
}



To the benefit of the community


For those who want to try the technology of tracking external events and working with oracles and providers of external requests, we have deployed on the Ethereum Rinkeby network:


Calendar oracle


The Oracle calendar is located in the Rinkeby test network at 79548a65e3ce179ec8d208c22ee84435dc34058f and gives the current calendar date in Moscow in the format YYYY / MM / DD.

An example of an appeal to the Oracle:

contract Check_request
{
Calendar Oracle ; // -
bytes32 Date ;
function Check_request()
{
// -
Oracle=Calendar(0x79548a65e3ce179ec8d208c22ee84435dc34058f) ;
//
Date=Oracle.GetDate() ;
}
}

//
//
//
contract Calendar
{
function GetDate() constant returns (bytes32 retVal) ;
}


External Request Portal


The queue of the smart contract of the External Requests Portal is located on the Rinkeby test network at d9b076d0b559f70782f379582bd3d54b85fc42cb .

The protocol for interacting with the External Request Portal is described above. The following query templates are currently open to the public:


To access the External Requests Portal queue, you must tell us (in a comment or in a personal note) the address of the Ethereum account from which queuing transactions will be sent.
It is advisable to apply 0.1 Ether to the transaction (this is free, we are in a test network) to debug the mechanism of paid services. In Rinkeby, you can get air only with the help of a faucet , due to the lack of mining opportunities due to the PoA protocol.

Some comments on the experience of integrating third-party components.


Ethereum


When implementing paid services for smart contracts, it would be extremely useful to be able to execute transactions at the expense of the “accepting” smart contract, and not at the expense of the transaction initiator (of course, if the smart contract is in any way agreed to this - for example , due to the mechanism of trusted addresses or something like that). This will greatly simplify the mechanisms for calculating the “services”, since the initiator of the transaction also pays for the execution of the smart contract method, the cost of which (execution) cannot always be determined in advance.

Ethereum solidity


The development of non-trivial scenarios that interact with the "outside world" is greatly complicated by the lack of built-in functions for working with strings - concatenation, search, and fragment cutting.

Ethereum swarm


It is highly desirable to have, like the main Ethereum, a mechanism for confirming the download of a file to the Swarm (its distribution to other nodes) is similar to the confirmation of a transaction. For it is unclear whether the file is saved somewhere outside your node or not.

Building from sources and deploying a Swarm node for Windows is an extremely trivial task. The developers have tested and prepared documentation only for linux and OSX, which they honestly admit.

Storj.io


Extremely difficult to use, too detailed API. For simple integration, it is desirable to have an “integrated” API, similar to that implemented in Ethereum Swarm - put the file, extract the file.

Missing multi-user file access. That is, the file can be read only from under the account details under which it was recorded. This leads to the fact that for the organization of multi-user file sharing it is necessary to actually “disclose” your account details, which, given the payment for the service, is not a good practice.

The findings of the study


At present, the components of the blockchain ecosystem that are productive or close to production can fully realize the functionality necessary to support the execution of trade finance transactions.

Of course, there are certain non-technical issues that need to be resolved in order to be able to talk about the implementation of large projects for trade finance (and indeed many areas close to it in terms of objectives) on the blockchain.

Firstly, the legal issues of transactions carried out through the blockchain, including the legal status of entries in the blockchain.

Secondly, now in Russia, the use by banks of public blockchains is actually blocked by the position of the regulator in relation to cryptocurrencies: the ban on their use makes it impossible to pay a fee for adding a transaction (transaction fee). Transactions in this case are needed not for settlement, but as a way to create smart contracts and interact with them.

Thirdly, it is necessary to standardize the formats of electronic documents for the possibility of their automatic verification.

Finally, the blockchain ecosystem needs to be saturated with sources of external events: oracles to various registries, information systems of banks and transport companies, etc. This will help eliminate the need for manual entry of external events and make the execution of smart contracts truly automatic and depersonalized.

It becomes obvious that in such projects the technical side is not the most significant part of the work. Now that the development has been completed, we continue to work with lawyers and work with other banks on approaches to defining unified requirements for electronic document formats to automate the verification of their content.

The case with the letter of credit allowed us to get both the technical base and the experience of implementing decentralized applications in the field of TF. Now we are looking at several areas in which we are interested in making a pilot, we will tell about them later.

Stay tuned!

Source: https://habr.com/ru/post/332756/


All Articles