Documentation
¶
Overview ¶
Package tl implements the Telegram TL (Type Language) wire format used by the COCOON network protocol.
The schema is published at TelegramMessenger/cocoon/tl/generate/scheme/cocoon_api.tl and vendored in this repo at references/cocoon_api.tl.
This package provides the primitive Reader/Writer for TL types. The higher-level constructors currently used by gocoon are maintained by hand in this package.
Wire conventions (matching the standard TL spec):
- All integers little-endian.
- int = 4 bytes
- long = 8 bytes
- int128= 16 bytes (raw)
- int256= 32 bytes (raw)
- bytes = length-prefixed blob with 4-byte alignment padding
- string= same encoding as bytes, UTF-8 expected
- vector= 4-byte count + count * t serialization
- bool = constructor IDs boolFalse=0xbc799737, boolTrue=0x997275b5
- flags = 4-byte bitmask gating optional fields
- constructors are prefixed by their 4-byte ID
Bytes/string length encoding:
- len < 254: single byte len, then len bytes, then padding to 4-byte align
- len >= 254: byte 0xfe, then 3-byte little-endian length, then bytes, then padding to 4-byte align
Index ¶
- Constants
- Variables
- func ConstructorID(signature string) uint32
- func EncodeTCPConnect(id int64) []byte
- func EncodeTCPConnected(id int64) []byte
- func EncodeTCPPacket(data []byte) []byte
- func EncodeTCPPing(id int64) []byte
- func EncodeTCPPong(id int64) []byte
- func EncodeTCPQuery(queryID int64, data []byte) []byte
- func IDStatus(id uint32) string
- func ReadSimpleFrame(r io.Reader) ([]byte, error)
- func WriteSimpleFrame(w io.Writer, payload []byte) error
- type ClientAuthorizeWithProxyLong
- type ClientAuthorizeWithProxyShort
- type ClientConnectToProxy
- type ClientParams
- type DecodedTCPPacket
- type FramedConn
- type ProxyParams
- type Reader
- func (r *Reader) EOF() bool
- func (r *Reader) Pos() int
- func (r *Reader) ReadBool() (bool, error)
- func (r *Reader) ReadBytes() ([]byte, error)
- func (r *Reader) ReadDouble() (float64, error)
- func (r *Reader) ReadFlags() (uint32, error)
- func (r *Reader) ReadInt32() (int32, error)
- func (r *Reader) ReadInt64() (int64, error)
- func (r *Reader) ReadInt128() ([16]byte, error)
- func (r *Reader) ReadInt256() ([32]byte, error)
- func (r *Reader) ReadRaw(n int) ([]byte, error)
- func (r *Reader) ReadString() (string, error)
- func (r *Reader) ReadUint32() (uint32, error)
- func (r *Reader) ReadUint64() (uint64, error)
- func (r *Reader) ReadVectorBytes() ([][]byte, error)
- func (r *Reader) ReadVectorInt256() ([][32]byte, error)
- func (r *Reader) ReadVectorLen() (int, error)
- func (r *Reader) ReadVectorString() ([]string, error)
- func (r *Reader) Remaining() int
- type TCPPacketKind
- type TokensUsed
- type Writer
- func (w *Writer) Bytes() []byte
- func (w *Writer) Len() int
- func (w *Writer) Reset()
- func (w *Writer) WriteBool(v bool)
- func (w *Writer) WriteBytes(b []byte)
- func (w *Writer) WriteDouble(v float64)
- func (w *Writer) WriteFlags(flags uint32)
- func (w *Writer) WriteInt32(v int32)
- func (w *Writer) WriteInt64(v int64)
- func (w *Writer) WriteInt128(v [16]byte)
- func (w *Writer) WriteInt256(v [32]byte)
- func (w *Writer) WriteRaw(b []byte)
- func (w *Writer) WriteString(s string)
- func (w *Writer) WriteUint32(v uint32)
- func (w *Writer) WriteUint64(v uint64)
- func (w *Writer) WriteVectorBytes(items [][]byte)
- func (w *Writer) WriteVectorInt256(items [][32]byte)
- func (w *Writer) WriteVectorLen(n int)
- func (w *Writer) WriteVectorString(items []string)
Constants ¶
const ( // ─── Generic infrastructure ─────────────────────────────────────────── IDBoolFalse uint32 = 0xbc799737 IDBoolTrue uint32 = 0x997275b5 // ─── Wire: client → proxy (functions) ───────────────────────────────── IDClientConnectToProxy uint32 = 0xff5fa0f4 IDClientAuthorizeWithProxyShort uint32 = 0x6c276723 IDClientAuthorizeWithProxyLong uint32 = 0xd3474303 IDClientRequestRefund uint32 = 0x238d863d IDClientUpdatePaymentStatus uint32 = 0x9ed1c697 IDClientRunQueryEx uint32 = 0xf54cb74b // explicit in schema IDClientGetWorkerTypesV2 uint32 = 0xb2133d72 // ─── Wire: proxy → client (responses) ───────────────────────────────── IDClientConnectedToProxy uint32 = 0x95317ad1 IDClientAuthorizationWithProxySuccess uint32 = 0x75d5ac34 IDClientAuthorizationWithProxyFailed uint32 = 0x60551c96 IDClientProxyConnectionAuthShort uint32 = 0xd6ffc5af IDClientProxyConnectionAuthLong uint32 = 0x417bf016 IDClientQueryAnswer uint32 = 0x9b943922 IDClientQueryAnswerError uint32 = 0x6d60569a IDClientQueryAnswerPart uint32 = 0xb765de4c IDClientQueryAnswerPartError uint32 = 0xd790a022 IDClientQueryAnswerEx uint32 = 0xcd524720 IDClientQueryAnswerErrorEx uint32 = 0x072562a8 IDClientQueryAnswerPartEx uint32 = 0xc07bfaec IDClientQueryFinalInfo uint32 = 0x69a452f0 IDClientRefund uint32 = 0x83aabead IDClientRefundRejected uint32 = 0xcf9d9957 IDClientPaymentStatus uint32 = 0xaa8a0ecc IDClientWorkerInstanceV2 uint32 = 0x3ea93d00 // explicit in schema IDClientWorkerTypeV2 uint32 = 0xb27d8197 IDClientWorkerTypesV2 uint32 = 0x0cf0dc67 // ─── proxy.signedPayment ────────────────────────────────────────────── IDProxySignedPayment uint32 = 0x02998182 IDProxySignedPaymentEmpty uint32 = 0xb347ce64 // ─── Shared ─────────────────────────────────────────────────────────── IDClientParams uint32 = 0x40fdca64 // explicit in schema IDProxyParams uint32 = 0xd5c5609f // explicit in schema IDWorkerParams uint32 = 0x869c73ed // explicit in schema IDTokensUsed uint32 = 0x70c5b15c )
Explicit constructor IDs from cocoon_api.tl. ALL VERIFIED via dual-source: CRC32(canonical_signature) AND extraction from cocoon_api.tlo binary. Cross-validated by research agent (2026-05-01); zero mismatches.
const MaxFrameSize = 16 * 1024 * 1024
MaxFrameSize is the inclusive maximum payload size (16 MiB). Frames larger than this are rejected to avoid memory exhaustion.
const MinFrameSize = 4
MinFrameSize is the smallest valid payload (4 bytes = constructor ID).
Variables ¶
var ( // ErrShortBuffer is returned when fewer bytes than required are available. ErrShortBuffer = errors.New("tl: short buffer") // ErrInvalidBool indicates the wire bytes do not match boolFalse or boolTrue. ErrInvalidBool = errors.New("tl: invalid bool constructor id") // ErrInvalidLength indicates a length prefix is malformed (e.g. 0xff is reserved). ErrInvalidLength = errors.New("tl: invalid length prefix") // ErrUnknownConstructor is returned when a constructor ID does not match any // registered type. ErrUnknownConstructor = errors.New("tl: unknown constructor id") )
Sentinel errors returned by the Reader/Writer.
var ( IDTCPPing = crc32.ChecksumIEEE([]byte("tcp.ping id:long = tcp.Packet")) IDTCPPong = crc32.ChecksumIEEE([]byte("tcp.pong id:long = tcp.Packet")) IDTCPPacket = crc32.ChecksumIEEE([]byte("tcp.packet data:bytes = tcp.Packet")) IDTCPQueryAnswer = crc32.ChecksumIEEE([]byte("tcp.queryAnswer id:long data:bytes = tcp.Packet")) IDTCPQueryError = crc32.ChecksumIEEE([]byte("tcp.queryError id:long code:int message:string = tcp.Packet")) IDTCPQuery = crc32.ChecksumIEEE([]byte("tcp.query id:long data:bytes = tcp.Packet")) IDTCPConnected = crc32.ChecksumIEEE([]byte("tcp.connected id:long = tcp.Packet")) IDTCPConnect = crc32.ChecksumIEEE([]byte("tcp.connect id:long = tcp.Packet")) )
tcp.* constructor IDs computed at init time from canonical signatures. Matches the algorithm verified against cocoon_api.tlo.
var ( IDHTTPHeader = ConstructorID("http.header name:string value:string = http.Header") IDHTTPResponse = uint32(0x1cd0c42b) IDHTTPRequest = uint32(0x47492de5) )
Functions ¶
func ConstructorID ¶
ConstructorID returns the TL constructor ID for the given normalized signature, computed as the IEEE CRC32 of the signature string.
The signature must be the constructor name + space-separated arg list + "= TypeName", exactly as in the .tl file (no `#xxxxxxxx` annotation).
Example: "boolFalse = Bool" → 0xbc799737.
func EncodeTCPConnect ¶
EncodeTCPConnect emits a `tcp.connect id:long` payload (already framed by FramedConn wrapper).
func EncodeTCPConnected ¶
EncodeTCPConnected emits a `tcp.connected id:long`.
func EncodeTCPPacket ¶
EncodeTCPPacket wraps fire-and-forget data.
func EncodeTCPPing ¶
EncodeTCPPing emits a tcp.ping with a random id chosen by caller.
func EncodeTCPPong ¶
EncodeTCPPong emits a tcp.pong with id echoing the ping.
func EncodeTCPQuery ¶
EncodeTCPQuery wraps a TL function payload in a tcp.query envelope.
Wire layout: [u32: IDTCPQuery][i64: id][bytes: data]
func IDStatus ¶
IDStatus reports whether a constructor ID is verified. All IDs in this file are HIGH-confidence (CRC32 + .tlo cross-validated), so this always returns "verified".
func ReadSimpleFrame ¶
ReadSimpleFrame reads a [uint32 LE: len]bytes frame without seqno. This format is used during the RA-TLS attestation handshake, before the regular framing loop kicks in.
Source: tdnet/td/net/FramedPipe.cpp framed_read.
Types ¶
type ClientAuthorizeWithProxyLong ¶
type ClientAuthorizeWithProxyLong struct{}
ClientAuthorizeWithProxyLong is the empty-body variant.
func (ClientAuthorizeWithProxyLong) Encode ¶
func (c ClientAuthorizeWithProxyLong) Encode(w *Writer)
type ClientAuthorizeWithProxyShort ¶
type ClientAuthorizeWithProxyShort struct {
Data []byte
}
ClientAuthorizeWithProxyShort
client.authorizeWithProxyShort data:bytes = client.AuthorizationWithProxy;
func (ClientAuthorizeWithProxyShort) Encode ¶
func (c ClientAuthorizeWithProxyShort) Encode(w *Writer)
type ClientConnectToProxy ¶
type ClientConnectToProxy struct {
Params ClientParams
MinConfigVersion int32
}
ClientConnectToProxy is the function call we send first.
client.connectToProxy params:client.params min_config_version:int = client.ConnectedToProxy;
`params:client.params` is a concrete lower-case TL type, so it is encoded bare inside the function body. Encoding the client.params constructor here makes the proxy read that constructor as `flags`, then reject the payload as trailing data.
func (ClientConnectToProxy) Encode ¶
func (c ClientConnectToProxy) Encode(w *Writer)
Encode writes the boxed function call.
type ClientParams ¶
type ClientParams struct {
Flags uint32
ClientOwnerAddr string // always present
IsTest bool // present iff Flags&1
MinProtoVersion int32 // present iff Flags&2
MaxProtoVersion int32 // present iff Flags&2
}
ClientParams = client.params from cocoon_api.tl:
client.params#40fdca64 flags:# client_owner_address:string is_test:flags.0?Bool min_proto_version:flags.1?int max_proto_version:flags.1?int = client.Params;
func DecodeClientParamsBody ¶
func DecodeClientParamsBody(r *Reader) (ClientParams, error)
DecodeClientParamsBody decodes the body (no constructor ID).
func (ClientParams) Encode ¶
func (p ClientParams) Encode(w *Writer, boxed bool)
Encode writes the constructor + body. If boxed=true, the constructor ID is prepended (as required at the top level of an RPC payload).
func (ClientParams) HasIsTest ¶
func (p ClientParams) HasIsTest() bool
HasIsTest reports whether the IsTest field is wire-encoded.
func (ClientParams) HasProtoVersion ¶
func (p ClientParams) HasProtoVersion() bool
HasProtoVersion reports whether the proto_version pair is wire-encoded.
type DecodedTCPPacket ¶
type DecodedTCPPacket struct {
Kind TCPPacketKind
ID int64 // ping/pong/connect/connected/query/queryAnswer/queryError
Data []byte // packet/query/queryAnswer
ErrCode int32 // queryError
ErrMsg string // queryError
}
DecodedTCPPacket is the parsed result of one frame payload.
func DecodeTCPPacket ¶
func DecodeTCPPacket(payload []byte) (*DecodedTCPPacket, error)
DecodeTCPPacket parses a frame payload into a DecodedTCPPacket.
type FramedConn ¶
type FramedConn struct {
// Strict, when true, rejects frames whose seqno does not match the
// expected counter. Matches upstream behavior.
Strict bool
// contains filtered or unexported fields
}
FramedConn wraps an io.ReadWriter to provide framed read/write with independent in/out seqno counters, matching upstream net/TcpConnection.cpp.
Concurrency: WriteFrame and ReadFrame may be called concurrently from different goroutines (one writer, one reader), but each side must be serialized.
func NewFramedConn ¶
func NewFramedConn(rw io.ReadWriter) *FramedConn
NewFramedConn returns a FramedConn around rw, with seqno counters at 0 and strict seqno validation enabled.
func (*FramedConn) InSeqno ¶
func (c *FramedConn) InSeqno() int32
InSeqno returns the next expected seqno on the receive side.
func (*FramedConn) OutSeqno ¶
func (c *FramedConn) OutSeqno() int32
OutSeqno returns the next seqno that will be assigned to an outgoing frame.
func (*FramedConn) ReadFrame ¶
func (c *FramedConn) ReadFrame() ([]byte, error)
ReadFrame reads the next framed payload, validating the incoming seqno.
func (*FramedConn) WriteFrame ¶
func (c *FramedConn) WriteFrame(payload []byte) error
WriteFrame writes one framed payload, prepending the next outgoing seqno.
type ProxyParams ¶
type ProxyParams struct {
Flags uint32
PublicKey [32]byte
OwnerAddress string
SCAddress string
IsTest bool
ProtoVersion int32
}
ProxyParams = proxy.params from cocoon_api.tl:
proxy.params#d5c5609f flags:# proxy_public_key:int256 proxy_owner_address:string proxy_sc_address:string is_test:flags.0?Bool proto_version:flags.1?int = proxy.Params;
func DecodeProxyParamsBody ¶
func DecodeProxyParamsBody(r *Reader) (ProxyParams, error)
func (ProxyParams) Encode ¶
func (p ProxyParams) Encode(w *Writer, boxed bool)
func (ProxyParams) HasIsTest ¶
func (p ProxyParams) HasIsTest() bool
func (ProxyParams) HasProtoVersion ¶
func (p ProxyParams) HasProtoVersion() bool
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader decodes TL primitives from a byte slice.
The Reader is not safe for concurrent use. All read methods advance the internal cursor; on error the cursor is left at the position of the first failed read so the caller can inspect what was already decoded.
func (*Reader) ReadBytes ¶
ReadBytes decodes a length-prefixed byte slice with 4-byte alignment.
The returned slice is a copy of the underlying buffer.
func (*Reader) ReadDouble ¶
ReadDouble decodes an IEEE-754 double precision float in little-endian.
func (*Reader) ReadInt128 ¶
ReadInt128 reads 16 raw bytes.
func (*Reader) ReadInt256 ¶
ReadInt256 reads 32 raw bytes.
func (*Reader) ReadString ¶
ReadString decodes a TL string (same wire format as bytes, UTF-8 expected but not validated here).
func (*Reader) ReadUint32 ¶
ReadUint32 decodes a 32-bit little-endian unsigned integer.
func (*Reader) ReadUint64 ¶
ReadUint64 decodes a 64-bit little-endian unsigned integer.
func (*Reader) ReadVectorBytes ¶
ReadVectorBytes is a convenience wrapper for `vector bytes`.
func (*Reader) ReadVectorInt256 ¶
ReadVectorInt256 is a convenience wrapper for `vector int256` (used for proxy_hashes, worker_hashes, etc. in rootConfig).
func (*Reader) ReadVectorLen ¶
ReadVectorLen reads a vector header and returns the element count.
func (*Reader) ReadVectorString ¶
ReadVectorString is a convenience wrapper for `vector string`.
type TCPPacketKind ¶
type TCPPacketKind int
TCPPacketKind identifies the variant of a decoded packet.
const ( TCPKindUnknown TCPPacketKind = iota TCPKindPing TCPKindPong TCPKindConnect TCPKindConnected TCPKindPacket TCPKindQuery TCPKindQueryAnswer TCPKindQueryError )
type TokensUsed ¶
type TokensUsed struct {
PromptTokens int64
CachedTokens int64
CompletionTokens int64
ReasoningTokens int64
TotalTokens int64
}
TokensUsed = tokensUsed from cocoon_api.tl:
tokensUsed prompt_tokens_used:long cached_tokens_used:long
completion_tokens_used:long reasoning_tokens_used:long
total_tokens_used:long = TokensUsed;
func DecodeTokensUsed ¶
func DecodeTokensUsed(r *Reader) (TokensUsed, error)
func (TokensUsed) Encode ¶
func (t TokensUsed) Encode(w *Writer)
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer encodes TL primitives.
Writer is not safe for concurrent use. Bytes returned by Bytes() are owned by the Writer; copy them if you need to retain them past the next mutation.
func NewWriterCap ¶
NewWriterCap returns a Writer pre-allocated to capacity n.
func (*Writer) Bytes ¶
Bytes returns the encoded bytes. The caller must copy if retention is needed.
func (*Writer) WriteBytes ¶
WriteBytes appends a length-prefixed byte slice with 4-byte alignment padding.
func (*Writer) WriteDouble ¶
WriteDouble appends an IEEE-754 double precision float.
func (*Writer) WriteFlags ¶
WriteFlags appends a flags:# field.
func (*Writer) WriteInt32 ¶
WriteInt32 appends a 32-bit signed integer.
func (*Writer) WriteInt64 ¶
WriteInt64 appends a 64-bit signed integer.
func (*Writer) WriteInt128 ¶
WriteInt128 appends 16 raw bytes.
func (*Writer) WriteInt256 ¶
WriteInt256 appends 32 raw bytes.
func (*Writer) WriteString ¶
WriteString appends a TL string (length-prefixed UTF-8 bytes).
func (*Writer) WriteUint32 ¶
WriteUint32 appends a 32-bit unsigned integer.
func (*Writer) WriteUint64 ¶
WriteUint64 appends a 64-bit unsigned integer.
func (*Writer) WriteVectorBytes ¶
WriteVectorBytes is a convenience wrapper for `vector bytes`.
func (*Writer) WriteVectorInt256 ¶
WriteVectorInt256 is a convenience wrapper for `vector int256`.
func (*Writer) WriteVectorLen ¶
WriteVectorLen writes a vector header.
func (*Writer) WriteVectorString ¶
WriteVectorString is a convenience wrapper for `vector string`.