交易如何在区块链中进行?

时间:2021-04-16 17:31:15

标签: blockchain solidity

我对区块链技术非常陌生。作为项目的一部分,我正在尝试开发用于电子投票的区块链应用程序。在我在 github 上看到的许多项目中,它的可靠性如下所示

pragma solidity ^0.4.11;
// We have to specify what version of compiler this code will compile with

contract Voting {
  /* mapping field below is equivalent to an associative array or hash.
  The key of the mapping is candidate name stored as type bytes32 and value is
  an unsigned integer to store the vote count
  */
  
  mapping (bytes32 => uint8) public votesReceived;
  
  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).
  We will use an array of bytes32 instead to store the list of candidates
  */
  
  bytes32[] public candidateList;



  /* This is the constructor which will be called once when you
  deploy the contract to the blockchain. When we deploy the contract,
  we will pass an array of candidates who will be contesting in the election
  */
  function Voting(bytes32[] candidateNames) {
    candidateList = candidateNames;
  }

  // This function returns the total votes a candidate has received so far
  function totalVotesFor(bytes32 candidate) returns (uint8) {
    if (validCandidate(candidate) == false) throw;
    return votesReceived[candidate];
  }

  // This function increments the vote count for the specified candidate. This
  // is equivalent to casting a vote
  function voteForCandidate(bytes32 candidate) {
    if (validCandidate(candidate) == false) throw;
    votesReceived[candidate] += 1;
  }

  function validCandidate(bytes32 candidate) returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }
}

那么从中创建的哪些数据作为区块链中的一个块?这段代码究竟是如何在区块链中创建交易的?

1 个答案:

答案 0 :(得分:0)

相反。

  1. 交易由客户端应用程序创建(以 JSON 对象的形式)并由发送者的私钥签名
  2. 发送到节点
  3. 并由节点广播到网络,在那里它在内存池(尚未挖掘的交易列表)中等待挖掘。
  4. 矿工将其包含在一个区块中
  5. 如果交易接收方是该智能合约,则交易的矿工执行它以能够计算其状态变化。此外,在将其包含在一个区块中之后,所有节点都会验证并投射其一侧的状态变化。

总结一下:这段代码不会创建交易。但它会在包含此代码的合约交易被挖掘时执行。


示例:

您的代码部署在地址 0x123。发件人向您的合约 0x123 发送一笔交易,其中 data 字段(交易的)表明他们想要执行函数 voteForCandidate(),其中 bytes32 candidate 的值为 {{1 }}。

当交易被挖掘时,矿工在他们的 EVM 实例中执行合约并计算状态变化,这导致 0x01 的存储值增加。然后将此信息(连同他们挖掘的所有其他交易)广播到网络,以便每个节点都知道地址 votesReceived[0x01] 上的 votesReceived[0x01] 在此交易中已更改。