Javascript

為什麼這個 Javascript Ethash 實現返回錯誤的雜湊結果?

  • April 22, 2021

我正在嘗試從ethereum/ethash/js計算 Etash 算法的“輕量級”實現的雜湊結果,但我似乎無法得到正確的結果。

比較的預期結果是用ethereumjethashjs計算的。

我的 Javascript 實現程式碼:

"use strict";

var ethash = require('./ethash');
var util = require('./util');

// init params
var ethashParams = ethash.defaultParams();
ethashParams.cacheSize = 16776896 //cachesize for epoc 0
ethashParams.dagSize = 1073739904 //fullsize for epoc 0

// create hasher
var seed = Buffer.alloc(32).fill(0); //epoc 0
var hasher = new ethash.Ethash(ethashParams, seed);

console.log('Ethash cache hash: ' + util.bytesToHexString(hasher.cacheDigest()));
// expected: 35ded12eecf2ce2e8da2e15c06d463aae9b84cb2530a00b932e4bbc484cde353 --> OK

       
var header = util.hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
var nonce = util.hexStringToBytes("0000000000000000");

var hash = hasher.hash(header, nonce);
console.log("Ethash hash result: " + util.bytesToHexString(hash));
// expected: 89eaac0ac621d2bb2d1a62455119cb0d0a0883d554e748bab23c2066da080916 --> OK


header = util.hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
nonce = util.hexStringToBytes("6c18bd55f3d77ab5");

hash = hasher.hash(header, nonce);
console.log("Ethash hash result: " + util.bytesToHexString(hash));
// expected: 0a9f8a9d1954c796b8bbafe0d443f1586c17ffe995070ea5a40436946c1bf2d7 --> NOT OK

輸出:

$ node ./post.js 
Ethash cache hash: 35ded12eecf2ce2e8da2e15c06d463aae9b84cb2530a00b932e4bbc484cde353
Ethash hash result: 89eaac0ac621d2bb2d1a62455119cb0d0a0883d554e748bab23c2066da080916
Ethash hash result: 72d628f1bb9e7229f43c210824975d179f6b55da47ebe4655b4a55d677697391

因此,似乎記憶體計算正確(雜湊與其他實現的雜湊匹配)。a 的雜湊結果nonce = '0x0000000000000000'也匹配,但隨機其他 nonce 計算的結果不匹配。我認為這與隨機數的字節順序有關……任何想法應該如何為Javascript實現指定隨機數以獲得正確的雜湊結果?

好吧,解決方案很簡單。假設它與字節順序有關,我是正確的。在將隨機數傳遞給散列函式之前反轉隨機數就可以了:

header = util.hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
nonce = util.hexStringToBytes("6c18bd55f3d77ab5").reverse();

hash = hasher.hash(header, nonce);
console.log("Ethash hash result: " + util.bytesToHexString(hash));
// expected: 0a9f8a9d1954c796b8bbafe0d443f1586c17ffe995070ea5a40436946c1bf2d7

引用自:https://ethereum.stackexchange.com/questions/97609