There are two different encodings used.
Everything in the Bitcoin protocol, including transaction signatures and alert signatures, uses DER encoding. This results in 71 bytes signatures (on average), as there are several header bytes, and the R and S valued are variable length.
For message signatures, a custom encoding is used which is more compact (and more recent) and supports public key recovery (given a message and a signature, find which public key would have created it). The code you're referring to in the question is for creating such signatures.
A correct DER-encoded signature has the following form:
0x30
: a header byte indicating a compound structure.
- A 1-byte length descriptor for all what follows.
0x02
: a header byte indicating an integer.
- A 1-byte length descriptor for the R value
- The R coordinate, as a big-endian integer.
0x02
: a header byte indicating an integer.
- A 1-byte length descriptor for the S value.
- The S coordinate, as a big-endian integer.
Where initial 0x00
bytes for R and S are not allowed, except when their first byte would otherwise be above 0x7F
(in which case a single 0x00
in front is required). Also note that inside transaction signatures, an extra hashtype byte follows the actual signature data.