How did we do the first blockchain letter of credit transaction at Alfa Bank

A few months ago, Alfa-Bank and S7 completed a letter of credit transaction using the blockchain. If you have not seen it, then please here .

I think many have heard or read about blockchain - there is a lot of hype around the technology and, as usual, it all came to us with some delay. But all the same, it has come and now many people want their blockchain in their products. Perhaps powerful marketing will lead to the “winter” in yet another technology, or perhaps we will all end up in one big blockchain. All the same, let's deal with technology and do it using the Letters of Credit product we created as an example.

This is our interface:

Technically, we did:

  • Front-end application for customers
  • Front-line application for a bank employee
  • API for interacting with internal banking services, saving documents to the database and interacting with Ethereum
  • Contracts for creating letters of credit and operations on them
  • Infrastructure squats to a minimum

All this on js: react, redux, node. Solidity contracts. Applications in Docker containers, and the client for the Ethereum network - Parity took from here . By the way, we picked it up on a separate machine, since it consumes resources quite actively, but as it turned out later on, we added a whole bunch of problems to this. In general, creating applications and fussing with the infrastructure took much longer than working on contracts. But there are enough articles about fronts and infrastructure, so let's talk about contracts.

Despite the hype, the most common question remains: why do you need blockchain and smart contracts? Many see the potential in technology, and even more people are skeptical, but we are just curious. But there is a problem - to find a business case in order to apply the blockchain and not be pulled over the ears. Therefore, we went the simple way and were inspired by the idea of ​​Barclays, which were the first in the world to make Letters of Credit on the blockchain together with Wave. In addition, the product that we made was needed without the blockchain, and then it turned out and do some research.

How can this technology be applied? It’s good when you can use one of the available cryptocurrencies to make money circulation, but, as you know, we are prohibited by law from working with cryptocurrencies, even if it is not actually a currency, but, for example,colored coins , so we did not transfer any equivalent to real money inside the network. The next idea is to use the blockchain as an “immutable” database (about immutability and just remember), the state of which is validated and saved by network participants, then you can create a dependence of your business operations on a certain state inside the blockchain and use it as another regulator, however ironic it may sound. The advantage of adding such a “switch” to your system is the openness and accessibility of its state, anyone who can download and run the client of the network your application is working with can find out what state the “switches” are now, provided that this person knows how to find them using the necessary identifiers. Accordingly, the more logic goes to the blockchain, the more open the process will be for customers, and the closer your application will be to the DAPP concept. Now it’s the turn to choose which network to use, and there are a lot of them, you can read the analysis of six months ago about some of the popular ones . Speaking of popular ones, many have heard about Bitcoin, but not everyone knows that it has a scripting language, and some concepts are quite implemented with the help of it. However, new cryptocurrencies are appearing, focused on solving Bitcoin problems, and one of them is Ethereum . The decision to use Ethereum was not made because of the availability of smart contracts, but because of the combination of improvements described in White-Paper.

But before you dive into writing the logic we need on the Ethereum side, let's look at the business process. During the transaction, the so-called irrevocable covered letter of credit was opened and executed. Behind these obscure terms is a fairly simple procedure in which 3 parties participate: the buyer, seller and bank: the

Buyer of services fills out a letter of credit application form, which indicates the details of the Seller and the conditions of the transaction: amount, terms and required documents.

The bank accepts this application and, if all checks are successfully passed, opens a letter of credit. Immediately removes the amount indicated by him from the Buyer. Now it's Seller’s turn. He must send the bank the documents that the Buyer expects from him. These documents are proof that he performed his services. For example, an invoice that certifies the actual shipment of goods. The bank checks these documents. If all is well, then the letter of credit is executed, the money is transferred to the account of the Seller. As a result, everyone is happy, including the bank, which takes its commission for all these manipulations.

In our case, it was not the most difficult letter of credit - all operations were carried out within the same bank, since both the buyer and seller were our customers. At this stage, the partial execution of the letter of credit was not necessary, so the process itself turned out to be quite simple.

What are Ethereum smart contracts? These are just programs executed by EVM (Ethereum Virtual Machine). Contracts can be written in several languages, for example, solidity. All supported languages ​​are Turing-complete, but this does not mean that you can do everything on EVM. The execution of your code should be monitored, as it will be performed by other network participants, so you will pay money for execution - wei ( ether denomination) For the code written in your contract to start executing, you need to create a transaction. These transactions are transferred to the miners - those network members who are engaged in its support. They add new blocks with valid transactions to the blockchain (the explanation is intentionally simplified, more details can be read here and here ). If the smart contract is specified as the transaction destination, the miner executes the code of the function that is called in the transaction, this costs the miner's computing resources, you must pay for their use.

