ethjs/ethjs-util

intToBuffer() fails for numbers that produce odd length hex strings

vpulim opened this issue · 13 comments

ethjs-util

Issue Type

Description

The intToBuffer() function is broken after this PR was merged: #7

It fails for numbers that don't produce an even length hex string. It's breaking the following modules:

Steps to reproduce

const util = require('ethjs-util')

const buf = util.intToBuffer(1);
console.log(buf) // output: "<Buffer >" (expected: "<Buffer 01>")
assert.equal(buf.toString('hex'), '01');

Versions

  • Node/NPM: 9.8.0
  • Browser: N/A

This is breaking a lot more then just the above mentioned modules. I just wanted to sign a Transaction with ethereumjs-tx, which produced a wrong transaction now!
Before converting a hex-string into buffer we always need to make sure the length is even, or new Buffer will throw away these bytes

As a workaround I'm just using now Version 0.1.4 again.

This small bug spoils entire ethereumjs libraries. Please fix this issue as soon as possible. I have already wasted 1 day to fix this bug on my project.

@vpulim should be up in NPM ethjs-util@0.1.6 @ChandraNakka @simon-jentzsch

@SilentCicero still is not fixed, since lib/index.js still is not changed. Please push new version and unpublish 2 previous versions with npm unpublish. Also please push last changes to repo.
This breaks a really lot of things in ETH libraries...
@ChandraNakka @simon-jentzsch I'd recommmend use npm/yarn lock file.

@fanatid the module I pushed has the updated lib/index.js code in version 0.1.6:

'use strict';

var isHexPrefixed = require('is-hex-prefixed');
var stripHexPrefix = require('strip-hex-prefix');

/**
 * Pads a `String` to have an even length
 * @param {String} value
 * @return {String} output
 */
function padToEven(value) {
  var a = value; // eslint-disable-line

  if (typeof a !== 'string') {
    throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.');
  }

  if (a.length % 2) {
    a = '0' + a;
  }

  return a;
}

/**
 * Converts a `Number` into a hex `String`
 * @param {Number} i
 * @return {String}
 */
function intToHex(i) {
  var hex = i.toString(16); // eslint-disable-line

  return '0x' + hex;
}

/**
 * Converts an `Number` to a `Buffer`
 * @param {Number} i
 * @return {Buffer}
 */
function intToBuffer(i) {
  var hex = intToHex(i);

  return new Buffer(padToEven(hex.slice(2)), 'hex');
}

Can you please expand where the module is failing, please try installing the new version again.

Very strange. Sorry, looks like I was on @0.1.5 when tested (i.e. install dependencies for ethereumjs-tx before 0.1.6 was published).
Still, can you unpublish 0.1.5 so nobody can use it?
Thanks!

I will depreciate.

Not everybody read messages in console, since this library is used in applications which operate with big amounts of money, I think unpublish will be appropriate.

@SilentCicero Thanks a lot, now it's working :)