首页 > 解决方案 > C中区块链的Nonce函数。C中无符号字符数组的连接

问题描述

我尝试在我的区块链程序中添加一个随机数。但是当我通过尝试重复结果来测试程序性能时(我需要能够验证我的链),我没有得到相同的结果。

首先,我有一个将 a 转换为的structure函数unsigned array pointer

struct  Test{
    unsigned char data[4];
    unsigned char nonce[4];
    unsigned char hash[32];
}*prev,*next; 

unsigned char *toStringTest(struct Test data)
{
    unsigned char *str=malloc(sizeof(unsigned char)*sizeof(data));
    memcpy(str,&data,sizeof(data));
    return str;
}

然后,我有一个程序给我一个哈希和随机数:

在这个函数中:

  1. 我将 unsigned char 指针toStringTest()与 unsigned char arrat连接起来nonce
  2. 我计算了这个连接的哈希值。
  3. 如果哈希开始于0x00我将哈希和随机数保存到next块中。如果没有,我重复这个功能。
void hash_with_nonce(struct Test* message,struct Test* new_message){
    unsigned char nonce[4]; //number only used once
    unsigned char buffer[32];
    while(1){
        RAND_bytes(nonce, 4); //this function puts 4 cryptographically strong pseudo-random bytes into nonce. 

        unsigned char* str=toStringTest(*message); 

        int len = sizeof(unsigned char)*sizeof(*str)+sizeof(unsigned char)*sizeof(nonce);
        unsigned char* message_with_nonce = malloc(len);  
        memcpy(message_with_nonce,str,sizeof(*str));
        memcpy(message_with_nonce+sizeof(unsigned char)*sizeof(*str),nonce,sizeof(nonce));
        //I concatenated toStringTest(*message) with nonce

        SHA256(message_with_nonce, sizeof(message_with_nonce), buffer); //calculation of hash

        free(message_with_nonce);   
        unsigned char var[1] = {0x00}; //rule for nonce decision, I want what hash start by 0x00
        if((int *)var[0] == (int *)buffer[0]){ 
            memcpy(new_message->hash,buffer, 32); 
            memcpy(new_message->nonce, nonce,sizeof(nonce));
            return;
        }
    }

}

这是我的主要内容:

int main(int argc, char **argv)
{
    unsigned char hash[32];

    prev=malloc(sizeof(struct Test));
    RAND_bytes(prev->data, 4);
    RAND_bytes(prev->nonce, 4);
    SHA256("",sizeof(""),prev->hash);

    next=malloc(sizeof(struct Test));
    RAND_bytes(next->data, 4);
    //I just have filled this block with random data  

    hash_with_nonce(prev,next);


    unsigned char* str=toStringTest(*prev); 

    int len = sizeof(unsigned char)*sizeof(*str)+sizeof(unsigned char)*sizeof(next->nonce);
    unsigned char* message_with_nonce = malloc(len);  

    memcpy(message_with_nonce,str,sizeof(*str));
    memcpy(message_with_nonce+sizeof(unsigned char)*sizeof(*str),next->nonce,sizeof(next->nonce));
    SHA256(message_with_nonce, sizeof(message_with_nonce), hash);
}

prev 和 next 只是我用来检查功能hash_with_nonce是否正常工作的 2 个块。

一个问题是unsigned char hash[32]main 的 与 不同next->hash。SHA256() 和 RAND_bytes() 是 openssl 函数。

要检查 2 个哈希是否相同,我有这个功能:

void PrintHex(unsigned char data[], int size) 
{
    unsigned char tmp[size];
    for (int i=0; i<size; i++)
    { 
        sprintf(tmp, "%02x",data[i]); 
        printf("%s", tmp);
    }
    printf("\n");
}

标签: cblockchain

解决方案


推荐阅读