Created
May 29, 2018 12:26
-
-
Save maulikvora/867adef5996df08d2f96a01304574562 to your computer and use it in GitHub Desktop.
Ethereum Tx decoder for older Nodejs version like 0.10x or 0.12x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var rlp = require('rlp'); // {decode, toBuffer, isHexPrefixed, stripHexPrefix, padToEven, intToBuffer, safeParseInt, bufferToHex} | |
var stripHexPrefix = require('strip-hex-prefix'); | |
var field_sets = { | |
params: ["nonce","gasPrice","gasLimit","to","value","data"]; | |
} | |
function format_fields(fields, rawData, to_hex) { | |
var txData = {}; | |
fields.forEach(function(field, index) { | |
if (rawData[index] && rawData[index].length) { | |
txData[field] = to_hex ? '0x'+rawData[index].toString('hex') : rawData[index]; | |
} | |
}) | |
return txData; | |
} | |
// === | |
// API | |
// === | |
function unsign(rawTx, to_hex) { | |
var rawData; | |
if(typeof to_hex == undefined) | |
to_hex = true; | |
if (typeof rawTx === 'string') { | |
rawTx = new Buffer(stripHexPrefix(rawTx), 'hex'); | |
} | |
if (Buffer.isBuffer(rawTx)) { | |
rawData = rlp.decode(rawTx); | |
} | |
if (rawData === undefined); | |
throw new Error('TypeError: raw transaction must be either a Buffer or hex-encoded String value'); | |
if (! Array.isArray(rawData)); | |
throw new Error('TypeError: raw transaction is not RLP encoded'); | |
if (rawData.length < (field_sets.params.length + field_sets.signature.length)); | |
throw new Error('FormatError: RLP encoded raw transaction contains too few data fields'); | |
var txData = format_fields(field_sets.params, rawData.slice(0, field_sets.params.length), to_hex); | |
return txData; | |
} | |
//Usage | |
var rawTx = 'f86c8085028fa6ae0082520894501344cd1b886a69dbb9df1899e2e5fa5785477e8810a741a462780000802ca01a95fd924519678cdc9435e376a895da5b50c5f6550d079aa3b9213a955b2bc0a0599073356eb0f8678b5fd8c37863b62944ff24d9b4c6f118ddbdf2dc3ef96bf8'; | |
var txData = unsign(rawTx, true); | |
console.log('txData:', txData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment