All code used in this post (C#, Solidity, DB scripts) can be downloaded at my Git repository
I had the opportunity to test the Nethereum.Web3 library by implementing a Supply Chain Traking System (SCTS) project and it proved extremely interesting from different points of view. During this post we will see how you can interact from .NET code with a BlockChain Ethereum making calls to Smart Contract methods.
What is a Supply Chain Tracking System (SCTS)
There is an official implementation of such a system that you can download at this address https://github.com/AtrauraBlockchain/scts. The definition that is given is this:
“STCS is a smart contract to keep track of products from the raw materials to the shopping stage.” This system is powered by the Ethereum Blockchain, so it’s fully distributed, immutable and auditable “. The version, however, here implemented differs a lot in the process flow architecture and in the relationship between entities. In practice we have this type of flow:
A Handler (which can be any user who manipulates the product at a certain stage of the transport chain) at some point takes charge of a product and applies an action to the same product (for example “I take the product from the Handler2″, or ” Deposited the product in Warehouse X “). A Handler is always associated with a user who must log in and to which always corresponds an Ethereum Address as an Ethereum Account . Every action applied to that product and performed by a certain Handler is memorized in the BlockChain and can be subsequently retrieved reconstructing the history of the product itself. Actions can be applied until the product reaches its destination and at that point is considered “consumed” and no action can be associated with it. Here is a process flow diagram:
The application consists of a .NET Core 2.0 web portal which is accessed through the IdentityServer. The Database was constructed in such a way that each account was associated with a BolockChain Address (Account Ethereum), so that a column was associated to the AspNetUsers table of Identity Server
To be able to return the BC Address at the time of authentication, IdentityServer will insert this information into a claim that will be added to the predefined claims collection that Identity returns in the token of the user who has just accessed the portal. To make everything simpler we have chosen to extend the ApplicationUser class with a property that will contain the BC Address:
And now we come to the MVC application. First we need to add the Nethereum.Web3 package via Nuget
Now we have all the ingredients to interact with our Blockchain, we will see later the part of the Smart Contracts involved in the implementation on the Ethereum side. Once logged in the portal we can browse the product page where the list of products already entered is displayed. This page begins with a call to the BC to interrogate a smart contract “Database” that contains all the products. As we can see, the page contains the BC Address on the top, as evidence of the association between this and the username in the upper right corner
The page must necessarily execute some calls to BC Ethereum in order to retrieve the list of products. So here the use of our Nethereum library begins. Let’s see the code in detail. First of all, the claims containing the Ethereum address of the user are retrieved from the IdentityServer. Once retrieved, we read from the configuration file the address of the Ethereum network that we give to the Web3 class constructor to define the instance representing the context of the Blockchain where we will operate.
With the Web3 instance we can now access the smart contracts published in the BC and invoke the methods. To invoke a method of a smart contract it is necessary to obtain the ABI (Application Binary Interface) and the address of the contract itself. What is an ABI for? We must think that a smart contract in bytecode was distributed in Ethereum. When we want to invoke a method then we must follow an extremely rigorous formalism that forces the caller to pass the parameters of the call in a way that perhaps is not usual to those who program only in high-level languages. Following the specifications of the Ethereum documentation we can see how to call a method with two whole parameters in input it will be necessary to pass 68 bytes to the call to the BC. It starts from the first 4 bytes which are the first 4 bytes of the result of the hashing operation of the method signature. Example if the method has the following signature
function baz(uint32 x, uint32 y) public pure returns (bool r)
then the first 4 bytes of the operation are taken
bytes4(keccak256("baz(uint32,uint32)") = 0xcdcd77c0
then follow 32 bytes for the first parameter (padded 0) and the other 32 bytes of the second parameter (padded 0). The thing is evidently much more complex than the passages of parameters of high-level languages where everything is hidden by compilers, which however always adopt ABI hidden mechanisms at a high level, but absolutely present at the machine language level. To take a further example, let’s think about the function calls of functions at the assembler level. In that case the stack represents the portion of memory that contains the ABI for the call to function by the caller.
Where do we find the ABI of a contract? The Solidity compiler provides it when it compiles a smart contract and the result will be a Json file containing among other things also the bytecode of the contract itself:
Above is shown the portion of ABI in Json format relative to the ‘getProduct’ method which in input wants an integer and returns the address of the relative contract.
For convenience, a ‘BlockChain’ class has been built containing all the ABIs and all the Addresses of the contracts. Finally, the contract address is very simple to retrieve during the contract migration phase. We have used Ganache as a Blockchain Ethereum using the default addresses provided
In our case the smart contract Database has address 0xde554c0b4ca9efcf1958c01485d673a0b06d5bc1
Let’s get ready for the various calls
We recover the Contract object that our library abstracts for us with good results. The Function object is then retrieved which abstracts the method present in the smart contract and then the asynchronous call to the method is made. This call returns to us the number of Product Smart Contract really recorded in BC. For each of these we will invoke another function of the Smart Contract Database to which we will pass the cycle index, returning the address of the smart contract. Once the address of the Product has been retrieved, we will retrieve the names of the product properties and read them through appropriate calls as shown:
With the properties of each Product we will create the corresponding DTO to be included in the model to be displayed on the page. Now let’s insert a new product. That is, we imagine that a new product is created within the company, or a new batch of materials that will then be sent to the end customer:
To get more precision we also store the location where the product was created. Once created we see it in the list:
How did the creation of a new smart contract product work in the blockchain? In this case the operation obviously has a cost (in Gas) unlike the consultation operation that does not change the status of the Blockchain and therefore does not require any contribution in Gas. To prepare the call data we construct an object that contains among other things also the Gas to ‘pay’ the transaction in addition to the other parameters that consist of the product name, additional information (product description) and geographical coordinates in addition to ‘address of the smart contract’ Database ‘. Here is the code in detail:
Now we add an action to the product. For example, let’s say that the product has been stored in the main warehouse
The technique from the point of view of Nethereum is the same as the previous transaction that created the Product contract. In pratical invoking a method to retrieve the address of the Product contract to which to add an action, setting the parameters to invoke ‘addAction’ to the contract and view the product history. If at this point the product was delivered to another user, an action would be added and, by accessing another account, the whole chain of steps would be displayed, representing the various actions performed on the product up to the end user (at this point we say that the product is ‘consumed’ and any other further action is not permitted), which could use an app to verify the whole chain of steps seeing that the product has followed a certain path from leaving the factory until you get to him.
We come now to the solidity part. There is a basic contract called Owned from which the DataBase contract is derived, for example, and which allows operations to be performed on the latter only if the initial (user) address has been configured.
The Database contract also contains the following features to manage the contracts within it:
Here instead I reproduce the code of the contructor of the Product, which has as its parameter the address of the contract database and this will be very interesting to see it during migration
Here is how a migration file must be made that contains a contract (product) inside it, which in order to be initialized must wait for the creation of the Database contract and receive its address
The SCTS system implemented through Blockchain Ethereum guarantees the total integrity and immutability of the various steps that characterize the life of a product. The more the product is characterized by a univocal recognition, the more this chain guarantees maximum reliability, offering guarantees regarding the integrity of the product in addition to its origin (we think, for example, the great use that can be made to guarantee the authenticity of some Made in Italy products). The code as tradition can be retrieved from the git project that contains, in addition to the C # code, also the script to generate the DB and the smart contract solidity code to be created in Visual Studio Code. The users already entered are the following:
email@example.com, firstname.lastname@example.org, email@example.com, firstname.lastname@example.org, email@example.com
All use the same password Pa$$w0rd