A few months ago, Alfa-Bank and S7 made a letter of credit transaction using blockchain. If you have not seen, then I ask
here .

I think many have heard or read about the blockchain - there is a lot of hyip around the technology and, as usual, it all came to us with some delay. But it still came, and now many people want a blockchain in their products. Perhaps powerful marketing will lead to “winter” in another technology, and perhaps we will all end up in one big blockchain. Let's all deal with the technology and do it on the example of the product Letters of Credit, which we created.
This is our interface:
')

Technically, we did:
- Customer front-end application
- Front 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 conducting transactions with them
- Infrastructure Squat Minimum
All this on js: react, redux, node. Contracts for solidity. Applications in Docker-containers, and the client for the Ethereum network - Parity was taken
from here . By the way, we raised it on a separate machine, as it is quite actively consuming resources, but as it turned out later - with this we added a bunch of problems to ourselves. In general, creating applications and fussing with the infrastructure took much more time than working on contracts. But about the fronts and the infrastructure of the articles is enough, so let's talk about contracts.
Despite the HYIP, the most frequent question remains: why do you need blockchain and smart contracts? Many see the potential in technology, and even more people are skeptical, we are just curious. But there is a problem - to find a business case in order to use the blockchain and not attract by the ears. Therefore, we went in a 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 the Wave company. In addition, the product that we made was needed without the blockchain, but it also turned out to do some research.
How can this technology be applied? It’s good when you can use one of the available cryptocurrencies to generate cash flow, but as you know, we’re not allowed to work with cryptocurrencies, even if it isn’t actually currency, but, for example,
colored coins , so we’re not equivalent to real money. did not carry inside the network. The next idea is to use the blockchain as an “immutable” database (about immutability and
just remembering ), the state of which is validated and maintained by network members, then you can create a dependency of your business operations on some state inside the blockchain and use it as another controller, ironically it sounded. The advantage of adding such a “switch” to your system is the openness and availability of its state, anyone who can download and launch the client of the network from which your application is working can find out what state the “switches” are in, provided that this person knows how to find them with 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 concept of
DAPP . Now the turn comes to choosing which network to use, and there are quite a few of them, you can read an
analysis of six months ago about some of the popular ones . Speaking of popular - many have heard about Bitcoin, but not everyone knows that there is a scripting language in it, and some concepts are fully realized with the help of it. Nevertheless, there are new cryptocurrencies, focused on how to solve the problems of Bitcoin, and one of these -
Ethereum . The decision to use Ethereum was made not because of the availability of smart contracts, but because of the cumulative improvements described in White-Paper.
But before plunging into writing the logic we need on the Ethereum side, let's take a look at the business process. During the transaction, the so-called irrevocable covered letter of credit was opened and executed. Behind these incomprehensible terms is a rather simple procedure, in which 3 parties are involved: the buyer, the seller and the bank:
The buyer of services fills in a questionnaire for opening a letter of credit, in which he specifies the details of the Seller and the terms of the transaction: the amount, terms and documents required.
The bank accepts this application and, if all checks are successfully completed, opens a letter of credit. Immediately removes from the Buyer the amount indicated by him. Now it's Seller's turn. He must send the bank the documents that are waiting for him from the Buyer. 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. In the end, 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 transactions were carried out within the same bank, since both the buyer and the seller were our clients. At this stage, the partial execution of the letter of credit did not have to be implemented, 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, on 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, since it will be executed by other members of the network, so you will pay money for execution - wei (
denomination ether ). In order for the code written in your contract to start running, you need to create a transaction. These transactions are transferred to the miners - those network participants who are engaged in its support. They add new blocks with valid transactions to the blockchain (the explanation is intentionally simplified, you can read more
here and
here ). If a smart contract is specified as a transaction addressee, the miner executes the code of the function that is called in the transaction, it costs the miner's computing resources, and you must pay for their use.
Creating a smart contract is also a transaction, but with an empty recipient, saving the contract to the next network state will require resources that must also be paid. To make the payment process more open (turn it into a marketplace), the concept of an intranet gas resource has been introduced (you will need a lot of gas, so you, apparently, are a
protoss ). Gas is not a denomination of the ether, but any computational operations and data storage have a price tag in units of gas. In the transaction you want to do, the number of startgas is indicated - how much gas it will cost to execute, and the cost of one unit of gas (gasprice) you assign yourself, therefore, indicating a higher gasprice, you increase the chance of including your transaction in the unit, although you should say that most miners do not select transactions, so you can leave the default value. You can calculate the value of your contract in the
web-editor .
It seems that you have to pay at all to do something, but if you don’t have a friend who gave you a broadcast for the new year, you can set up a client for a private chain, you can enter cheat codes for millions of ethers and test your creations. In general, it is always better to do so.
Parity has the ability to start with a
private chain . Although there is a simpler way - use the
simulator . There are also frameworks that simplify the writing of 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 js-piping on calling contract functions, is focused on TDD and by default creates a meta-coke project (how to make your currency inside Ethereum), therefore, I would recommend it to start to understand.
It seems to be simple, take the framework and in production, but you understand that the price of a mistake in the contract can be very expensive, for example, the first hardfork Ethereum, when the problem was in contracts written for DAO, this problem was discussed at the stage of the crowdsale DAO, but in the end it all turned into hardfork and the creation of Ethereum Classic (very general - the DAO hacking was removed with a crutch, but many people were for the option: they nagged - their fault, the platform should not save those who nakosyachil 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 have added blockchain dependency after the second and fourth points in the business process. After confirmation of the letter of credit by an employee of the bank, 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 or create an item of credit. In our case, the key will be md5 from three fields - buyer's TIN + seller's TIN + Contract name and number (yes, this is one field). As far as you remember, md5 is a 128 bit hash function, then digest is 16 bytes, if represented as characters, we use hexadecimal calculus, respectively, one character encodes 2 ^ 4 - half a byte (called nibbl), 16 bytes are converted into 32 nibbls, 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 (the padded stool 16 bytes of steel 32). Since we keep working with our contracts from clients with a web-view, then we have to put up with the fact that they will enter exactly the line there, so md5. From the point of view of data protection, md5, of course, is
not worth using ; you can increase the resistance to attacks by adding an additional hash layer before md5 and using, for example, SHA-3.
This is how the functions of the first contract look like, if you connect to it via the Parity client network (these are functions that do not change the state of the blockchain - accordingly, they are free)

What these functions do should be clear from the title. The second field in the checkData function is the hash from the date of creation of the letter of credit + closing date + amount.
Then we need to implement the closing of the letter of credit and we can do everything inside the same contract, but since In the future, there are development plans and in the next stages it will be advisable to use some set 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:
nextContract.call(bytes4(sha3("create(bytes32,bytes32)")), id, lcs[id].hash);
From this line it becomes clear that we simply call the create function with certain parameters on nextContract. Now, in order to be able to call the create function only on the first contract, 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) throw; _; } }
where the address owner will be initialized when you create a contract with your address.
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 tx.origin (
example contracts ). This is because the calling of one contract to another occurs through
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 a letter of credit gets into the second contract, a status field is added to its structure, and by default it will be open.
After the seller provides the relevant documents that the bank employee checks, 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 an account (address) that has rights to close letter of credit. If the id existing in the second contract is transferred to the closing function input and the letter of credit received using the mapping contains a hash field identical to the one transferred to the function, then the letter of credit will be closed, i.e. the value of the “status” field in the structure of the letter of credit will change.
Let's look at this through Parity, connected to the second contract:

In addition to the functions, the results of their work are visible here - under the retVal
All these operations are carried out in three transactions:
- txCreate - creating a letter of credit
- txForSend - sending it to the second contract for closing
- txClose - closing a letter of credit
What it looks like for the user:

(transactions from a screenshot on a private chain)
You can see the public transaction on a special
search engine (etherscan) . Our contracts for etherscan:
first and
second .
As you understand, now in smart contracts just saving hashes from some fields of a letter of credit, its status and checking information at closing is implemented. Yes, we had more ideas of what could be transferred to the blockchain side, and perhaps in the future they will be implemented. In this project, we spent most of the time creating applications: front-end and api. Although it is believed that this happens in many projects related to the blockchain.
If you get to start your project with a blockchain and will raise your client for the network, then you may encounter 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 time synchronization via NTP on the server where Parity will be running, you can check your time using the
watch , if yours is not accurate, then synchronize too.
If you have a microservice architecture and an application that requires a connection to a network client, is not on the same server as the client, then your application will return errors. Because by default Parity (client) listens only to localhost. We solved this problem by setting Nginx in front of it in order to properly query requests and bypass CORS in addition:
location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Origin http://127.0.0.1:8080; }
This should save you some nerves and time (other ways to defeat this problem with the help of the launch parameters did not work for us).
And yet, why would you need a blockchain? Ideally, if you need to create a system for the exchange of information between the 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 bunch of private / public key, hence a digital signature is implemented, for example: the transaction is signed by the private key of the account that created it. As I understand it, CEP (qualified electronic digital signature), which has legal value, is a regular digital signature, a key in the key fob, 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 that will be signed with your private key, so you can verify that the transaction was created by you. So, you have an authorization mechanism, the same as in CEP, and that's it? Not really, when all participants in the transaction are authorized, the execution of the algorithm of the transaction itself can be a problem, usually the institution through which you are going to make the transaction acts as a guarantor, and here the execution of transactions through the platform for smart contracts begins to win. Because the logic prescribed in smart contracts does not change after they have been created and is in the public domain, and its performance 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 of these processes. Also in such a system it is possible to create decentralized communities with common capital, where proposals for the use of resources will be decided by the quorum of participants. Now the creation of products using the blockchain is still developing as a direction, so be prepared for the fact that the best practices will change.
So, the easy level of using the blockchain is that you want to record transactions in your business process in an external resource, so that you can later show transactions about these transactions and apply to smart contracts, which will return a formal confirmation of the transactions made (we are at easy).
Medium level - you authorize all participants in the transaction and save information about the documents created by them (you probably already guessed that we are talking about hashes) 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, verified through a public key - you receive a signed electronic document (analogue of CEP), respectively, 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’s advisable to use hashes with which to check the electronic document transferred in another way.Formal criteria for conducting transactions are better implemented in individual contracts, in this case it 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 require an answer, 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 associated with the blockchain can find the necessary investments .Finally:The main problem of the use of the blockchain within projects remains the legal side of the solution. Perhaps with the support of German Gref in 2017, something will change, but at the moment the use of technology is severely limited. In such projects, lawyers are needed from the very beginning. There are still no clear rules for the regulation of cryptocurrency in the Russian Federation, therefore the presence of such a person from the moment of laying the foundations and the brainstorm of air castles 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 still spend most of the time there.We managed to create a simple solution that preserves the results of its activities in the blockchain; this is far from how to use technology in principle, but we are only at the very beginning.Now there are many hypotheses and ideas on how to use 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 regulating the use of the blockchain.What else to read:→ Writing more robust smart contracts→ Understanding oraclesMore about Ethereum:→ Yellow paper→ Ethereum trie