The adapter for working with the blockchain Ethereum for the InterSystems IRIS data platform

    1. Blockchain


    Now, when I write this article, the Bitcoin course has fallen more than 5 times relative to the maximum value and telling me that I did something related to the blockchain, the first thing I hear is undisguised skepticism - “who needs all this blokchain now” .

    Yes, really, the HYIP around the blockchain is over. But the underlying technologies remain, they evolve and will continue to evolve and be used in certain niches.On the Internet and in particular on Habré a lot of materials describing both the general directions of application of technologies (for example, habr.com/company/bitfury/blog/353350 and more particular examples habr.com/company/raiffeisenbank/blog/332756 ).

    As is known, the blockchain is a distributed registry, i.e. a database that is distributed among several nodes, with each node keeping a complete copy of the registry. The feature of the blockchain is that the records (transactions) are grouped into blocks, and the blocks are combined into a chain of blocks. In this case, only operations for adding data are available. All this leads to the fact that it is almost impossible to make changes to transactions already stored in the blockchain.

    There are a lot of materials about how the blockchain works (if you have not heard anything about the blockchain before, then you can start with this simple video ).

    At the time of the maximum burst of interest in blockchain technology, there were many calls to use the blockchain absolutely everywhere. However, there are certain signs of projects / tasks that may require a blockchain.

    First, the participation of a large number of players (users) who record the data, while it is necessary to prevent discrepancies and increase the level of trust.

    Secondly, the absence of a third party that everyone trusts.

    Thirdly, the need for a mechanism for public data verification.
    If all the above conditions are met - you need to think about using the blockchain.

    Such tasks can arise in any industry. The project www.101blockchains.com collects information about both potential and implemented projects, as well as about the peculiarities of using blockchain in different areas.

    For example, in the healthcare sector, the blockchain can be used:

    • for the safe management of patient data;
    • to combat counterfeit drugs through unchanged transactions throughout the supply chain;
    • to improve the monitoring and effectiveness of clinical trials by eliminating fraud and manipulating data.

    When using the blockchain in the corporate segment, a private blockchain is usually used with a different level of permissions (Private Permissioned Blockchain). In such networks there is a special set of nodes for confirming transactions.

    However, when developing the first InterSystems IRIS adapter for working with the blockchain, we chose Ethereum , which belongs to the category of Permissionless Blockchain - an open platform without a governing body. This choice is associated with the popularity of Ethereum and a well-developed infrastructure: the presence of various tools and libraries. You can also notice that using the software for working with Ethereum, you can create a private blockchain .

    2. Adapter


    Now it's time to go to the adapter itself.

    An adapter in InterSystems IRIS (as well as in Ensemble) is a class or class package of InterSystems IRIS classes that provide the ability to work with an external system. InterSystems IRIS adapters are divided into incoming (to receive data from an external system when the external system is the initiator of interaction) and outgoing (to work with the external system when the initiator of the interaction is InterSystems IRIS).

    The IRIS Ethereum adapter is an outbound adapter and is slightly different from most other InterSystems IRIS adapters, since part of this adapter is the InterSystems IRIS class package, but the adapter also includes a small NodeJS module. The architecture is shown in Figure 1.


    Figure 1.

    The NodeJS adapter module uses the existing NodeJS libraries to work with Ethereum.

    The adapter provides the following features:

    • Place a smart contract in Ethereum (we plan to prepare another article in which we will discuss in more detail about smart contracts, development tools and discuss an example).
    • Call methods of smart contracts: as methods that do not change the state of the blockchain, and methods that change the state of the blockchain
    • Saving transaction (transfer of funds from wallet to wallet)
    • Calling helper methods to get blockchain status
    • Log all requests (performs NodeJS module, useful for debugging)

    The adapter is available with OpenExchange source codes .

    3. A simple example


    Along with the adapter, the “Hello world” example is installed.

    To get started with Ethereum (including starting this example) you will need:

    • Choose which network you will work with. For development usually use test networks such as Ropsten.
    • Create a wallet in this network and top it up
    • Install a local Ethereum client (for example, Geth) or get a key for working with a cloud provider (for example, Infura)

    When setting up a business transaction, you need to set (Figure 2):

    1. Server and port where NodeJS module is running (port 3000 by default)
    2. Provider settings (in this case, access to Infura)
    3. Реквизиты доступа ( в реквизитах доступа в качестве имени пользователя необходимо указать ваш кошелек, в качестве пароля — приватный ключ от кошелька. В InterSystems IRIS реквизиты доступа хранятся в отдельной БД, для которой необходимо включить шифрование)


    Figure 2.

    To work with smart contracts - you will need to create (for each smart contract you will apply) a folder in the file system and place there 2 files:
    * abi.txt
    * bytecode.txt

    These files must have ABI smart Contract and Bytecode. ABI smart contract - a formal description of the interface of a smart contract in json-format. ABI and Bytecode are created at the time of compiling the smart contract.

    Bytecode is required only to deploy a contract.

    Using the testing service, you can verify the operation of a business transaction.

    In Figure 3, a smart contract is deployed using the test service. The result of calling this business operation is a message containing the transaction hash.


    Figure 3.

    Using the ropsten.etherscan.io browser (https://etherscan.io/), you can find this transaction and get the address of the placed smart contract.

    To implement the smart contract methods using the adapter, you must specify the settings in the product configuration: ContractFolder and ContractAddress.

    The code for calling a smart contract method is quite simple:

    set ..ContractABI = [].%FromJSON(..ContractFolder_"abi.txt")		
    set contract = ..Adapter.GetContract(
                    ##class(Ethereum.Address).%New(..ContractAddress), 
                     ..ContractABI)
    set result = contract.hello()
    set pResponse = ##class(Ens.StringContainer).%New(result.args)
    

    Using the GetContract adapter method, which is passed the address of the smart contract and the ABI, a smart contract object is created, which is then used to invoke the methods. In this case, the hello () method that returns the string must be defined in the smart contract.

    In this example, the hello () method does not change the state of the blockchain, so it can be called synchronously. However, methods changing the blockchain state can take quite a long time (waiting for confirmation of the transaction).

    To call such methods, you can use the deferred response mechanism ( deferred response) in InterSystems IRIS. The adapter needs to send a deferred token (deferred) and then when confirming the NodeJS transaction, the module will transfer the result of its execution to InterSystems IRIS. To do this, you need to configure the web application and add a business transaction to the products that will process the response received.

    The code to call the method that changes the state of the blockchain:

    // getting EthereumAccount(wallet) and privateKey
    do ##class(Ens.Config.Credentials).GetCredentialsObj(.cred, "Ethereum.Demo.EthereumOperation", "Ens.Config.Credentials", ..Credentials)
    set account = ##class(Ethereum.Address).%New(cred.Username)
    set privateKey = cred.Password	
    //reading contract ABI
    set ..ContractABI = [].%FromJSON(..ContractFolder_"abi.txt")			
    // get contract object
    set contract = ..Adapter.GetContract(
                           ##class(Ethereum.Address).%New(..ContractAddress),
                           ..ContractABI)
    $$$ThrowOnError(..DeferResponse(.deferred))
    // estimate gas
    do contract.SetOptions(account)
    set gasJSON = contract.EstimateGas("setName",pRequest.Name)
    $$$TRACE(gasJSON.gas)
    do contract.SetOptions(account, privateKey,
                           ##class(Ethereum.Wei).%New(1000000000),
                           ##class(Ethereum.Wei).%New(100*gasJSON.gas),,deferred)
    set result = contract.setName(pRequest.Name)  

    In this case, before calling the setName () smart contract method, you must specify a number of parameters, including a delayed response token.

    In our next article, we will discuss in more detail about smart contracts and give an example of solving an applied problem using the InterSystems IRIS Ethereum adapter.

    Also popular now: