【问题标题】:How do transactions take place in a blockchain?交易如何在区块链中进行?
【发布时间】:2021-04-17 01:49:19
【问题描述】:

我对区块链技术非常陌生。作为项目的一部分,我正在尝试开发一个用于电子投票的区块链应用程序。在我在 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;
  }
}

那么,其中的哪些数据被创建为区块链中的块?这段代码究竟是如何在区块链中创建交易的?

【问题讨论】:

    标签: blockchain solidity


    【解决方案1】:

    情况正好相反。

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

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


    示例:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-07
      • 2021-10-08
      • 2022-12-15
      • 1970-01-01
      • 2022-07-22
      • 2019-04-24
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多