簡體   English   中英

交易如何在區塊鏈中發生?

[英]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. 如果交易接收者是這個智能合約,交易的礦工執行它來計算它的 state 變化。 此外,在將其包含在一個塊中之后,所有節點都會驗證並投射 state 更改。

總結一下:這段代碼不會創建交易。 但它是在挖掘到包含此代碼的合約的交易時執行的。


例子:

您的代碼部署在地址0x123上。 發件人向您的合約0x123發送交易,其中(交易的) data字段表明他們想要執行 function voteForCandidate()bytes32 candidate的值為0x01

當交易被挖掘時,礦工在他們的 EVM 實例中執行合約並計算 state 的變化,這導致votesReceived[0x01]的存儲值增加。 然后將此信息(連同他們挖掘的所有其他交易)廣播到網絡,以便每個節點都知道地址0x123上的votesReceived[0x01]在此交易中已更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM