how we implemented the most important feature for blockchain in fintech

how we implemented the most important feature for blockchain in fintech

IN fast For the history of the development of smart contracts, we have devoted a whole section to such a concept as confidential smart contracts. Blockchain has a number of advantages that make it attractive for the implementation of confidential systems. But the data of smart contracts, which form the business logic of the blockchain, are stored in open form by default and are available to everyone. This conflict is resolved by confidential smart contracts (CSC) – they became one of the main features of the platform for us, planned for 2023, and successfully reached the release. Next, we will reveal the details of the KSK implementation and give an example of a contract that you can easily deploy on an open-source instance of our network.

The idea of ​​implementing confidential smart contracts began to mature during our project with FNP, the Federal Tax Service. More about him told our CTO Denys last year; you can view the current case here Online. In short, the central platform of the FNP distributed registry runs on our blockchain technologies: all applications for the issuance of interest-free loans from small and medium-sized businesses under the interest-free lending program, approved in Government Regulations during the pandemic, went through it.

Information about the borrower within this system must be simultaneously available to all organizations — otherwise, the borrower, using the desynchronization of the system, will be able to obtain many interest-free loans from different banks. However, the amount of loans to specific borrowers must be kept private, since by law this information constitutes a commercial secret.

General case

In general, the above is described. Let’s imagine that there is some central organization BaseOrg, which is in the same network with organizations Org1, Org2, Org3 … and interacts with them according to the same model. But some details and results of these interactions should not be available to everyone, but only to the central organization and selected others.

Let’s look at it from the perspective of smart contracts. Technically, all interactions of the main organization must be implemented within the framework of one smart contract. The state of this smart contract is single, on one contract. In each pair BaseOrg+Org1, BaseOrg+Org2, BaseOrg+Org3, keys accessible only to nodes in the pair are recorded in the contract state. In addition, there are, of course, keys available to all participants.

If we impose “confidential smart contracts” on the described configuration, then what requirements should we implement:

  • creation of private groups within which network participants can exchange confidential information recorded in closed transactions;

  • distribution of private smart contract call parameters and private execution results among private group members;

  • validating the successful execution of the smart contract with private results within the group and then within the general consensus of the results of the execution of the smart contract.

Three ways to achieve privacy

Confidential smart contracts are not the only way to implement privacy in our case. In total, three approaches can be distinguished here.

Confidential Transactionstransaction data is available only to a certain number of participants. This is how we transfer tasks from the level of smart contracts to the level of transactions and solve tasks more precisely. But we have already implemented a mechanism for transactions transfer of confidential datain which we create data access groups,

that are sent to the network via gRPC or REST API. If you implement privacy at the transaction level, you will have to change this whole approach so that privacy works natively for most transactions. We are quite satisfied with the current scheme, so we will evaluate other options.

Confidential data in transactionstransactions are public, but the data in them is at least partially hidden. This is the path of least refinement, which minimally changes the current mechanisms of exchanges. But then it will be impossible to maintain the anonymity or confidentiality of the transactions themselves. And in general, this method solves, rather, not a general case, but a private case with FNP, which we described at the beginning of the post.

Confidential smart contractsonly some participants have access to call the contract and get the results. This approach is implemented at a relatively higher level and, accordingly, only at the level of the concept there is a minimum of nuances. We simply call the smart contract and get a valid confidential result. So you can hide not only the data, but also the smart contract itself, as well as the transaction with the result. The implementation also looks quite accessible, since we work at the level of smart contracts and do not touch the deeper layers of the blockchain.

The third option, as you already guessed, went into development. Here we need to think separately about the infrastructure of smart contracts, because if a large number of P2P exchanges are involved in the projects, we risk being overloaded with more complex smart contracts. Parallel execution of smart contracts can help – we also wrote about it in a post about the history of development these tools. After all, it is worth thinking about how smart contracts will call each other (by the way, there will be a next post on our blog about this). We will solve some of these issues already in 2024, and for now we will talk about what we achieved by the end of last year.

