Skip to content

Commit

Permalink
Improve cli interface (#95)
Browse files Browse the repository at this point in the history
* improve cli interface and add examples to readme
* fix first example to use json string rather than number
* organize code, better error output, add string input validation
* re-add buffer hex encoding
Co-authored-by: acolytec3 <17355484+acolytec3@users.noreply.github.com>
  • Loading branch information
ryanio authored Jan 4, 2022
1 parent ced5ef2 commit 5d165b4
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 24 deletions.
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,15 @@ assert.deepEqual(nestedList, decoded)

## CLI

`rlp decode <hex string>`
`rlp encode <json String>`
`rlp encode <JSON string>`
`rlp decode <0x-prefixed hex string>`

### Examples

- `rlp encode '5'` => `0x05`
- `rlp encode '[5]'` => `0xc105`
- `rlp encode '["cat", "dog"]'` => `0xc88363617483646f67`
- `rlp decode 0xc88363617483646f67` => `["cat","dog"]`

## TESTS

Expand Down
54 changes: 36 additions & 18 deletions bin/rlp
Original file line number Diff line number Diff line change
@@ -1,35 +1,53 @@
#!/usr/bin/env node

const rlp = require('../dist/index.js')
const command = process.argv[2]
var raw = process.argv[3]
const method = process.argv[2]
const strInput = process.argv[3]

if (command === 'encode') {
if (typeof strInput !== 'string') {
return console.error(`Expected JSON string input, received type: ${typeof strInput}`)
}

if (method === 'encode') {
// Parse JSON
let json
try {
const json = JSON.parse(raw)
console.log(rlp.encode(json).toString('hex'))
} catch (e) {
console.log('invalid json')
}
} else {
if (!raw) {
raw = command
json = JSON.parse(strInput)
} catch (error) {
return console.error(`Error could not parse JSON: ${JSON.stringify(error)}`)
}

// Encode RLP
try {
console.log(baToJSON(rlp.decode(raw)))
const encoded = rlp.encode(json)
console.log('0x' + encoded.toString('hex'))
} catch (e) {
console.log('invalid RLP' + e)
console.error(`Error encoding RLP: ${JSON.stringify(error)}`)
}
} else if (method === 'decode') {
// Decode
try {
const decoded = rlp.decode(strInput)
const json = JSON.stringify(baToJSON(decoded))
console.log(json)
} catch (error) {
console.error(`Error decoding RLP: ${JSON.stringify(error)}`)
}
} else {
console.error('Unsupported method')
}

function baToJSON (ba) {
/**
* Buffer or Buffer Array to JSON
*/
function baToJSON(ba) {
if (Buffer.isBuffer(ba)) {
return ba.toString('hex')
} else if (ba instanceof Array) {
var array = []
for (var i = 0; i < ba.length; i++) {
array.push(baToJSON(ba[i]))
const arr = []
for (let i = 0; i < ba.length; i++) {
arr.push(baToJSON(ba[i]))
}
return array
return arr
}
}
32 changes: 28 additions & 4 deletions test/integration.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as assert from 'assert'
import { exec } from 'child_process'
import { promisify } from 'util'
import * as RLP from '../dist'
import * as vm from 'vm'

Expand All @@ -11,11 +12,34 @@ describe('Distribution:', function () {
})
})

const execAsync = promisify(exec)

describe('CLI command:', function () {
it('should be able to run CLI command', function () {
exec('./bin/rlp encode "[ 5 ]"', (_error, stdout) => {
assert.strictEqual(stdout.trim(), 'c105')
})
it('should be able to run CLI command', async function () {
const result = await execAsync('./bin/rlp encode "[ 5 ]"')
const resultFormatted = result.stdout.trim()
assert.strictEqual(resultFormatted, '0xc105')
})

const officalTests = require('./fixture/rlptest.json').tests
it('should return valid values for official tests', async function () {
// eslint-disable-next-line no-invalid-this
this.timeout(10000)

// eslint-disable-next-line no-restricted-syntax
for (const testName in officalTests) {
const { in: incoming, out } = officalTests[testName]

// skip if testing a big number
if (incoming[0] === '#') {
continue
}

const json = JSON.stringify(incoming)
const encodeResult = await execAsync(`./bin/rlp encode '${json}'`)
const encodeResultTrimmed = encodeResult.stdout.trim()
assert.strictEqual(encodeResultTrimmed, out.toLowerCase(), `should pass encoding ${testName}`)
}
})
})

Expand Down

0 comments on commit 5d165b4

Please sign in to comment.