or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-rlp

Recursive Length Prefix (RLP) encoding and decoding library for Node.js and browser environments, fundamental for Ethereum ecosystem data serialization

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/rlp@3.0.x

To install, run

npx @tessl/cli install tessl/npm-rlp@3.0.0

0

# RLP (Recursive Length Prefix)

1

2

RLP is a comprehensive implementation of Recursive Length Prefix encoding and decoding for Node.js and browser environments. RLP is a fundamental serialization method used throughout the Ethereum ecosystem for encoding arbitrarily nested arrays of binary data. This zero-dependency library provides a simple API with `encode()` and `decode()` functions that handle arrays, Uint8Arrays, strings, numbers, and nested data structures with high performance.

3

4

## Package Information

5

6

- **Package Name**: rlp

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install rlp`

10

11

## Core Imports

12

13

```typescript

14

import RLP from "rlp";

15

import { encode, decode, Input, NestedUint8Array, Decoded, utils } from "rlp";

16

```

17

18

For CommonJS:

19

20

```javascript

21

const RLP = require("rlp");

22

const { encode, decode, utils } = require("rlp");

23

```

24

25

## Basic Usage

26

27

```typescript

28

import RLP from "rlp";

29

30

// Encode various data types

31

const encodedString = RLP.encode("hello");

32

const encodedNumber = RLP.encode(42);

33

const encodedArray = RLP.encode(["cat", "dog"]);

34

const encodedNested = RLP.encode([[], [[]], [[], [[]]]]);

35

36

// Decode RLP data

37

const decoded = RLP.decode(encodedArray);

38

// Result: ["cat", "dog"] as Uint8Array | NestedUint8Array

39

40

// Stream decoding (returns remainder)

41

const streamResult = RLP.decode(encodedData, true);

42

// Result: { data: Uint8Array | NestedUint8Array, remainder: Uint8Array }

43

```

44

45

## Architecture

46

47

RLP implements the Recursive Length Prefix specification with several key components:

48

49

- **Encoding Engine**: Converts JavaScript data types to RLP-encoded Uint8Arrays

50

- **Decoding Engine**: Parses RLP-encoded data back to nested Uint8Array structures

51

- **Type System**: Full TypeScript support with precise type definitions for inputs and outputs

52

- **Utility Functions**: Helper functions for byte manipulation and conversion

53

- **CLI Interface**: Command-line tool for encoding and decoding operations

54

55

## Capabilities

56

57

### RLP Encoding

58

59

Encodes various JavaScript data types into RLP format according to the Ethereum specification.

60

61

```typescript { .api }

62

/**

63

* RLP Encoding based on https://eth.wiki/en/fundamentals/rlp

64

* This function takes in data, converts it to Uint8Array if not,

65

* and adds a length for recursion.

66

* @param input - Will be converted to Uint8Array

67

* @returns Uint8Array of encoded data

68

*/

69

function encode(input: Input): Uint8Array;

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

import { encode } from "rlp";

76

77

// Encode a string

78

const encodedString = encode("hello");

79

80

// Encode a number

81

const encodedNumber = encode(42);

82

83

// Encode an array

84

const encodedArray = encode(["cat", "dog"]);

85

86

// Encode nested arrays

87

const encodedNested = encode([[], [[]], [[], [[]]]]);

88

89

// Encode mixed types

90

const encodedMixed = encode([42, "hello", [1, 2, 3]]);

91

```

92

93

### RLP Decoding

94

95

Decodes RLP-encoded data back to nested Uint8Array structures. Supports both complete and stream decoding modes.

96

97

```typescript { .api }

98

/**

99

* RLP Decoding based on https://eth.wiki/en/fundamentals/rlp

100

* @param input - Will be converted to Uint8Array

101

* @param stream - Is the input a stream (false by default)

102

* @returns decoded Array of Uint8Arrays containing the original message

103

*/

104

function decode(input: Input, stream?: false): Uint8Array | NestedUint8Array;

105

function decode(input: Input, stream?: true): Decoded;

106

```

107

108

**Usage Examples:**

109

110

```typescript

111

import { decode } from "rlp";

112

113

// Standard decoding (throws if remainder exists)

114

const decoded = decode(encodedData);

115

116

// Stream decoding (returns data and remainder)

117

const streamResult = decode(encodedData, true);

118

console.log(streamResult.data);

119

console.log(streamResult.remainder);

