Recursive Length Prefix implementation
The purpose of RLP (Recursive Length Prefix) is to encode arbitrarily nested arrays of binary data, and RLP is the main encoding method used to serialize objects in Ethereum. The only purpose of RLP is to encode structure; encoding specific atomic data types (eg. strings, ints, floats) is left up to higher-order protocols; in Ethereum integers must be represented in big endian binary form with no leading zeroes (thus making the integer value zero be equivalent to the empty byte array).
npm install --save @polkajs/rlp
const RLP = require('@polkajs/rlp');
let encode = RLP.encode(['hello']);
console.log(encode);
// <Buffer c6 85 68 65 6c 6c 6f>
c6 - represents an array with a 6 byte buffer to follow (0xc6 - 0xc0)
85 - represents a string or number with the size of 5 (0x85 - 0x80)
let decode = RLP.decode(encode);
console.log(decode);
// [ <Buffer 68 65 6c 6c 6f> ] (ascii)
let str = decode[0].toString();
console.log(str);
// 'hello'
If you are only working with arrays and strings, this method has better decoding
const arr = ['a', 'abc', 5];
const encode = RLP.encode(arr);
const decode_str = RLP.decode_str(encode);
console.log(decode_str);
// ['a', 'abc', '\x05']
First byte of an encoded item
x: single byte, itself
|
|
0x7f == 127
0x80 == 128
|
x: [0, 55] byte long string, x-0x80 == length
|
0xb7 == 183
0xb8 == 184
|
x: [55, ] long string, x-0xf8 == length of the length
|
0xbf == 191
0xc0 == 192
|
x: [0, 55] byte long list, x-0xc0 == length
|
0xf7 == 247
0xf8 == 248
|
x: [55, ] long list, x-0xf8 == length of the length
|
0xff == 255
ISC License (ISC) Copyright 2017 Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC") Copyright (c) 1995-2003 by Internet Software Consortium
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.