2

I am trying to spend an utxo sent to a p2sh address. The scriptsig (including the redeem script) is longer than 256 bytes. When the transaction is serialized there is only one byte to indicate the size of the scriptsig. How should I do? Thanks by advance.

3

The size is encoded as Compact size. These can be up to 9 bytes long and encode a size of anything between zero to 18446744073709551615 bytes.

The rules are (according to serialize.h) :

/**
 * Compact Size
 * size <  253        -- 1 byte
 * size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
 * size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
 * size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
 */
inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
{
    if (nSize < 253)             return sizeof(unsigned char);
    else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
    else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
    else                         return sizeof(unsigned char) + sizeof(uint64_t);
}

Which basically means, for any data of length L in bytes,

If L < 253, the encoding is just the value itself. Anything between 0x00 and 0xFC.

For larger sizes, we prepend the encoding with one byte 0xFD, 0xFE or 0xFF depending on how many bytes it would take to encode it. The sizes 253, 254 and 255 are an exception (easy to see why. their bytes are used for the encoding itself) and are treated as a two-byte size. The size bytes themselves are encoded in little endian.

If 253 <= L < 65535, the encoding is first the byte 0xFD, then the two bytes that make up the actual size. Your specifc value of 256 is in this range, and will be encoded as :

FD0001

FD because it's in the second range, and 0001 is the "reverse" of 0100.

The rest of the ranges behave the same, and their ranges are shown in the code snippet.

  • 2
    Note that in the specific case of spending P2SH, you never need 254 or 255, as the maximum allowed redeemscript is 520 bytes. – Pieter Wuille Dec 2 '17 at 21:44
  • 2
    The size bytes themselves are encoded in little endian. – amaclin Dec 2 '17 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.