Building a Blockchain: Serialization

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 data types (eg. strings, floats) is left up to higher-order protocols; but positive RLP 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). Deserialised positive integers with leading zeroes must be treated as invalid. The integer representation of string length must also be encoded this way, as well as integers in the payload. Additional information can be found in the Ethereum yellow paper Appendix B.

Encoding some simple byte arrays to RLP encoded byte arrays
Encoding an entity
public static byte[] encode(Transaction transaction) {byte[] rlpSender = RLPEncoder.encodeAddress(transaction.getSender());byte[] rlpReceiver = RLPEncoder.encodeAddress(transaction.getReceiver());byte[] rlpValue = RLPEncoder.encodeCoin(transaction.getValue());byte[] rlpNonce = RLPEncoder.encodeUnsignedLong(transaction.getNonce());byte[] rlpData = RLP.encode(transaction.getData());byte[] rlpGas = RLPEncoder.encodeUnsignedLong(transaction.getGas());byte[] rlpGasPrice = RLPEncoder.encodeCoin(transaction.getGasPrice());return RLP.encodeList(rlpSender, rlpReceiver, rlpValue, rlpNonce, rlpData, rlpGas, rlpGasPrice);}
public static Transaction decode(byte[] encoded) {byte[][] bytes = RLP.decodeList(encoded);if (bytes.length != 7)throw new IllegalArgumentException("Invalid transaction encoding");Address sender = RLPEncoder.decodeAddress(bytes[0]);Address receiver = RLPEncoder.decodeAddress(bytes[1]);Coin value = RLPEncoder.decodeCoin(bytes[2]);long nonce = RLPEncoder.decodeUnsignedLong(bytes[3]);byte[] data = ByteUtils.normalizeBytesToNull(RLP.decode(bytes[4]));long gas = RLPEncoder.decodeUnsignedLong(bytes[5]);Coin gasPrice = RLPEncoder.decodeCoin(bytes[6]);return new Transaction(sender, receiver, value, nonce, data, gas, gasPrice);}

Pending Work



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store