current position:Home>When mining with code, why do you have to convert it into JSON format and sort it when hashing?

When mining with code, why do you have to convert it into JSON format and sort it when hashing?

2022-02-03 20:53:11 Q & A of Denglian community

use Python Create blockchain from scratch In the article .

When mining with code , Why do you have to convert to... When hashing json Format ( Why not use a dictionary directly ), And sort ? The code is as follows :

def last_block_hash(self,block):    block_str = json.dumps(block,sort_keys=True).encode('UTF-8')    return hashlib.sha256(block_str).hexdigest()

Why can't the above code directly apply to block Dictionary search hash Is it worth it ? But to be converted into json Format and sort before hash What about computation ?




Take the answer 1:

hashlib.sha256 The type of the parameter is string , So you need to do a type conversion .

python The dictionary itself is json form , So convert to json character string .

The reason for sorting is : Because of the dictionary It's out of order , Because of different series, the same dictionary will produce different hash value , After the sorting , From the same dictionary hash It's the same .




copyright notice
author[Q & A of Denglian community],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202032053094487.html

Random recommended