120

121

// Decode from hex string

122

const decodedFromHex = decode("0xc88363617483646f67");

123

```

124

125

### Default Export

126

127

The library provides a default export object containing both encode and decode functions.

128

129

```typescript { .api }

130

const RLP: {

131

encode: (input: Input) => Uint8Array;

132

decode: {

133

(input: Input, stream?: false): Uint8Array | NestedUint8Array;

134

(input: Input, stream?: true): Decoded;

135

};

136

};

137

```

138

139

**Usage Example:**

140

141

```typescript

142

import RLP from "rlp";

143

144

const encoded = RLP.encode(["hello", "world"]);

145

const decoded = RLP.decode(encoded);

146

```

147

148

### Utility Functions

149

150

Helper functions for byte manipulation and data conversion operations.

151

152

```typescript { .api }

153

const utils: {

154

/** Convert Uint8Array to hexadecimal string representation */

155

bytesToHex: (uint8a: Uint8Array) => string;

156

/** Concatenate multiple Uint8Arrays into a single Uint8Array */

157

concatBytes: (...arrays: Uint8Array[]) => Uint8Array;

158

/** Convert hexadecimal string to Uint8Array */

159

hexToBytes: (hex: string) => Uint8Array;

160

/** Convert UTF-8 string to Uint8Array using TextEncoder */

161

utf8ToBytes: (utf: string) => Uint8Array;

162

};

163

```

164

165

**Usage Examples:**

166

167

```typescript

168

import { utils } from "rlp";

169

170

// Convert bytes to hex

171

const hex = utils.bytesToHex(new Uint8Array([72, 101, 108, 108, 111]));

172

// Result: "48656c6c6f"

173

174

// Convert hex to bytes

175

const bytes = utils.hexToBytes("48656c6c6f");

176

// Result: Uint8Array([72, 101, 108, 108, 111])

177

178

// Convert UTF-8 string to bytes

179

const utf8Bytes = utils.utf8ToBytes("hello");

180

181

// Concatenate byte arrays

182

const combined = utils.concatBytes(

183

new Uint8Array([1, 2, 3]),

184

new Uint8Array([4, 5, 6])

185

);

186

// Result: Uint8Array([1, 2, 3, 4, 5, 6])

187

```

188

189

### CLI Interface

190

191

Command-line interface for encoding and decoding RLP data directly from the terminal.

192

193

```bash

194

# Encode JSON data to RLP

195

rlp encode '["cat", "dog"]'

196

# Output: 0xc88363617483646f67

197

198

# Decode RLP data to JSON

199

rlp decode 0xc88363617483646f67

200

# Output: ["cat","dog"]

201

202

# Encode simple values

203

rlp encode '5'

204

# Output: 0x05

205

206

# Encode nested arrays

207

rlp encode '[5]'

208

# Output: 0xc105

209

```

210

211

## Types

212

213

```typescript { .api }

214

/** Union type for all valid RLP input data types */

215

type Input = string | number | bigint | Uint8Array | Array<Input> | null | undefined;

216

217

/** Nested array structure of Uint8Arrays representing decoded RLP data */

218

type NestedUint8Array = Array<Uint8Array | NestedUint8Array>;

219

220

/** Result structure for stream decoding operations */

221

interface Decoded {

222

/** The decoded data as Uint8Array or nested structure */

223

data: Uint8Array | NestedUint8Array;

224

/** Any remaining bytes not consumed during decoding */

225

remainder: Uint8Array;

226

}

227

```

228

229

## Error Handling

230

231

The library throws descriptive errors for various invalid conditions:

232

233

- **Invalid RLP encoding format**: When the input data doesn't conform to RLP specification

234

- **Out-of-bounds operations**: When trying to access data beyond array boundaries

235

- **Invalid hex sequences**: When hex strings contain invalid characters

236

- **Unsupported input types**: When input data types cannot be converted to Uint8Array

237

- **Malformed length prefixes**: When RLP length encoding is corrupted

238

239

**Common Error Examples:**

240

241

```typescript

242

import { decode } from "rlp";

243

244

try {

245

decode("invalid-hex");

246

} catch (error) {

247

// Error: hexToBytes: received invalid unpadded hex

248

}

249

250

try {

251

decode(new Uint8Array([0xef, 0xde, 0xbd]));

252

} catch (error) {

253

// Error: invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds

254

}

255

```