Skip to content

Commit

Permalink
fix: #4 error decoding empty buffer with rlp.NumericKind
Browse files Browse the repository at this point in the history
  • Loading branch information
qianbin committed Aug 9, 2018
1 parent b0745bd commit a09b010
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/lib/rlp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,15 @@ export namespace RLP {
public decode(buf: Buffer, ctx: string) {
assert(this.maxBytes ? buf.length <= this.maxBytes : true, ctx,
`expected less than ${this.maxBytes} bytes`)
assert(buf.length > 0 ? buf[0] !== 0 : true, ctx,

if (buf.length === 0) {
return 0
}

assert(buf[0] !== 0, ctx,
`expected canonical integer (no leading zero bytes)`)
const bn = new BigNumber('0x' + buf.toString('hex'))

const bn = new BigNumber(buf.toString('hex'), 16)
const num = bn.toNumber()
return Number.isSafeInteger(num) ? num : '0x' + bn.toString(16)
}
Expand Down
1 change: 1 addition & 0 deletions tests/rlp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ describe('rlp', () => {
})
it('numericKind decode', () => {
const kind = new RLP.NumericKind(8)
expect(kind.decode(Buffer.alloc(0), '')).equal(0)
expect(kind.decode(Buffer.from([1, 2, 3]), '')).equal(0x010203)
expect(kind.decode(Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]), '')).equal('0x102030405060708')

Expand Down

0 comments on commit a09b010

Please sign in to comment.