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

How do transactions take place in a blockchain?

我对区块链技术还很陌生。作为项目的一部分,我正在尝试开发用于电子投票的区块链应用程序。在我在 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. 交易由客户端应用程序创建(以 JSON 对象的形式)并由发送方的私钥签名
  2. 发送到节点
  3. 并由节点广播到网络,它在内存池(尚未开采的交易列表)中等待被开采。
  4. 矿工将其包含在一个区块中
  5. 如果交易接受者是这个智能合约,交易的矿工执行它是为了能够计算它的状态变化。此外,在它被包含在一个块中之后,所有节点都会验证并投射状态变化。

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


示例:

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

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