[Ethereum] Signing raw transaction AssertionError: The field v must have byte length of 1

ethereumjsgo-ethereumweb3js

I have followed every option present in net to do Raw transaction I have followed

ethereumjs-tx

let resData = {};
var Tx = require('ethereumjs-tx')
var privateKey = new Buffer('0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')
var gasPrice = privateWeb3.eth.gasPrice;
var gasPriceHex = privateWeb3.toHex(gasPrice);
var nonce = privateWeb3.eth.getTransactionCount(req.body.fromAddress);
var nonceHex = privateWeb3.toHex(nonce);
var rawTx = {
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gasLimit: '0x2710000000',
    to: req.body.toAddress,
    from: req.body.fromAddress,
    data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
    chainId: req.body.chain
}

var tx = new Tx(rawTx)
console.log(tx.v);
tx.sign(privateKey)

var serializedTx = tx.serialize()
console.log(serializedTx.toString('hex'))

privateWeb3.eth.sendRawTransaction(serializedTx.toString('hex'), function(err, hash) {
    //  if (!err)
        console.log("hiii", err, hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"
});

This approach give me error in tx.sign(privateKey)

AssertionError: The field v must have byte length of 1
at Transaction.setter [as v] (node_modules/ethereumjs-util/index.js:609:9)

Best Answer

This may be caused by unexpectedly large chainId. It is used to compute tx.v.

See EIP155:

v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36

And ethereumjs-tx source:

// sig.v = 28

if (this._chainId > 0) {
  sig.v += this._chainId * 2 + 8
}

So, to fit v into a single byte, your chainId must be less than 0x6d (109 dec).

Ropsten has chainId = 3, mainnet has chainId = 1.