Skip to content

Necessary buffer padding details should be documented #5

@jselbie

Description

@jselbie

This statement in the docs could be much improved:

The buffer size must be chosen very carefully, if you are not sure about that choose your biggest guess.

I'd like to save everyone hours of debugging insanity.

Minimum buffer size is the summation of sizes of all serialized values and enough padding such that this size value is a multiple of 32. Or in other words, up to 31 bytes of padding is needed.

Don't allocate a buffer like this based solely on the summation of sizeOf results for each variable:

uint size = sizeOfBool()*3 + sizeOfUnit(32)*2 + sizeofAddress()*2;
bytes memory data = new bytes(size);

The above will lead to undefined behavior after serializing values into it, incorrect program behavior, and Truffle/Ganache will do even weirder stuff (freeze/crash).

Compute the size of the buffer to account for needed padding:

uint size = sizeOfBool()*3 + sizeOfUnit(32)*2 + sizeofAddress()*2;
if ((size % 32)  > 0) {
    size += 32 - (size % 32);
}
bytes memory data = new bytes(size);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions