简体   繁体   English

将数据存储到区块链中

[英]Storing data into the blockchain

Writing a DApp where it stores data into a "blockchain". 编写一个将数据存储到“区块链”的DApp。 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... . 假设您将此合同部署到了网络,合同地址为0x1234abc...
Now you deploy it again, this time contract being deployed at 0x987cba... 现在,您再次部署它,这次合同的部署位置是0x987cba...
Calling AddData() on 0x1234abc... and 0x987cba... won't be the same. 0x1234abc...0x987cba...上调用AddData()会不同。
You're simply adding more data to that specific instance of that contract. 您只是将更多数据添加到该合同的that specific instance中。

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 . 如果您想修改数据,则可以向AddData()函数添加某种类型的修饰符,例如OpenZeppelin的Ownable 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. 最好为您的情况使用mapping ,因为这使您可以定义自定义index ,该index不仅可以是0, 1, 2, ..., n ,还可以是字符串或任何您想要的值。 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: 您还可以使用此表达式通过addData函数存储数据:

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

It looks better, but makes the size of the smart contract bigger! 它看起来更好,但会增加智能合约的大小!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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