Creating a smart contract is also a transaction, but with an empty addressee, saving the contract to the next state of the network will require resources that also need to be paid. To make the payment process more open (turn it into a marketplace), the concept of an intranet resource - gas - was introduced (you will need a lot of gas, so you are probably a protoss) Gas is not a denomination of ether, but any computing operation and data storage has a price tag in units of gas. In the transaction you want to do, the startgas number is indicated - how much gas will it cost to execute, and you set the cost of one gas unit (gasprice) yourself, so by indicating a higher gasprice you increase the chance of including your transaction in the block, although it’s worth saying that most miners do not select transactions, which means that you can leave the default value. You can calculate the cost of your contract in a web editor .

It seems that in order to do something at all, you need to pay, but if you don’t have a friend who presented you with ether for the new year, you can set the client to a private chain, you can enter cheat codes for millions of ethers and test your creations. In general, it’s always better to do this.

Parity has the ability to run with a private chain . Although there is a simpler way - use the simulator . There are also frameworks that simplify writing smart contracts and applications that interact with them, for example, truffle or embark. I have no particular preferences, but on this project I worked more with embark. Although truffle allows you to compile contracts - to create a js binding on calling up functions of contracts, it is TDD-oriented and by default creates a metacoin project (how to make your own currency inside Ethereum), therefore, to start understanding, I would recommend it.

It seems to be simple, take the framework in production too, but you understand that the price of an error in a contract can be very expensive, for example, the first Ethereum hard fork, when the problem was in contracts written for the DAO, this problem was discussed at the crowdsale DAO stage, but in the end, all this resulted in a hard fork and the creation of Ethereum Classic (very common - the DAO hack was removed with a crutch, but many people were for the option: they screwed up — their fault, the platform should not save those who screwed up if the platform performs its functions correctly), I advise you to read more . Therefore, before translating the logic of your applications into a decentralized network, it makes sense to read the guide .

We added blockchain dependency after the second and fourth points in the business process. After confirmation of the letter of credit by the bank employee, the object of the letter of credit is created in the first contract.

struct LetterOfCredit {
    bool init;
    bytes32 hash;

These structures need to be stored somewhere, preferably in something like a key-value store, in solidity there are:

mapping (bytes32 => LetterOfCredit) lcs;

Now, using a 32-byte key, we can access the object of the letter of credit or create it. In our case, the key will be md5 from three fields - buyer's TIN + seller's TIN + Name and contract number (yes, this is one field). As you recall, md5 is a 128-bit hash function, so digest is 16 bytes, if represented as characters, we use hexadecimal, respectively, one character encodes 2 ^ 4 - half a byte (called nibble), 16 bytes turn into 32 nibbles, 32 characters, when transmitting these characters as a line from a third-party client, it is logical to assume that they will be encoded in one byte, which means 32 bytes (poof 16 bytes became 32). Because Since we keep working with our contracts from clients with web-view, we have to put up with the fact that they will enter exactly the line there, therefore md5.not worth using , you can increase the resistance to attacks by adding an additional hash layer in front of md5 and use for example SHA-3.

This is how the functions of the first contract look if you connect to it through the Parity client network (these are functions that do not change the state of the blockchain - accordingly they are free)

What these functions do, the name should be clear. The second field in the checkData function is the hash from the date of the letter of credit creation + closing date + amount.

Then we need to realize the closing of the letter of credit and everything can be done inside the same contract, but since there are development plans in the future and in the next stages it will be advisable to use a number of contracts - we decided to close in another contract, so we need to somehow transfer the object, for this there is an opcode call, for example:"create(bytes32,bytes32)")), id, lcs[id].hash);

From this line it becomes clear that we simply call the create function with certain parameters for nextContract. Now, in order to be able to call the create function only the first contract remains, you need to restrict access to certain functions, this can be solved by adding a modifier

modifier restricted() {
    if (msg.sender == owner) _;

or a separate contract from which you can inherit:

contract Owned {
    function Owned() { owner = msg.sender; }
    address owner;
    modifier restricted {
        if (msg.sender != owner)

where the address owner will be initialized when the address creates the contract.

Now the second contract can be created from the first contract (using just new NextContract ()), marking the necessary functions of the second contract with the restricted modifier, because in this case msg.sender will be the first contract, and not your account that pays for the transaction, its address will be in tx.origin ( example of contracts ). This is because the call of one contract to another occurs via messages , while all execution is paid from the original gas in the transaction.

You can also create a function that allows you to change the addresses of the following contracts in the chain, thereby changing the logic of your business process.

When the letter of credit falls into the second contract, the status field is added to its structure, and by default it will be open.

After the seller submits the relevant documents that the bank employee will verify, the second contract will call the function of closing the letter of credit, access to which is restricted by another modifier, in this case it is not the first contract, but only the account (address) that has rights to close letter of credit. If the id existing in the second contract is transferred to the input of the closing function and the letter of credit obtained using the mapping contains a hash field identical to that transferred to the function input, then the letter of credit will be closed, i.e. the value of the “status” field in the letter of credit structure will change.

Let's look at this through Parity, connected to the second contract:

Here, in addition to the functions, the results of their work are visible - under the retVal field.

All these operations are carried out by three transactions:

  • txCreate - creation of a letter of credit
  • txForSend - sending it to the second contract for closing
  • txClose - closing a letter of credit

How it looks for the user:

(transactions from the screenshot on a private chain)

You can see the public of the transaction on a special search engine (etherscan) . Our etherscan contracts: first and second .

As you understand, now in smart contracts it is implemented simply saving hashes from some fields of a letter of credit, its status and checking information at closing. Yes, we had more ideas of what can be transferred to the side of the blockchain, and, perhaps, it will be possible to realize them in the future. In this project, we spent most of the time creating applications: front-end and api. Although there is an opinion that this happens in many projects related to the blockchain.

If you get to the launch of your project with a blockchain and will raise your client for the network, then you may run into problems due to inaccurate time, for example, you will not be able to access the Parity web interface. Therefore, I advise you to immediately set up NTP time synchronization on the server where you will run Parity, you can check your time using the watch , if you have an incorrect one, then synchronize too.

If you have a microservice architecture and an application that requires a connection to a network client is not located on the same server as the client, then errors will be returned to requests from your application. Because by default Parity (client) listens only to localhost. We solved this problem by putting Nginx in front of it in order to correctly proxy requests and additionally bypass CORS:

location / {
proxy_set_header Origin;

this should save you a little nerves and time (other ways to defeat this problem with the launch options did not work for us).

And yet, why might you need a blockchain? Ideally, if you need to create a system of information exchange between participants, independent of the level of trust between them, then this is what you need. Such a task becomes feasible because each client of the network has a private / public key combination, therefore a digital signature is implemented, for example: a transaction is signed by the private key of the account that created it. As I understand it, a CEP (Qualified Electronic Digital Signature), which has legal value, is an ordinary digital signature, in the keychain is a private key, and in the registry where you brought your passport - public, sign the hash of your documents with a private key. In Ethereum, you can simply create a hash transaction in the “date” field, which will be signed by your private key; therefore, you can check that the transaction was created by you. It turns out that you have an authorization mechanism, the same as in CEP, and all? Not really, when all participants in the transaction are authorized, the problem may be the execution of the algorithm of the transaction itself, the guarantor is usually the institution through which you intend to carry out the transaction, here the transaction through the platform for smart contracts starts to win. Because the logic prescribed in smart contracts does not change after they have been created and are in the public domain, and its execution is guaranteed by all network participants who mine blocks. How to apply it? For example, you can simply transfer some of your processes inside the network if there is no trust between the participants in these processes. Also in this system, you can create decentralized communities with a common capital, where proposals for the use of resources will be decided by a quorum of participants. Now the creation of products using the blockchain is still developing as a direction, so be prepared for the fact that best-practices will change.

So, the easy level of using blockchain is that you want to record transactions in your business process in an external resource so that you can then show transactions about these operations and refer to smart contracts that will return formal confirmation of the operations performed (we are on easy).

Medium level - you authorize all participants in the transaction and save information about the documents they created (you probably already guessed that it was a hash) in the blockchain using smart contracts. Since you do this through a transaction on behalf of clients, the transaction is signed with a private key, checked through a public key - you receive a signed electronic document (analogue of CEP), accordingly, all further operations with these documents will also be signed and you can create an analog of electronic document management within the network, of course, sending the documents themselves inside the blockchain will be quite an expensive operation, so it is advisable to use hashes with which to check the electronic document transferred in another way.

Formal criteria for conducting transactions are best implemented in separate contracts, in this case this can already be done, because all elements of the transaction are inside the blockchain. You get a platform for creating and conducting transactions, where all transactions are signed and the schemes for conducting transactions are unchanged. Of course, not everything is so perfect, in this concept there are many questions that need to be answered, and many of them are not technical, but legal.

Fun level - there are a lot of articles that consider the potential of technology and what can be done with it . Now there is a certain interest in technology, so startups in the field related to the blockchain can find the necessary investments .


The main problem of using blockchain within projects remains the legal side of the solution. Perhaps with the support of German Gref, something will change in 2017, but at the moment, the use of technology is very limited. In such projects, lawyers are necessary from the very beginning. There are still no clear rules for cryptocurrency regulation in the Russian Federation, so the presence of such a person from the moment of laying the foundations and the brainstorm of air locks greatly reduces the risk of potential problems. The blockchain part is the backend of your project, so you can start writing your decentralized application from the front, you will spend most of the time there anyway.

We managed to create a simple solution that preserves the results of our activities on the blockchain, this is far from how the technology can be used in principle, but we are only at the very beginning.

Now there are many hypotheses and ideas on how to use the blockchain. What of this can be implemented in accordance with the legislation of the Russian Federation? This question can be answered only after the adoption of more laws governing the use of the blockchain.

What else to read:

Writing more robust smart contracts
Understanding oracles

More about Ethereum:

Yellow paper
Ethereum trie

Also popular now: