Prusa Research publishes the binary G-code specification with its reference library, libbgcode. This page follows that specification (version 1) and the library. All integers are little-endian.
Block order
- File header
- File metadata block (optional)
- Printer metadata block
- Thumbnail blocks (optional, one per image)
- Print metadata block
- Slicer metadata block
- Slicer3 metadata block (optional; libbgcode, see below)
- G-code blocks, or for an encrypted file (Encrypted files) an identity block, one or more key blocks and encrypted blocks
The specification (doc/specifications.md) lists the sequence without the
Slicer3 block. libbgcode’s writer (Binarizer::initialize) writes the blocks
in the order above, writes the file metadata block only if it has content, and refuses
to continue without printer and print metadata and without at least one of the two
slicer blocks. Its validity check (is_valid_binary_gcode) requires, after
the optional file metadata block, a printer metadata block, then any number of
thumbnail blocks, then a print metadata block, then a slicer metadata block, and then
G-code blocks. The block that follows the slicer block is read and then skipped
without any check of its type, and that block may itself be the first
G-code block: no extra block is needed between the slicer block and the G-code. (After
it, every following block must be a G-code block; a file that ends right after the slicer
block is an error, because that next block header cannot be read.) That unchecked place is
where the Slicer3 block fits. Any other block type out of place gives an invalid-block-type
error. Source: is_valid_binary_gcode in core.cpp (libbgcode
main, raw).
What the printer firmware accepts
Source: Prusa-Firmware-Buddy (raw src/common/gcode/gcode_reader_binary.cpp, src/common/e2ee/utils.cpp and utils.hpp, lib/AddLibbgcode.cmake). The firmware does not call libbgcode’s is_valid_binary_gcode; it builds only libbgcode’s core part and walks the blocks itself.
The firmware’s copy of libbgcode (lib/libbgcode in that repository, raw src/LibBGCode/core/core.hpp, core.cpp, core_impl.hpp) is not the same as the public main branch: it adds block types 6 to 8 (Encrypted files). Its rules for values it does not know, in both firmware builds, are these:
- A file header whose magic is not
GCDEor whose checksum type is 2 or more is refused (“Invalid BGCODE file header”). The version number is not checked. - A block whose type is 9 or more, or whose compression is 4 or more, makes the block header unreadable: reading stops with an error and the file is not printable (
read_next_block_headerreturnsInvalidBlockTypeorInvalidCompressionType). A block is therefore never skipped for being of an unknown type; only types 0 to 8 can appear. - An unreadable header is not the same as “a block that is not a G-code block”: blocks of types 0 to 8 that the reader does not need are skipped by their stored size.
- Build without encrypted-file support:
valid_for_printreads block headers one after another and accepts the file at the first block of type G-code; the order of the blocks before it is not checked, and a file with no G-code block is refused (“File doesn’t contain any print instructions”). Its index step (generate_index,gcode_reader_binary.cpp) also reads blocks in any order until the first G-code (or encrypted) block, and keeps in the index the last readable printer metadata block (INI, uncompressed; each later one replaces the position of the earlier) and, for each thumbnail the caller asked for, the last block that matches it (by format and size); other block types are skipped. The reader’s search without an index (stream_metadata_start, andstream_thumbnail_startfor thumbnails) goes the other way: it stops at the first readable printer metadata block, or the first thumbnail that matches, before the first G-code block. A file with two printer metadata blocks is therefore read differently with and without the index. - Build with encrypted-file support: a block-sequence validator adds rules: every metadata block must come before any identity, key or G-code block; an identity block must start exactly where the last metadata block ends; the first key block must start exactly where the identity block ends (and an identity block must exist); an encrypted block must start exactly where the key block ends, after an identity and a key block; an unencrypted G-code block after an identity block is refused.
- In the build without encrypted-file support, an encrypted file (types 6 to 8) has no block of type 1, so it is refused as having no print instructions. The layouts of types 6 to 8 are in Encrypted files.
File header
| Offset | Size | Type | Name | Meaning |
|---|---|---|---|---|
| 0 | 4 | char[4] | Magic number | GCDE (47 43 44 45) |
| 4 | 4 | uint32 | Version | 1 |
| 8 | 2 | uint16 | Checksum type | 0 none, 1 CRC-32 |
Blocks
Every block is a header, parameters, data and, when the file uses checksums, a checksum.
| Offset | Size | Type | Name | Meaning |
|---|---|---|---|---|
| 0 | 2 | uint16 | Type | Block type; see below |
| 2 | 2 | uint16 | Compression | See below |
| 4 | 4 | uint32 | Uncompressed size | Size of the data when uncompressed |
| 8 | 4 | uint32 | Compressed size | Size of the stored data; present only when Compression is not 0 |
So the header is 8 bytes when the data is uncompressed and 12 bytes otherwise. The
stored data is Uncompressed size bytes long when Compression is 0, and
Compressed size bytes otherwise. With CRC-32 checksums, 4 bytes follow
the data: the CRC-32 of the block header, parameters and stored data.
CRC-32
When the file header’s checksum type is 1, every block ends with a 4-byte checksum
(checksum_size is 4 for CRC-32, 0 for none). The algorithm is in
crc32_sw (core_impl.hpp): the reflected CRC-32 with polynomial
0xEDB88320, the value starting from 0xFFFFFFFF and
exclusive-ored with 0xFFFFFFFF at the end, as in zlib’s crc32.
The checksum is stored as 4 bytes, least significant byte first. It covers, in this
order and as one running CRC:
- the block header’s type (2 bytes), compression (2 bytes) and uncompressed size (4 bytes);
- the compressed size (4 bytes), only when Compression is not 0, exactly as the header is stored, so an uncompressed block’s 8-byte header is covered and no compressed size is included;
- the block parameters (encoding, or format, width and height);
- the stored data, compressed if the block is compressed.
The file header (its first 10 bytes) is not covered, and there is no checksum after it.
verify_block_checksum recomputes the CRC the same way and compares it with
the stored four bytes.
Block types
| Type | Block | Parameters | Data |
|---|---|---|---|
| 0 | File metadata | uint16 encoding | Key-value pairs about the file, such as the producing software |
| 1 | G-code | uint16 encoding | A part of the G-code program |
| 2 | Slicer metadata | uint16 encoding | Key-value pairs made and used by the slicer, such as its settings |
| 3 | Printer metadata | uint16 encoding | Key-value pairs used by the printer, such as printer model and nozzle diameter |
| 4 | Print metadata | uint16 encoding | Key-value pairs about the print, such as print time and material used |
| 5 | Thumbnail | uint16 format, uint16 width, uint16 height | One preview image |
| 6 | Identity | uint16 signing cypher, uint8 flags | Who made the file: a public key, a name and two hashes, signed; see below |
| 7 | Key | uint16 encryption | The symmetric keys for the encrypted blocks, for one printer; see below |
| 8 | Encrypted | uint16 encryption, uint8 last-block flag | A whole block (header, parameters and data), AES-encrypted, with HMACs; see below |
Types 6 to 8 are not in the specification or in the public libbgcode main branch (EBlockType ends at Thumbnail). They are defined in the copy of libbgcode inside Prusa-Firmware-Buddy, where block_parameters_size gives the parameter sizes shown (3, 2 and 3 bytes).
Compression
| Value | Meaning |
|---|---|
| 0 | None |
| 1 | Deflate: a zlib stream (libbgcode uses deflateInit and inflateInit, so the data has the 2-byte zlib header and checksum trailer, not raw deflate) |
| 2 | Heatshrink, window size 11, lookahead 4 (bit stream) |
| 3 | Heatshrink, window size 12, lookahead 4 (bit stream) |
Encodings
| Blocks | Value | Meaning |
|---|---|---|
| Metadata blocks | 0 | INI: lines of key=value, each ending in a line feed. A reader splits a line at its first = and ignores a line without one |
| Metadata blocks | 1 | JSON (EMetadataEncodingType::JSON): the data is one JSON text; see Slicer3 metadata |
| G-code blocks | 0 | Plain G-code text |
| G-code blocks | 1 | MeatPack, with comments removed |
| G-code blocks | 2 | MeatPack, keeping comment lines |
Thumbnail formats
| Value | Format |
|---|---|
| 0 | PNG |
| 1 | JPEG |
| 2 | QOI |
What the readers do with a thumbnail block (sources: binarize.cpp, ThumbnailBlock::write and read_data, libbgcode main; gcode_reader_binary.cpp of Prusa-Firmware-Buddy; both raw):
- libbgcode refuses, when writing and when reading a block, a format above 2 (the formats count is one more than QOI, so only 0, 1 and 2 pass), a width of 0, a height of 0, and an empty image (data size 0).
- libbgcode writes the block uncompressed (the block header says compression 0) and reads the data as
uncompressed_sizebytes; the thumbnail data is already compressed image data. - The firmware ignores a thumbnail block whose compression is not 0 (
thumbnail_detailsreturns nothing: “no compression supported on images”) and reads the data as it is. It maps only format 0 (PNG) and format 2 (QOI) to an image type it can use; a JPEG block (format 1) gets the typeUnknown, and what the firmware does with anUnknownthumbnail beyond that was not read.
Reader limits on block size
The format itself limits a block only by its two 32-bit size fields (a little under 4 GiB of stored data, and as much uncompressed). The size a reader accepts is a choice of the reader:
- libbgcode’s reader:
binarize.cpp(prusa3d/libbgcodemain, raw) holdsg_max_block_data_size, 16 MiB (16 × 1024 × 1024) by default, which a program can change withset_max_block_data_size.block_sizes_within_limitchecks both the uncompressed size and the compressed size of the header, before either is used to allocate, and the reading of a metadata block, a G-code block and a thumbnail returnsEResult::BlockTooLarge(“Block data size exceeds the configured maximum”) when either is over the limit. The limit is a memory rule, not a format rule: the comment in the source says it is about 150 times the largest block seen in practice, and that peak memory is about three times the limit, as the compressed, the decompressed and the decoded data are held together. The function that undoes the compression refuses an uncompressed size over the limit in the same way, and stops a stream that would give more. - The printer firmware: Prusa-Firmware-Buddy keeps a copy of
binarize.cppinlib/libbgcode, with the same 16 MiB default, but does not build it:lib/AddLibbgcode.cmake(raw) setsLibBGCode_BUILD_COMPONENT_BinarizetoOFF(and the Convert component and the tests too), and builds only the core component (bgcode_core). The firmware therefore has none of the functions that apply the limit (block_sizes_within_limit,set_max_block_data_sizeand the binarize readers); the limit does not exist there. Its G-code reader (src/common/gcode/gcode_reader_binary.cpp, raw) reads block headers with the core library and streams the data of the G-code block through its own decoders (Heatshrink 11/4 and 12/4, or none; a Deflate block is refused there), so a G-code block over 16 MiB is not refused for its size. The files were read, not run.
A file with a block over 16 MiB is therefore valid, and readable by the firmware’s streaming reader, but a program that reads blocks with libbgcode’s defaults refuses it. The viewer reads blocks of any size, in windows, and says so in the Overview.
The Heatshrink bit stream
Compression values 2 and 3 hold the output of the heatshrink library (Scott Vokes, version 0.4.1 in heatshrink_common.h), an LZSS compressor. Sources, raw from github.com/atomicobject/heatshrink: heatshrink_decoder.c, heatshrink_encoder.c, heatshrink_common.h; and from prusa3d/libbgcode binarize.cpp, which fixes the parameters (window 11 for value 2 and 12 for value 3, lookahead 4 in both, set in both the encoder and the decoder call).
Parameters
Two numbers define the stream: w, the window size in bits (11: a 2,048-byte window; 12: 4,096 bytes), and l, the lookahead size in bits (4 here). The library accepts w from 4 to 15 and requires l of at least 3 and less than w. Neither number is stored in the stream: the block’s compression value is the only record of them, and the block header’s uncompressed size says how many bytes the stream expands to.
Tokens
The data is a sequence of bits. Bits are taken from each byte starting at the most significant bit (0x80) and bytes are taken in order. A token starts with a one-bit tag:
| Tag | Then | Output |
|---|---|---|
1 (literal) | 8 bits: a byte, most significant bit first | That byte. |
0 (back-reference) | w bits: index; then l bits: count (each most significant bit first) | count + 1 bytes (1 to 2l, that is 1 to 16) copied from index + 1 bytes back (1 to 2w) in the data produced so far. |
- The copy runs one byte at a time, so a distance shorter than the count repeats the bytes just written (a distance of 1 with a count of 16 writes one byte 16 times).
- The decoder’s window starts filled with zero bytes. A back-reference that reaches back past the start of the output therefore reads zeros; the decoder does not check it. A writer never produces one, so such a stream is not a valid output of the encoder.
- An encoder (
find_longest_match) uses a back-reference only when the match is longer than (1 + w + l) ÷ 8 bytes, with the division rounded down: for both Prusa settings that is 2, so only matches of 3 to 16 bytes become back-references and everything else is a literal. A decoder does not enforce this. - The index field holds the distance minus 1 and the count field the length minus 1 (the encoder writes
match_pos - 1andmatch_length - 1).
End of the stream
There is no end marker and no length. The encoder pads the last byte with zero bits (st_flush_bit_buffer). Because a zero tag starts a back-reference, the padding can look like the start of one whose fields are all zeros; the decoder’s finish check accepts that when no input bytes are left. The decoder’s bit reader (get_bits) refuses to start a field when fewer bits remain in the input than the field needs, so a partial token at the very end, such as a tag bit followed by fewer than 8 literal bits, is dropped without an error. A reader stops when it has produced the uncompressed size from the block header. libbgcode’s decoder (binarize.cpp) treats a block as valid only if exactly the declared number of bytes comes out, the decoder has no pending output and no input is left over; a declared uncompressed size of 0 is valid only with an empty compressed payload.
What the printer firmware reads
The Prusa-Firmware-Buddy G-code reader (src/common/gcode/gcode_reader_binary.cpp, init_decompression) decodes G-code blocks with compression 0, 2 (window 11, lookahead 4) and 3 (window 12, lookahead 4) only; any other value, including Deflate, makes it refuse the block. It also ignores metadata blocks that are compressed or not INI-encoded (is_readable_metadata: “We don’t support compressed metadata”). A file meant for the printer therefore needs Heatshrink or no compression for its G-code blocks.
JSON metadata and the Slicer3 block
The specification’s tables list only encoding 0 (INI) for metadata blocks. libbgcode
(core.hpp, EMetadataEncodingType) defines two: INI = 0 and
JSON = 1. A metadata block’s parameter is that 16-bit value, and the reader accepts
either for any metadata block. For JSON the library does not parse the text: the
whole block data is kept as one string under an empty key
(decode_metadata), and the writer accepts a block with exactly one such value
(encode_metadata returns false otherwise).
The Slicer3MetadataBlock (binarize.hpp) is a second block
of type 2 (the same type number as the slicer metadata block), with encoding 1, holding
a JSON text for the slicer. Binarizer::initialize writes it directly after
the INI slicer metadata block, if it has content, with its own compression setting
(slicer3_metadata); a file may have the INI block, the Slicer3 block, or
both, but at least one. A reader tells the two apart by the encoding parameter of a
type-2 block (peek_slicer_metadata_block: 1 means Slicer3, otherwise
ordinary slicer metadata). The block order is as in Block order.
Library quirk: the reader’s check on the encoding value is value > count,
with a count of 2 for metadata and 3 for G-code, so a value of 2 (metadata) or 3
(G-code) is not refused by that check; decoding then yields no data.
Encrypted files: identity, key and encrypted blocks
Sources, raw from github.com/prusa3d/Prusa-Firmware-Buddy (master): lib/libbgcode/src/LibBGCode/core/core.hpp, core.cpp; src/common/e2ee/e2ee.cpp, e2ee.hpp, hmac.cpp, decryptor.cpp, utils.cpp, key.cpp, sha256_multiuse.cpp; and src/common/gcode/gcode_reader_binary.cpp. The layouts below are what that reader requires. The software that writes such files was not read, and nothing here says which products do. All sizes and offsets are bytes; integers are little-endian as elsewhere. Every block of types 6 to 8 has the ordinary block header and, with CRC-32 checksums, the ordinary checksum.
Block sequence
- The metadata blocks as in an ordinary file (file, printer, thumbnails, print, slicer; the firmware’s check allows a second slicer block).
- One identity block, starting exactly where the last metadata block ends.
- One or more key blocks. The first starts exactly where the identity block ends. Later ones are not required to be adjacent by the sequence check; the first encrypted block must start exactly where the last key block seen ends.
- Encrypted blocks, one after another, in place of the G-code blocks. The last has its last-block flag set.
- Every metadata block (types 0, 3, 4, 2 and 5) must come before the identity block, key blocks and G-code or encrypted blocks.
- A block of type 1 (plain G-code) after an identity block is refused: an encrypted file holds no plain G-code.
- A key block before the identity block, or an encrypted block before the identity block or before a key block, is refused.
- The firmware’s
is_valid_binary_gcode(its copy of the core library) follows the same order: after the slicer block (and an optional second slicer block) it accepts either an identity block or a G-code block; after an identity block it skips any number of key blocks and then requires every remaining block to be an encrypted block.
Identity block (type 6)
| Part | Size | Meaning |
|---|---|---|
| Parameter: cypher | 2 | 0 RSA. Any other value is refused (“Unknown Identity block cypher”). |
| Parameter: flags | 1 | Bit 0 (1): ONE_TIME_IDENTITY (EIdentityFlags in the firmware’s core.hpp). What the sources read show is only this: read_and_verify_identity_block (e2ee.cpp) copies the bit into the identity information (one_time_identity, later IdentityInfo::one_time), which the G-code reader passes, with the identity’s name and key hash, to the printer’s trusted-identity check and, at the “Ask” level, to set_identity_info. What the printer then does with the bit (for example, whether it offers to remember the identity) was not read, so it is not stated here. |
| Key length | 2 | Length of the public key that follows. |
| Public key | key length | The signer’s RSA public key in DER form (read with mbedtls_pk_parse_public_key). The firmware’s buffer is 400 bytes. |
| Name length | 1 | Length of the name; at most 31 (“Identity name too long” otherwise). |
| Name | name length | The identity’s name, not null-terminated. |
| Intro hash | 32 | SHA-256 of the file header and the metadata blocks (rule below). |
| Key block hash | 32 | SHA-256 over the key blocks (rule below). |
| Signature | 256 | RSA signature, RSASSA-PSS with SHA-256 (mbedtls_rsa_rsassa_pss_verify), made with the private key matching the public key in this block. It covers the block header (8 bytes, as stored), the parameters (3 bytes) and all data before the signature. It must be exactly the key’s modulus length, so the keys are 2048-bit. |
- The block must be uncompressed (“Compressed identity block not supported”). Its data size must be at least 323 bytes (2 + 1 + 64 + 256 with empty key and name) and at most 256 + 2 + 400 + 1 + 31 + 64 = 754.
- The identity block is a signature by the key it carries, not a certificate: it proves the file was not altered after signing, and the printer decides separately whether it trusts that key. The firmware identifies a key by the SHA-256 of its DER public key, written as 64 hexadecimal digits (
get_key_hash_string). Its identity check level is one of known only (an unknown identity aborts), ask (the user may trust it permanently, for this print only, or abort) and any identity (an unknown identity is kept temporarily and the file is printed). This is printer policy and not a file rule. - The signature and the two hashes are checked only in the firmware’s “full check”; a quick check reads the layout without verifying them.
The two hashes
The firmware keeps one running SHA-256 (SHA256MultiuseHash), and reading the hash also restarts it:
- Intro hash: starts with the file header’s magic (4), version (4) and checksum type (2). For each metadata block (types 0, 2, 3, 4 and 5, in file order) it adds the block header as stored, the parameters, the stored data (compressed size if compressed) and, with CRC-32 checksums, the 4 checksum bytes. The identity block is not included. The value is compared with the identity block’s intro hash.
- Key block hash: starts again after the identity block. For each key block, in file order, it adds the block header as stored, the parameters (2 bytes), the data and, with CRC-32 checksums, the 4 checksum bytes. The value, taken when the first encrypted block is reached, is compared with the identity block’s key block hash (“Key block hash mismatch” otherwise).
A mismatch of the intro hash is reported as “File has corrupted metadata”.
Key block (type 7)
| Parameter value | Meaning | Data (the block is uncompressed) |
|---|---|---|
0 | None: the keys are stored in the clear | 32 bytes: the 16-byte AES encryption key, then the 16-byte HMAC signing key. |
1 | RSA encrypted and signed | 512 bytes: 256 bytes of RSA-OAEP ciphertext (SHA-256, to the printer’s 2048-bit public key), then a 256-byte RSASSA-PSS SHA-256 signature, made with the identity’s key, over those 256 ciphertext bytes. The ciphertext decrypts to exactly 96 bytes: the SHA-256 of the identity’s DER public key (32), the SHA-256 of the printer’s DER public key (32), the encryption key (16) and the signing key (16). Both hashes must match the keys the reader knows. |
- A file carries one key block per printer it can be read by. A printer that cannot decrypt a key block (different private key, hash mismatch, bad signature, wrong data size, compressed block, or a parameter value other than 0 and 1, whose data is read and skipped) moves on to the next. If none of them opens, it reports “Bgcode not encrypted for this printer!”.
- The number of key blocks is the number of HMACs stored in each encrypted block (below), and the position of the printer’s key block among them (counting from 0) is the position of its HMAC.
Encrypted block (type 8)
| Part | Size | Meaning |
|---|---|---|
| Parameter: encryption | 2 | 0 AES-128 in CBC mode with HMAC-SHA-256. Any other value is an error. |
| Parameter: last block | 1 | Non-zero on the last encrypted block of the file. |
| Ciphertext | uncompressed size − 32 × key blocks | A multiple of 16 bytes: AES-128-CBC of the inner block (below), padded with PKCS#7 (1 to 16 bytes, each holding the padding length). |
| HMACs | 32 × number of key blocks | One HMAC-SHA-256 per key block, in the key blocks’ order. |
The outer block header’s uncompressed size is the size of the ciphertext plus all the HMACs (the firmware passes that field to its decryptor as the size to read). It does not check the outer compression field; it is meant to be 0, which gives an 8-byte header.
- Inner block: the decrypted bytes are an ordinary block without a checksum: a block header (type, compression, uncompressed size, compressed size if compressed), the parameters (for G-code, the 2-byte encoding), and the data. The firmware reads no checksum inside. G-code is wanted, so the inner type is 1; the compression and encoding values are the ordinary ones (0, 2, 3 for compression, as the firmware reads them).
- Cipher: AES-128 with the 16-byte encryption key, CBC. The initialisation vector is 16 bytes: the file position of the encrypted block’s header as 8 little-endian bytes (the offset of its first byte, type field included), then 8 zero bytes. Each encrypted block starts again from that vector, so blocks can be decrypted separately.
- HMAC: HMAC-SHA-256 with the 16-byte signing key over, in order: the outer block header as stored, the 16-byte initialisation vector above, the parameters (3 bytes) and the ciphertext. The HMACs themselves and the CRC are not included. The block’s own HMAC is the one at index (key block position) among the 32-byte entries at the end of the data.
- Checksum: with CRC-32, the usual 4 bytes follow, covering the outer header, the parameters, the ciphertext and all the HMACs.
- Chain rules: every block after the first encrypted block must also be of type 8 (otherwise an error), must have the same inner type, inner compression and inner encoding as the previous one, and must pass its HMAC check; compression and MeatPack state restart at each block. A block with the last-block flag set must be the final block: more data after it is “corrupt”, and a file that ends before such a block is “corrupt” too (a cropped file). Padding that is not valid PKCS#7, or a ciphertext length that is not a multiple of 16, is an error.
What the file alone allows
Read in the same sources (e2ee.cpp, hmac.cpp, decryptor.cpp and gcode_reader_binary.cpp), and carried out by the viewer on test files built from this page:
- Keys in the clear (key block encryption 0): the 16-byte AES key and the 16-byte HMAC key are in the file, so the file holds all that decryption and the HMAC check need: the initialisation vector comes from the block’s offset, and the keys from the key block. Anyone who has the file can decrypt it. Encryption 0 is therefore no secrecy: the HMACs still detect damage, and the identity’s signature still shows the file unchanged since signing, but the payload is open to anyone. The viewer decrypts such blocks (AES-128-CBC, PKCS#7 padding), checks each HMAC with the key block’s HMAC key, reads the inner block as G-code and lists its lines. The firmware, though, takes even a clear key block only on a printer that has a private key:
decrypt_key_blockreturns at once when no printer private key is given, before it looks at the encryption value, and a file whose key blocks all fail that way is refused as encrypted for a different printer. - Keys RSA-encrypted (encryption 1): the AES key and the HMAC key are inside the 256-byte RSA-OAEP ciphertext, which only the private key of the printer it is encrypted to opens, so without that key the payload cannot be decrypted and the HMACs cannot be checked; what remains readable is the layout, the sizes and the signatures.
- The SHA-256 hashes: the intro hash and the key block hash are worked out from bytes of the file alone (rules above) and compared with the two the identity block holds.
- The signatures: the identity block’s signature is checked in the firmware with the public key the identity block carries (
read_and_verify_identity_blockpassesidentity_pk), and the signature of a key block of encryption 1 with the same identity key; neither needs the printer’s key, so both can be checked from the file. A valid signature shows the bytes are as the holder of that key signed them. It does not show who that is: whether to trust the key is the printer’s policy (its list of known identities). The firmware callsmbedtls_rsa_rsassa_pss_verify, which takes no salt length; the viewer accepts any salt length.
Not known
- Note, does not affect the layout: the software that writes these blocks, and the policy behind the flags, were not read.
- PSS salt length. The reader accepts any salt length: the firmware calls
mbedtls_rsa_rsassa_pss_verify(e2ee.cpp), which in mbedtls 2.16.12 and 2.28.8 (library/rsa.c, raw) passesMBEDTLS_RSA_SALT_LEN_ANYto the extended verify, and that check only compares the salt length when the expected one is not “any”. The mask function is MGF1:mbedtls_rsa_rsassa_pss_verifytakes the MGF1 hash from the context’s hash id when that is set and otherwise from the message hash, which the firmware passes asMBEDTLS_MD_SHA256, so MGF1 is over SHA-256 unless the context carries another hash id (whether the key parsing sets one was not checked). The firmware’s exact mbedtls version was not read; the salt length that writers choose is a writer matter and is not known. - OAEP parameters. The RSA-encrypted key block (encryption 1) is decrypted with
rsa_oaep_decrypt(e2ee.cpp):mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256)(OAEP, hash and MGF1 over SHA-256) andmbedtls_rsa_rsaes_oaep_decryptwith an empty label (nullptr, 0). The input must be exactly the key’s length. - Note, does not affect the layout: whether the public libbgcode
mainbranch will take block types 6 to 8 is not known; today only the firmware’s copy does.
MeatPack
MeatPack packs the most common G-code characters into 4 bits each, two to a byte: the first character in the low four bits, the second in the high four bits.
| Bits | Character |
|---|---|
| 0000 to 1001 | 0 to 9 |
| 1010 | . |
| 1011 | Space, or E in no-spaces mode |
| 1100 | Line feed |
| 1101 | G |
| 1110 | X |
| 1111 | The character is not packed: a full byte with it follows |
If the first character is a line feed, the high four bits are not used. Commands are
sent as two FF bytes followed by a command byte (decoder: unbinarize
in meatpack.cpp):
| Command | Meaning |
|---|---|
| 251 | Enable packing |
| 250 | Disable packing; bytes are copied as they are |
| 249 | Reset all (packing off) |
| 248 | Query configuration |
| 247 | Enable no-spaces mode |
| 246 | Disable no-spaces mode |
libbgcode’s encoder turns packing and no-spaces mode on at the start, writes
lower-case e as E, and leaves out the spaces between a
command and its parameters. Its decoder puts a space back before each parameter
letter on lines that start with G.
Characters that cannot be packed
A character not in the table above is sent as a full byte. The packed byte before it
says so with the nibble 1111:
- First character unpackable, second packable: one byte with low nibble
1111and the second character in the high nibble, then the first character as a full byte. The decoder writes the full byte first and then the second character. - First packable, second not: one byte with the first character in the low nibble and
1111in the high nibble, then the second character as a full byte. - Neither packable: the byte
FF, then the first character, then the second, as full bytes.
Because FF is also the command prefix, the encoder refuses any line that
contains the byte FF (binarize_line returns false). The decoder
takes two FF in a row as a command prefix whether packing is on or off; a
single FF not followed by another is passed on as an ordinary byte (so
the FF of the neither-packable layout works).
Encoding 1 and encoding 2
The G-code block’s encoding parameter chooses the mode; the encoder always uses
no-spaces mode with either. In both, each line has the text after ; cut
off and the ends trimmed unless it is a comment line kept as below; a line of only
white space or a comment is left out; every written line ends in a line feed. Only
lines that start with G0 to G3 are compacted: e
becomes E, x becomes X, g becomes
G, spaces are removed, and a * checksum is recomputed
(exclusive-or of the characters, written in decimal after *). Other
lines keep their spaces, which go out as full bytes.
- The line feed stays on a line without
;. The text is cut at the first;and trimmed of spaces and tabs only (triminmeatpack.cppdoes not remove a line feed). A line with a;loses its line feed with the cut, and one without keeps it, so for such a linecompact_gcode_line_for_packingworks on text that still ends in a line feed. When it holds a*, the exclusive-or therefore includes the line feed, and the*and the number are added after it, followed by another line feed:G1 X1 Y2*5becomes the textG1X1Y25, a line feed,*75and a line feed (75 is the exclusive-or of the eight charactersG1X1Y25and the line feed), and the decoder gives it back as the two linesG1 X1 Y25and*75: the checksum lands on a line of its own. The same line with a;comment after it has no line feed when it is compacted, so there the checksum stays on the line. - Only
e,xandgare made upper case;fis not. The encoder replacese,xandgand takes out the spaces, but leaves a lower-casef(andy,zand others) as it is. The decoder puts a space back only before the upper-case lettersX Y Z E F I J R S G P W H C A, so a lower-casefdoes not get its space:G1 X3 e.5 f100comes back asG1 X3 E.5f100. (yandzare sent as full bytes, still lower case, and get no space either.)
- Encoding 1: comments removed. The stream begins with
FF FF FB(251, enable packing) andFF FF F7(247, no-spaces on) and ends withFF FF F9(249, reset all). - Encoding 2: a line whose first non-blank character is
;is written unchanged, as plain bytes, withFF FF FA(250, disable packing) before it if packing was on. The next packed line is preceded byFF FF FB(251) again. The stream begins as in encoding 1 and ends without the reset command.
Decoder rules
- Packing is off at the start: bytes are copied unchanged until
FF FF FB. - Commands 251 (packing on), 250 (packing off), 249 (reset all: packing off, no-spaces unchanged), 247 and 246 (no-spaces on and off) are acted on. 248 (query) and any other value, such as the unused 253, are ignored.
- In a packed byte the low nibble is read first. If it is a line feed, the high nibble is not used. Nibble
1011is a space, orEwhile no-spaces mode is on. - A line feed is not written when the last character written was a line feed, so blank lines collapse to one; this applies to copied bytes too.
- Spaces are put back: after a
Gthat starts a line (at the start of the output or after a line feed), a space is written before each ofX Y Z E F I J R S G P W H C Athat follows it, until the line ends or a space is written (a line that contains a space was stored unchanged).
Source: prusa3d/libbgcode main, src/LibBGCode/binarize/meatpack.cpp and
binarize.cpp, read as raw text.
Worked example: G1 X10 in no-spaces mode is the characters
G, 1, X, 1, 0, line
feed, which pack as 1D (G then 1), 1E (X then 1) and
C0 (0 then line feed).