简体   繁体   中英

Storing data into the blockchain

Writing a DApp where it stores data into a "blockchain". I'm trying to write this in solidity but i don't understand how to store it into a "blockchain". Am i able to do it like this? Would it be safe to store data just like that?

pragma solidity 0.4.24;

contract database{
struct Data{
    uint index;
    uint value;
}

Data[] public Datas;

  function AddData(uint _index, uint _data) public {
      Datas.push(Data(_index, _data));
  }
}

Yes! You can simply store data in the blockchain as simple as that.

Let's say you deployed this contract to the network and the contract address is 0x1234abc... .
Now you deploy it again, this time contract being deployed at 0x987cba...
Calling AddData() on 0x1234abc... and 0x987cba... won't be the same.
You're simply adding more data to that specific instance of that contract.

I can't say if storing some data in this way would be safe, It can be as safe as you want it to be. Meaning, it depends on your specific need and implementation.

Currently your contract looks like it can never be tampered with.
Because you're only appending data, not modifying anything in the contract.

If you want your data to be modified you can add some kind modifiers to your AddData() function such as Ownable by OpenZeppelin . So the only owner can modify data in this contract.

It would be better to use a mapping for your case, cause this gives you the possibility to define a custom index which could be not just 0, 1, 2, ..., n , but also a string or whatever you want. Here is an example:

pragma solidity 0.4.24;

contract database{

    struct Table{
        uint value1;
        uint value2;
    }

    mapping(bytes32 => Table) public tables; 

    function addData(bytes32 _index, uint _value1, uint _value2) public {
        tables[_index].value1 = _value1;
        tables[_index].value2 = _value2;
    }
}  

You could also use this expression to store the data via the addData function:

tables[_index] = Table(_value1, _value2);

It looks better, but makes the size of the smart contract bigger!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM