Agree with Sanchit about using modifiers to control access to functions.
However, the example implementation is misleading. I would flag that for a redesign.
A couple of things to consider.
As far a data storage is concerned, you might want to consider off-chain serialization with encryption. This, to reduce the overall storage cost without compromising the distributed nature of the app.
For privacy, I see you're aware that information in Ethereum is visible to all parties. Consider using multi-party encryption with a smart contract to help distribute the "secret" to multiple authorized parties.
For scalability, @Sanchit's modifier needs to eliminate the unbounded for
loop. Put simply, for(i=0;i<n;i++)
is an anti-pattern. At a certain n
the cost of execution will exceed the block gasLimit meaning it will fail in all cases. In other words, implemented that way guarantees a successful application will eventually fail, possibly in a way that can't be repaired.
What's shown is perfectly logical in a server-centric world. In Ethereum, all functions need an (approximately) fixed gas cost at any scale. A solution is to refactor with 1-step lookups using mapping
.
Just mentioning this because this error exists in a lot of contracts and I hope the answer (I generally agree) doesn't lead coders to replicate that sort of defect.
Hope it helps.
First of all, information is encrypted using public key and decrypted using private key, not the other way around (that is signing and verifying).
First time A
stores data, A
will generate new keypair (private and public key) from hash or that data itself.
After that A
will first encrypt data using newly generated public key and after that encrypt newly generated private key using her own public key. When transferring A
will decrypt newly generated private key and encrypt it using B
's public key.
Then B
can decrypt that private key using his own private key and then decrypt data using that private key and confirm that it is indeed same data (since he can decrypt it, and if A
put wrong data on blockchain than she would not be able to decrypt it).
Now you can decide if you are going to generate keypair everytime data is changed or you are going to use keypair from first data entry on blockchain. And if B
wants to restrict access to A
when B
next time changes data, B
just has to generate new keypair from altered data.
Contract will need one event with string encryptedPrivateKey and string encryptedData.
When transferring you will just put B
's address alongside private key encrypted with B
's public key in another event.
In dapp you will notice B
if his address is in transfer event and try to decrypt data and if it works transfer is legit.
Best Answer
It is possible to do public private key encryption with ethereum addresses: How to encrypt a message with the public-key of an Ethereum address