首页 > 其他分享 >在以太坊区块链上添加一个区块

在以太坊区块链上添加一个区块

时间:2023-10-26 21:46:15浏览次数:47  
标签:txn sha256 hash string 以太 json 链上 区块 block

包括json库的相关读取,proof-of-work算法的实现,Merkel Tree的构建,使用hash创建新块等内容,使用本地json文件模拟mempool和block chain,C++编写。

#include <iostream>
#include <fstream>
#include <string>
#include <nlohmann/json.hpp>
#include <zlib.h>
#include <openssl/sha.h>

using namespace std;
using json = nlohmann::json;

/*{"header":{
"difficulty":3,
"height":120,
"miner":"0xca4388fb6d0ee25d59c24360e49c2dd4c9d02727",  
"nonce":320,
"hash":"0x000a3698e344f2549cb88537e129a37ac78e195c08006486f928cc465bcc0550",
"previous_block_header_hash":"0x000232491f11addef82c7217de3c8f03873975442192fe6e41437bd6584585c8",
"timestamp":1697413800,
"transactions_count":70,
"transactions_merkle_root":"0xdc73d314ad97973cfcebff8ae6c5f06d545156a543be949ed237f1ca9ac3f70f"},*/

/*transaction
{
" receiver ": "0 xb0d7e24e8818e78878c116e73ea6a081d1f12b7d ",
" lock_time ": 0,
" transaction_fee ": 86 ,
" amount ": 72619 ,
" sender ": "0 x3a55c9e459c0c5b744fa4839d5e833af96c503be ",
" signature ": "0 x305930130 ... f78a667 "
}*/


string sha256_my(const string str)
{
    char buf[2];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    std::string NewString = "";
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(buf,"%02x",hash[i]);
        NewString = NewString + buf;
    }
        return NewString;
}

string H(string a, string b)
{
    string res = "0x";
    if (a < b)
    {
        res += sha256_my(a + b);
    }
    else
    {
        res += sha256_my(b + a);
    }
    return res;
}

int main()
{
    /*have decompressed the gz to json*/
    /* get header from blockchain.json.gz */
    std::ifstream f("blockchain.json");
    json blockchain = json::parse(f);
    /* Load the most recent block header hash*/
    json recent_block = *blockchain.rbegin();


    /*part 2: use proof-of-work algorithm to produce new block*/
    std::ifstream f2("mempool.json");
    json mempool = json::parse(f2);


    /*part2-1*/
    int blockTimestamp = recent_block["header"]["timestamp"];
    //int transactions_count = recent_block["header"]["transactions_count"];
    const int max_txn_num = 100;
    json profitableTransactions;

    for(auto it = mempool.begin(); it != mempool.end(); it++) {

        /*fliter*/
        if((*it)["lock_time"] <= blockTimestamp) {
            profitableTransactions.push_back(*it);
        }

        if(profitableTransactions.size() >= max_txn_num) {
            break;
        }
    }

    sort(profitableTransactions.begin(), profitableTransactions.end(), mycomp);//lexicographic order???

    /*part2-2 construct the markle tree*/
    /*get txn hash*/
    //2-AVL? : markle tree
    vector<string> txn_sha;
    for(auto it = profitableTransactions.begin(); it != profitableTransactions.end(); it++) {
        // serialised transaction
        string serialised_txn = "";
        auto one_txn = *it;
        for(auto it2 = one_txn.begin(); it2 != one_txn.end(); it2++) {
            one_txn += it2.value();
            if(it2 != one_txn.begin())
                one_txn += ",";
        }
        txn_sha.push_back(sha256_my(serialised_txn));
    }

    vector<string> MerkleTree(txn_sha);
    if(MerkleTree.empty()) {
        cout<<"error: MerkleTree empty"<<endl;
        exit(-1);
    }

    while(MerkleTree.size() != 1) {
        vector<string> temp;
        for(int i=1;i<MerkleTree.size();i+=2) {
            temp.push_back(H(MerkleTree[i-1], MerkleTree[i]));
        }
        if(MerkleTree.size() % 2 == 1) {
            temp.push_back(H(*MerkleTree.rbegin(), ""));//take "" as 0
        }
        temp.swap(MerkleTree);
    }
    string MerkleRoot = MerkleTree[0];

    //part2-3: 
    json new_block = recent_block;

    //fill header
    new_block["header"]["height"] += 1;
    new_block["header"]["miner"] ="0x00132b386d939d081bffad6dbaef99e7d4618862";
    new_block["header"]["nonce"] = 0;
    new_block["header"]["previous_block_header_hash"] = recent_block["header"]["hash"];
    new_block["header"]["timestamp"] += 10;
    new_block["header"]["transactions_count"] = profitableTransactions.size();
    new_block["header"]["transactions_merkle_root"] = MerkleRoot;

    //fill transactions
    new_block["transactions"].clear();
    for(auto it = profitableTransactions.begin(); it != profitableTransactions.end(); it++) {
        new_block["transactions"].push_back(*it);
    }

    // part2-4:Mine the block, Proof-of-Work algorithm
    string str_to_hash1 = "";
    str_to_hash1 += to_string(new_block["header"]["difficulty"]) + ",";
    str_to_hash1 += to_string(new_block["header"]["height"]) + ",";
    str_to_hash1 += new_block["header"]["miner"] + ",";

    string str_to_hash2 = ",";
    str_to_hash2 += new_block["header"]["previous_block_header_hash"] + ",";
    str_to_hash2 += to_string(new_block["header"]["timestamp"]) + ",";
    str_to_hash2 += to_string(new_block["header"]["transactions_count"]) + ",";
    str_to_hash2 += new_block["header"]["transactions_merkle_root"];

    for (int i = 0;; i++) {
        string str = str_to_hash1 + to_string(i) + str_to_hash2;
        string res = sha256_my(str);
        string effective_pos = res.substr(0, new_block["header"]["difficulty"]);
        if(effective_pos.find_last_not_of("0") == string::npos) {
            new_block["header"]["hash"] = "0x" + res;
            break;
        }

        if(i % 100000 == 0) {
            cout<<"i"<<endl;
        }
    }

    //part3: write back
    std::ofstream o("blockchain1.json");
    o << new_block;

    return 0;
}

标签:txn,sha256,hash,string,以太,json,链上,区块,block
From: https://www.cnblogs.com/kazusarua/p/17790479.html

相关文章

  • 区块链技术软件开发师:打造区块链应用的专家,掌握开发实战技能
    区块链技术软件开发师:打造区块链应用的专家,掌握开发实战技能 专业技能:一、编程语言方面C/C++(必须熟悉C++语言),Golang(必须熟悉GO语言)、Python、Java、Solidity,能独立开发Chaincode熟练掌握golang的goroutine,  channel,gRPC等技术可以额外学习一些前端技术,HTML5、DIV、CSS、J......
  • 从0到1,全面学透区块链:掌握区块链的基础理论和技术
    从0到1,全面学透区块链:掌握区块链的基础理论和技术1、简介​区块链是一个又一个区块组成的链条。每一个区块中保存了一定的信息,它们按照各自产生的时间顺序连接成链条。这个链条被保存在所有的服务器中,只要整个系统中有一台服务器可以工作,整条区块链就是安全的。这些服务器在......
  • 从零构建以太坊智能合约到项目实战:掌握区块链编程的精髓 成为区块链编程大师
    从零构建以太坊智能合约到项目实战:掌握区块链编程的精髓成为区块链编程大师为什么说现在学习区块链才是最好的时机?区块链技术不只是能开发数字货币,不只是能进行ICO。当我分享一些区块链文章的时候,偶尔总会有人艾特我说,春哥,现在国家都不让炒币了,还弄个毛的区块链啊。我一般会......
  • 在goland上部署环境用于区块链开发
    1.下载ubantu虚拟环境,使用Linux。(直接在goland中的plugin搜索下载)2.在plugin中搜索Remotedevelopmentconnector下载,用于远程开发3.在terminal中使用ubantu,下载NVM用于管理Node.js版本的工具curl-o-https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh|bas......
  • 汉源高科1路万兆光4路千兆物理隔离电口4路1000M物理隔离以太网光纤收发器
    HY5700-3514XGV-LC10汉源高科万兆1光4电物理隔离型光纤收发器,提供1路万兆SFP+光口+4路千兆物理隔离电口,支持存储转发或直通透传模式,可通过一芯光纤同时实时传输4路不同的网络信号,杜绝各个电口通道系统信号的相互串扰,实现了不同通道信号之间的物流隔离;产品采用高品质光模块、Marvel......
  • 区块链安全技术全方位掌握:从基础知识到公链开发和智能合约实战
    区块链安全技术全方位掌握:从基础知识到公链开发和智能合约实战0x00 前言区块链的安全需求越来越多,下面就将这些需求一一拆分,看看区块链安全需求到底是个什么样子。0x01 拆分目前针对安全服务行业的区块链安全需求,更多的是基于其上层应用(红色箭头指向)比如数字货币交易平台......
  • 基于Go语言跟我一起写DApp-转型区块链应用开发推荐课程GoSDK+Fisco-Bcos
    基于Go语言跟我一起写DApp-转型区块链应用开发推荐课程GoSDK+Fisco-Bcos0介绍学习目标:1、理解什么是区块链;2、掌握区块链基本结构;3、构建区块链基本模型;理论部分:1、区块链七层架构模型;2、区块链链式结构;实践部分:1、创建区块;2、创建区块的“链”;3、访问区块链;开发环境:GoL......
  • 基于以太坊Ethereum & IPFS的去中心化Ebay区块链项目实战
    基于以太坊Ethereum&IPFS的去中心化Ebay区块链项目实战1.介绍1.1eBay简介eBay,(EBAY,中文电子湾、亿贝、易贝)是一个管理可让全球民众上网买卖物品的线上拍卖及购物网站。ebay于1995年9月4日由PierreOmidyar以Auctionweb的名称创立于加利福尼亚州圣荷西。人们可以在ebay上通过......
  • 智安网络|从区块链到社交网络:解析去中心化的意义与应用
    在当今数字化的世界中,一个越来越常见的概念是“去中心化”。从区块链技术到金融系统,从社交网络到数据存储,去中心化被认为是一种前所未有的方式来重新定义和改变传统的中心化结构。那么,去中心化到底是什么?首先,去中心化是一种思想和哲学,旨在消除中心化权力和控制。传统的中心化结构通......
  • 别再吹捧什么区块链,元宇宙,Web3了,真正具有颠覆性的估计只有AI
    「感谢你阅读本文!」别再吹捧什么区块链,元宇宙,Web3了,真正具有颠覆性的估计只有AI。我们这个社会有这样一个特性,就是出现一个新事物,新概念,新技术,先不管是否真的现实,是否真的了解,第一件事首先要做的就是先圈一波钱,不过繁华终将逝去,经得起推荐者才能长存。区块链自从2008年比特币......