Package org.aion.rlp

Class CompactEncoder


  • public class CompactEncoder
    extends Object
    Compact encoding of hex sequence with optional terminator

    The traditional compact way of encoding a hex string is to convert it into binary - that is, a string like 0f1248 would become three bytes 15, 18, 72. However, this approach has one slight problem: what if the length of the hex string is odd? In that case, there is no way to distinguish between, say, 0f1248 and f1248.

    Additionally, our application in the Merkle Patricia tree requires the additional feature that a hex string can also have a special "terminator symbol" at the end (denoted by the 'T'). A terminator symbol can occur only once, and only at the end.

    An alternative way of thinking about this to not think of there being a terminator symbol, but instead treat bit specifying the existence of the terminator symbol as a bit specifying that the given node encodes a final node, where the value is an actual value, rather than the hash of yet another node.

    To solve both of these issues, we force the first nibble of the final byte-stream to encode two flags, specifying oddness of length (ignoring the 'T' symbol) and terminator status; these are placed, respectively, into the two lowest significant bits of the first nibble. In the case of an even-length hex string, we must introduce a second nibble (of value zero), in addition to the encoded flags added as a first nibble, to ensure the resulting hex-string is still even in length and thus is representable by a whole number of bytes.

    Examples:

    • [ 1, 2, 3, 4, 5 ] '\x11\x23\x45'
    • [ 0, 1, 2, 3, 4, 5 ] '\x00\x01\x23\x45'
    • [ 0, 15, 1, 12, 11, 8, T ] '\x20\x0f\x1c\xb8'
    • [ 15, 1, 12, 11, 8, T ] '\x3f\x1c\xb8'
    • Constructor Detail

      • CompactEncoder

        public CompactEncoder()
    • Method Detail

      • packNibbles

        public static byte[] packNibbles​(byte[] nibbles)
        Pack nibbles to binary
        Parameters:
        nibbles - sequence. may have a terminator
        Returns:
        hex-encoded byte array
        Throws:
        NullPointerException - when given a null input
      • hasTerminator

        public static boolean hasTerminator​(byte[] packedKey)
        Throws:
        NullPointerException - when given a null input
      • unpackToNibbles

        public static byte[] unpackToNibbles​(byte[] str)
        Unpack a binary string to its nibbles equivalent
        Parameters:
        str - of binary data
        Returns:
        array of nibbles in byte-format
      • binToNibbles

        public static byte[] binToNibbles​(byte[] str)
        Transforms a binary array to hexadecimal format + terminator
        Parameters:
        str - byte[]
        Returns:
        array with each individual nibble adding a terminator at the end
      • binToNibblesNoTerminator

        public static byte[] binToNibblesNoTerminator​(byte[] str)