Web3.js: Error: invalid argument 0: json: cannot unmarshal hex string of odd len gth into Go value of type common.Hash

Created on 4 Aug 2017  路  9Comments  路  Source: ChainSafe/web3.js

While trying get a block from ropsten getBlock(2378) succeed but getBlock('0x0c5b789878042c12f3cd9d69f040be1c3f669aee2997654c0b570f40b7dd72bb') fails, both refer the same block (https://ropsten.etherscan.io/block/0x0c5b789878042c12f3cd9d69f040be1c3f669aee2997654c0b570f40b7dd72bb).

It will work correctly with other blocks like 2377 and 2379.

The following script works without problems in v0.20.1 but fails with 1.0.0-beta.15.

const Web3 = require('web3');
const Promise = require('bluebird');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const isV1 = typeof web3.version === 'string';
const getBlock = isV1 ? web3.eth.getBlock : Promise.promisify(web3.eth.getBlock);

const numBlock = 2378;

async function main() {
  try {
    const block1 = await getBlock(numBlock);
    console.log(`${JSON.stringify(block1, null, '  ')}`);
    const block2 = await getBlock(block1.hash);
    console.log(`${JSON.stringify(block2, null, '  ')}`);
  } catch (err) {
    console.log(err);
  }
}

main();

The callstack of the error is

Error: invalid argument 0: json: cannot unmarshal hex string of odd length into Go value of type common.Hash
    at Object.ErrorResponse (/ethereum/test/node_modules/web3/packages/web3-core-helpers/src/errors.js:29:16)
    at /ethereum/test/node_modules/web3/packages/web3-core-requestmanager/src/index.js:137:36
    at XMLHttpRequest.request.onreadystatechange (/ethereum/test/node_modules/web3/packages/web3-providers-http/src/index.js:64:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/ethereum/test/node_modules/web3/packages/web3-providers-http/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/ethereum/test/node_modules/web3/packages/web3-providers-http/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/ethereum/test/node_modules/web3/packages/web3-providers-http/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/ethereum/test/node_modules/web3/packages/web3-providers-http/node_modules/xhr2/lib/xhr2.js:469:24)
    at emitNone (events.js:110:20)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1047:12)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
bug

Most helpful comment

I figured the issue out, thanks.
The getBlock formatter was converting the already hex to hex again, and subsequently removed the leading 0, as it doesn't care about padding when converting. I did now a proper check for HEX and don't convert any given HEX anymore. will be fixed in beta.17

All 9 comments

This error us comes from geth itself, it seems like your string you pass in has a space: getBlock('0x0c5b789878042c12f3cd9d69f040be1c3f669aee2997654c0b570f40b7dd 72bb')
@karalabe any idea?

The extra space was a copy&paste error into the github issue.

The test script doesn't have that error since it uses the value returned by getBlock(2378).

I don't think it is a geth error because it does work with web3 v0.20.

I figured the issue out, thanks.
The getBlock formatter was converting the already hex to hex again, and subsequently removed the leading 0, as it doesn't care about padding when converting. I did now a proper check for HEX and don't convert any given HEX anymore. will be fixed in beta.17

Will be there some fix for 0.20.x ?

@yangwao The bug I reported and I was able to reproduce was present only in web3 v1.0. If you have a different bug that affects v0.20 I encourage you to create a new issue since this particular issue was resolved some months ago.

Is this fixed, I am getting it too.

@BeOleg This particular report was an issue that affects web3 v1.0.0-beta.15 and was fixed in beta.17. If you experience the same error message with a newer version I'd suggest to create a new issue with indications how to reproduce it so it is easier for developers to fix it.

I have read the suggestion above,but I still don't know how to solve it. Does anybody have more specific suggestions?
My web3's vesion is 1.0.0-beta.52, My errors are as follows:

(node:11268) UnhandledPromiseRejectionWarning: Error: Node error: {"code":-32602,"message":"invalid argument 0: json: cannot unmarsh
al non-string into Go value of type common.Hash"}
    at Function.validate (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\web3-providers\dist\web3-providers.cjs.js:11
1:18)
    at HttpProvider._callee$ (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\web3-providers\dist\web3-providers.cjs.j
s:706:61)
    at tryCatch (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\regenerator-runtime\runtime.js:45:40)
    at Generator.invoke [as _invoke] (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\regenerator-runtime\runtime.js:2
71:22)
    at Generator.prototype.(anonymous function) [as next] (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\regenerator
-runtime\runtime.js:97:21)
    at asyncGeneratorStep (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\@babel\runtime\helpers\asyncToGenerator.js:
3:24)
    at _next (E:\Workspace\WebStormProjects\Ethereum\CloudNote\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:11268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an as
ync function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11268) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are n
ot handled will terminate the Node.js process with a non-zero exit code.
(node:11268) UnhandledPromiseRejectionWarning: #<Object>
(node:11268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an as
ync function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

and my code is as follows:

var Web3 = require('web3');
var fs = require('fs');
var Tx = require('ethereumjs-tx');
var ethabi = require('web3-eth-abi');
class Database{
    constructor(){
        this.contractAddress = 'my contract address...';
        this.gasPrice = '0x3B9ACA00';
        this.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/..."));
        this.abi = JSON.parse(fs.readFileSync("./CloudNote_sol_CloudNote.abi").toString());
        // this.contract = this.web3.eth.contract(this.abi).at(this.contractAddress);
        this.contract = this.web3.eth.Contract(this.abi,this.contractAddress);
    }
    getNonce(){
        var nonce = this.web3.eth.getTransactionCount("my account...");
        return nonce;
    }
    addUpdateNote(id,name,content,notefun){
        var estimateGas = this.web3.eth.estimateGas({
            to:this.contractAddress,
            data:notefun
        });
        estimateGas = this.web3.utils.toHex(estimateGas);
        var nonce = global.getNextNonce();
        var rawTx = {
            nonce:nonce,                
            gasPrice:this.gasPrice,     
            gasLimit: estimateGas,      
            to:this.contractAddress,    
            value:'0x00',               
            data:notefun,                
            chainId: 3
        }
        var tx = new Tx(rawTx);
        const privateKey = new Buffer.from('my private key...','hex');
        tx.sign(privateKey);
        var serializedTx = tx.serialize();
        return this.web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
    }

    addNote(id,name,content){
        var addNote = this.contract.methods.addNote(id,name,content).encodeABI();
        return this.addUpdateNote(id,name,content,addNote);
    }
    updateNote(id,name,content){
        var updateNote = this.contract.methods.updateNote(id,name,content).encodeABI();
        return this.addUpdateNote(id,name,content,updateNote);
    }
    getNote(id,name){
        var getNote = this.contract.methods.getNote(id,name).encodeABI();
        var result = this.web3.eth.call({
            to:this.contractAddress,
            data:getNote
        });
        return ethabi.decodeParameter('string',result);
    }
    queryTransactionStatus(hash){
        var result = this.web3.eth.getTransactionReceipt(hash);
        if (result != null){
            return parseInt(result.status,16);
        }
        return null;
    }
}

module.exports = Database;

Can someone give me a hand? Thanks!

@yuanziwoxin The bug reported affects web3 1.0.0-beta.15 and that specific bug was fixed in 1.0.0-beta.17. It seems a new bug affects more recent versions, I suggest to create a new bug report with a full working example and provide details like geth version used, solidity compiler, etc.

For a workaround the last working version I've used is 1.0.0-beta.37.

Was this page helpful?
0 / 5 - 0 ratings