Ethereum RLP


RLP (Recursive Length Prefix) is the main encoding method used to serialize objects in Ethereum. Usages include generate raw transaction, data storage.


RLP Encoder

<?php 
use kornrunner\Keccak;

include_once "../libraries2/vendor/autoload.php";
include_once("html_iframe_header.php");

use Web3p\RLP\RLP;

$result = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	try {
		$rlp = new RLP;
		
		$firstTag = substr($_POST['string'], 0, 1);
		$lastTag  = substr($_POST['string'], -1);
		
		if ($firstTag == '[' AND $lastTag == ']') {
			$toEncode = json_decode($_POST['string'],true);
		
			if (json_last_error() !== JSON_ERROR_NONE) {
				throw new Exception("Invalid JSON-ARRAY string.");
			}
		} else {
			
			//auto cast if integer or float is detected
			
			if (ctype_digit($_POST['string'])) {
				$toEncode = (int)$_POST['string'];
			} else if (is_numeric($_POST['string'])) {
				$toEncode = (float)$_POST['string'];
			} else {
				$toEncode = $_POST['string'];
			}
		}
		$result = $rlp->encode($toEncode);
		
	} catch (Exception $e) {
        $errmsg .= "Problem found. " . $e->getMessage();
    }
}

if ($errmsg) {
?>
	<div class="alert alert-danger">
		<strong>Error!</strong> <?php echo $errmsg?>
	</div>
<?php
}

if ($result) {
?>
	<div class="alert alert-success">
		<?php echo $result;?>
	</div>
<?php
}
?>
<form action='' method='post'>
	<div class="form-group">
		<label for="string">Data To Encode:</label>
		<textarea class="form-control" type='text' name='string' id='string' rows=10><?php echo $_POST['string']?></textarea>
		<small>
			<ol style="padding-left: 0; list-style: inside decimal;">
				<li>
					To encode array, JSON-ARRAY serialized string must be applied and start with '[' and end with ']'.
				</li>
				
				<li>
					Numeric number will be casted to integer or float.
				</li>
			</ol>
		</small>
	</div>

	<input type='submit' class="btn btn-success btn-block"/>
</form>
<?php 
include_once("html_iframe_footer.php");
go/eth_rlp_encoder.go

package main

import(
	_ "fmt"
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"encoding/json"
	"strings"
	"math"
)

func rlpEncode(dataJson string) (map[string]string, error) {
	
	response := make(map[string]string)
	
	var thisError error	
	var arrJson []interface{}
	var rlpBytes []byte = []byte{}
	
	if thisError = json.Unmarshal([]byte(dataJson),&arrJson); thisError == nil {
		
		for k, v := range arrJson {
			
			switch v.(type) {
				case string:
					
					if strings.HasPrefix(v.(string), "0x") {
						arrJson[k], _ = hexutil.Decode(v.(string))
					}
				case float64:
					if (v.(float64) / math.Round(v.(float64))) == 1 {
						//convert if it is an integer
						arrJson[k] = uint64(arrJson[k].(float64))
					} 
				default:
				
			}
		}
		
		if rlpBytes, thisError = rlp.EncodeToBytes(arrJson); thisError==nil {
			response["rlpHex"] = hexutil.Encode(rlpBytes)
		}
		
	} 
	
	return response,thisError
}

go/templates/eth_rlp_encoder.html

{{ template "html_iframe_header.html" .}}

{{if .error}}
	<div class="alert alert-danger">
        <strong>Error!</strong> {{ .error }}
    </div>
{{else if .rlpHex}}
	<div class="alert alert-success">
		{{.rlpHex}}
	</div>
{{end}}

<form action='' method='post'>
	<div class="form-group">
		<label for="string">Data To Encode:</label>
		<textarea class="form-control" type='text' name='string' id='string' rows=10>{{.string}}</textarea>
		<small>
			<ol style="padding-left: 0; list-style: inside decimal;">
				<li>
					To encode array, JSON-ARRAY serialized string must be applied and start with '[' and end with ']'.
				</li>
				
				<li>
					Numeric number will be casted to integer or float.
				</li>
			</ol>
		</small>
	</div>

	<input type='submit' class="btn btn-success btn-block"/>
</form>

{{ template "html_iframe_footer.html" .}}

RLP Decoder

<?php 
use kornrunner\Keccak;

include_once "../libraries2/vendor/autoload.php";
include_once("html_iframe_header.php");

use Web3p\RLP\RLP;

$result = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	try {
		$rlp = new RLP;
		$rlpedStr = ltrim($_POST['rlped_string'], "0x");
		$result = $rlp->decode("0x" . $rlpedStr);
		
	} catch (Exception $e) {
        $errmsg .= "Problem found. " . $e->getMessage();
    }
}

if ($errmsg) {
?>
	<div class="alert alert-danger">
		<strong>Error!</strong> <?php echo $errmsg?>
	</div>
<?php
}

if ($result) {

	if (is_array($result)) {
?>
		<div class="alert alert-success">Result is in Array</div>
<?php
		echo "<pre>";
		var_dump($result);
		echo "</pre>";
	} else {
?>
		<div class="alert alert-success">
			<?php echo $result;?>
		</div>
<?php	
	}
}
?>
<form action='' method='post'>
	<div class="form-group">
		<label for="rlped_string">Data To Decode:</label>
		<input class="form-control" type='text' name='rlped_string' id='rlped_string' rows=10 value="<?php echo $_POST['rlped_string']?>">
		
		<small>
			Result is in HEX. Below is conversion tool from HEX to your desired data types.
			<ol style="padding-left: 0; list-style: inside decimal;">
				<li><a href="https://www.rapidtables.com/convert/number/hex-to-decimal.html" target="blank">HEX To Decimal</a></li>
				<li><a href="http://string-functions.com/hex-string.aspx" target="blank">HEX To String</a></li>
			</ol>
		</small>
			
			
		
	</div>

	<input type='submit' class="btn btn-success btn-block"/>
</form>
<?php 
include_once("html_iframe_footer.php");








Tutorials
About Us
Contents have been open source in GITHUB. Please give me a ⭐ if you found this helpful :)
Community
Problem? Raise me a new issue.
Support Us
Buy me a coffee. so i can spend more nights for this :)

BTCSCHOOLS would like to present you with more pratical but little theory throughout our tutorials. Pages' content are constantly keep reviewed to avoid mistakes, but we cannot warrant correctness of all contents. While using this site, you agree to accept our terms of use, cookie & privacy policy. Copyright 2019 by BTCSCHOOLS. All Rights Reserved.