[Ethereum] How to make a database and smart contract interact

contract-designcontract-developmentdatabasesolidity

I started to code a smart contract which was supposed to store some datas from corporations. These datas (mostly names and dates) were organized like that :

├── Client1(Contract)
│   ├── Year2018 (Struct containing string,uint and struct)
│   │   ├── Case 1 (Struct containing string)
│   │   └── Case 2 (Struct containing string)
│   └── Year2017
│       └── Case 1 (Struct containing string)
├── Client 2
│   └── Year2018
│          ├──Case1 (Struct containing string)
│          └──Case2 (You got it)

I managed to make a contract to fill these structs. Therefore , I realized that this process was way too heavy and costly. It won't be a problem if my project interact with a centralized database , the blockchain is used for verifications purpose only.

Few people on this forum suggested me to "hash the datas and store them on a DB". I think that would be a great solution but I can't get how to setup this …

How would I store the above structure of data on a DB ? How would I upload the datas first (Is it from DB to smart contract or the contrary ? ) ? Would it be possible to visualize the datas on a block eplorer ?

Please ask if you didn't get something in what I said 🙂
Thank you very much and have a good day

Best Answer

You can use that solution to prove that the database is working with "legit" records by storing hashes of the documents in a contract.

The basic process is you have a record you want to insert and you want to stamp it as legitimate in your contract. You'll record the hash of the document in the contract and the document itself somewhere else (db).

Convert the data into a string object, server-side, then generate a hash. In my opinion, the best way to ensure that all clients (at all times in the future) can generate a hash by the same algo the contract uses, is to offer this as a free service from the contract.

function hashHelper(string data) public pure returns(bytes32 hash) {
  return keccack256(data);
}

Then, there would be a way for the server to add this to the contract state:

function addHash(bytes32 hash) public onlyAuthorized returns(bool success) {
  require(!isHash(hash)); // check uniqueness
  hashMap[hash] = true; // store it, for example, mapping(bytes32 => bool) public hashMap
  return true;
}

More on the technique: https://medium.com/@robhitchens/selective-disclosure-with-proof-f6a1ac7be978

More on general-purpose contract storage organization: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

Related Topic