Final implementation

We chose a fairly simple option for implementing smart contracts. The only architectural change compared to ordinary smart contracts is the introduction of new groups that can be given inputs to a contract and receive outputs in return.

Interaction with confidential smart contracts, as with conventional ones, takes place in three stages: creation, invocation and update. Here are the new tools we’ve added to do just that.

CreateContractTransactionV6 – New contract creation transaction including new fields:

  • isConfidential – whether the smart contract is confidential or not;

  • groupParticipants – members of a private group;

  • groupOwners – administrators of a private group.

UpdateContractTransactionV5 — a new smart contract update transaction, with new fields groupOwners and groupParticipants that perform the same functions.

We have also prescribed separate calls for confidential contracts:

We create a confidential smart contract

You can try confidential smart contracts on the open-source version of our platform. It’s easy to deploy, we’ll guide you published. Here is an example of a simple confidential smart contract:

val image = createContractImage() // cоздание образа контракта
// создание группы, которая имеет доступ к конфиденциальным данным
val participants = nodes.map(node => Address.fromString(node.address).explicitGet()).toSet
// генерация и отправка запроса на создание контракта с поддержкой конфиденциальных данных
val request = createSignedCreateContractRequestV6(txSender,
image,
List.empty,
isConfidential = true,
groupParticipants = participants,
groupOwners = Set(txSender.toAddress))
val createTxId = txSenderNode.signedCreateContractV6(request).id

// конфиденциальные данные
val expectedInput = List(IntegerDataEntry("test", 1))
val request = ConfidentialContractCallRequest(
sender = txSender.toAddress.toString,
contractId = contractId,
contractVersion = 1,
params = expectedInput,
timestamp = System.currentTimeMillis(),
fee = callContractFee,
commitment = None,
commitmentKey = None
)

// вызов контракта
val callResponse = txSenderNode.confidentialCall(request, broadcast = true)

val callTransactionId = (callResponse \ "callContractTransactionV6" \ "id").as[String]

// проверка, что данные не доступны публично
val executedTransactionFromPublic = txSenderNode.executedTxFor(callTransactionId)
executedTransactionFromPublic.results shouldBe List.empty

val confidentialInputAndOutput = txSenderNode.confidentialTxWithInputAndOutput(callTransactionId)

val expectedOutput           = List(IntegerDataEntry("sum", 1))
val actualConfidentialInput  = (confidentialInputAndOutput \ "confidentialInput").as[ConfidentialInput]
val actualConfidentialOutput = (confidentialInputAndOutput \ "confidentialOutput").as[ConfidentialOutput]

// проверка, что для нужных участников данные возвращаются
actualConfidentialInput.entries shouldBe expectedInput
actualConfidentialOutput.entries shouldBe expectedOutput

/* как изменяется контракт для поддержки конфиденциальности определенного ключа - просто ставится проверка на версию транзакции */

private def handleCallTransaction(
tx: ContractTransaction,
authToken: String
): Unit = {
if (tx.version >= 6) {
tx.params.extractStringParam("confidential-parameter")
} else {

// do something else
}
}

Some points should be further explained. The confidentiality of the smart contract is registered at the time of receiving the call transaction. In the contract itself, it is necessary to prescribe a check of the transaction version (sixth or later) and then carry out manipulations with the key. This prevents private group keys from being used by non-confidential transactions.

And this is how, in general, the above smart contract will work:

  1. A confidential smart contract will be invoked.

  2. A member of the participants group regulated through validation will transfer confidential data to the contract.

  3. The smart contract will send confidential output to a separate instance of RocksDB, where only members of the participants group can read it.

Only logic and key names will be available in the smart contract itself

Development of confidential smart contracts

In 2024, we plan to introduce atomic transactions within the framework of confidential smart contracts. Perhaps, as in conventional smart contracts, we will add support for MVCC (control of parallel access in the form of multiversion). Other features of confidential smart contracts will appear according to the needs of specific projects.

Related posts