1. 程式人生 > >C++從零開始區塊鏈:區塊鏈業務模組之建立交易和區塊

C++從零開始區塊鏈:區塊鏈業務模組之建立交易和區塊

建立交易簡單,直接給結構體賦值就行

    Transactions BlockChain::CreateTransactions(const std::string &sender, const std::string &recipient, float amount)
{
    Transactions ts;
    ts.sender = sender;
    ts.recipient = recipient;
    ts.amount = amount;
    return ts;
}

建立區塊需要從上一個區塊中獲取相關資訊,然後將已經記錄的交易打包加到區塊中,最後再將之前的交易記錄清空
下面的程式碼引數設計的有些重複,只要一個工作量證明的引數即可,其他引數都可以從上一個區塊中讀取到,但介面改動都很麻煩,我這裡就不改了

Block BlockChain::CreateBlock(int index, time_t timestamp, long int proof)
{
    Block block;

    ShaCoin::Block last = GetLastBlock();
    std::string strLastBlock = GetJsonFromBlock(last);

    block.index = index;
    block.timestamp = timestamp;
    block.proof = proof;
    block.previous_hash = Cryptography::GetHash(strLastBlock.c_str(), strLastBlock.length
()); pthread_mutex_lock(&m_mutexTs); block.lst_ts = m_lst_ts; m_lst_ts.clear(); pthread_mutex_unlock(&m_mutexTs); return block; }