package mtproto

Import Path
	github.com/gotd/td/mtproto (on go.dev)

Dependency Relation
	imports 27 packages, and imported by 3 packages


Package-Level Type Names (total 21, in which 17 are exported)
/* sort exporteds by: | */
Cipher handles message encryption and decryption. ( Cipher) DecryptFromBuffer(k crypto.AuthKey, buf *bin.Buffer) (*crypto.EncryptedMessageData, error) ( Cipher) Encrypt(key crypto.AuthKey, data crypto.EncryptedMessageData, b *bin.Buffer) error github.com/gotd/td/crypto.Cipher
Conn represents a MTProto client to Telegram. Invoke sends input and decodes result into output. NOTE: Assuming that call contains content message (seqno increment). Ping sends ping request to server and waits until pong is received or context is canceled. Run initializes MTProto connection to server and blocks until disconnection. When connection is ready, Handler.OnSession is called. *Conn : github.com/gotd/td/tg.Invoker func New(dialer Dialer, opt Options) *Conn
Dialer is an abstraction for MTProto transport connection creator. func New(dialer Dialer, opt Options) *Conn func github.com/gotd/td/telegram/internal/manager.CreateConn(create Dialer, mode manager.ConnMode, appID int, opts Options, connOpts manager.ConnOptions) *manager.Conn
Handler will be called on received message from Telegram. ( Handler) OnMessage(b *bin.Buffer) error ( Handler) OnSession(session Session) error *github.com/gotd/td/telegram/internal/manager.Conn
MessageBuf is message id buffer. ( MessageBuf) Consume(id int64) bool *github.com/gotd/td/proto.MessageIDBuf
MessageIDSource is message id generator. ( MessageIDSource) New(t proto.MessageType) int64 *github.com/gotd/td/proto.MessageIDGen
NewSessionHandler is implemented by a Handler that wants to know when the server created a new session (new_session_created), e.g. to recover updates it may have missed. ( NewSessionHandler) OnNewSession(firstMsgID int64) error *github.com/gotd/td/telegram/internal/manager.Conn github.com/gotd/td/telegram/internal/manager.NewSessionHandler (interface) NewSessionHandler : github.com/gotd/td/telegram/internal/manager.NewSessionHandler
Options of Conn. AckBatchSize is maximum ack-s to buffer. AckInterval is maximum time to buffer ack. Cipher defines message crypto. Clock is current time source. Defaults to system time. CompressThreshold is a threshold in bytes to determine that message is large enough to be compressed using GZIP. If < 0, compression will be disabled. If == 0, default value will be used. DC is datacenter ID for key exchange. Defaults to 2. DialTimeout is timeout of creating connection. EnablePFS enables Perfect Forward Secrecy using temporary auth keys. ExchangeTimeout is timeout of every key exchange request. Handler will be called on received message. Key that can be used to restore previous connection. KeyCreatedAt is the creation time of the permanent key (Key, or PermKey in PFS mode), Unix seconds; zero if unknown. It is reported back in Session.KeyCreatedAt and used by the PFS key recovery policy. Logger is the structured logger. No logs by default. MaxRetries is max retry count until rpc request failure. MessageID is message id source. Share source between connection to reduce collision probability. PermKey is permanent auth key for PFS mode. PingInterval is the duration between ping_delay_disconnect requests. Zero (default) pings like Telegram Desktop: every 30–45 seconds (a random interval in [30s, 45s]) with disconnect_delay 60. A positive value pings at that fixed interval with disconnect_delay PingInterval + PingTimeout. PingTimeout is the time to wait for a pong, after which the connection is considered dead. Default is 15 seconds. PublicKeys of telegram. If not provided, embedded public keys will be used. Random is random source. Defaults to crypto. RequestTimeout is function which returns request timeout for given type ID. RetryInterval is duration between retries. Salt from server that can be used to restore previous connection. SaltFetchInterval is the duration between get_future_salts requests. Zero (default) never sends get_future_salts, like Telegram Desktop: the server salt is taken from new_session_created and bad_server_salt (a request with an expired salt is re-sent with the new one). A positive value fetches future salts every interval, the first time one interval after the session starts. ServerTime tracks the server time offset; share it between connections of a client. Defaults to a new ServerTime over Clock. Message ids of the default MessageID source and the msg_id time check use it. SessionState keeps the server session (session_id and seqno) across reconnects of a connection slot with the same key. Nil starts a new session on every connect. Not used in PFS mode, where every connection has a new temporary key. TempKeyTTL is temporary auth key lifetime in seconds. Default: 86400 (24h). Minimum: 60. Tracer for OTEL. Types map, used in verbose logging of incoming message. WireTracer observes plaintext messages and lifecycle events of the connection. Nil (default) disables wire tracing. func github.com/gotd/td/pool.(*SyncSession).Options(opts Options) (Options, pool.Session) func New(dialer Dialer, opt Options) *Conn func github.com/gotd/td/pool.(*SyncSession).Options(opts Options) (Options, pool.Session) func github.com/gotd/td/telegram/internal/manager.CreateConn(create Dialer, mode manager.ConnMode, appID int, opts Options, connOpts manager.ConnOptions) *manager.Conn
ServerTime tracks the difference between the server clock and the local clock, so that message ids and the msg_id time window use server time even when the local clock is off. Like TDLib (AuthData::update_server_time_difference), the difference is taken from the time encoded in every received msg_id (and the server_time of the key exchange): the first observation sets it, later ones only raise it, since a message is always received after the server created it. A bad_msg_notification "msg_id too high" resets it from the notification's own msg_id. One ServerTime is shared by all connections of a client. It is safe for concurrent use. Known reports whether the offset was observed from the server. Now returns the current server time. Offset returns server time minus local time. Seed sets the offset, e.g. one persisted by a previous run, unless it was already observed from the server. *ServerTime : github.com/cenkalti/backoff/v4.Clock func NewServerTime(base clock.Clock, offset time.Duration) *ServerTime
Session represents connection state. ID int64 Key crypto.AuthKey KeyCreatedAt is the creation time of the permanent key (Key, or PermKey in PFS mode), Unix seconds; zero if unknown. PermKey is non-zero only in PFS mode and is used for bindTempAuthKey. Salt int64 func Handler.OnSession(session Session) error func github.com/gotd/td/telegram/internal/manager.(*Conn).OnSession(session Session) error func github.com/gotd/td/telegram/internal/manager.Handler.OnSession(cfg tg.Config, s Session) error func github.com/gotd/td/telegram/internal/manager.NoopHandler.OnSession(cfg tg.Config, s Session) error
SessionState is the server session of a connection slot: session_id and the number of content messages sent in it (for seqno). Connections that share a SessionState one at a time continue the same server session after a reconnect with the same auth key, so the server keeps its queued answers and updates and does not send new_session_created, like TDLib and Telegram Desktop do. A new session is started when the key changes. A SessionState must be used by one connection at a time: acquire it with TryAcquire before passing it in Options; the connection releases it when Run returns. TryAcquire marks the state as used by a connection. It reports false if another connection uses it. func NewSessionState() *SessionState
WireConn identifies the connection of a traced message or event. DC is the DC id of the connection used for key exchange (Options.DC): 10000 is added for test DCs. ID is unique for every Conn of the process, starting from 1.
WireDirection is the direction of a traced message. String implements fmt.Stringer. WireDirection : fmt.Stringer const WireIn const WireOut
WireEvent is a connection lifecycle event. Fields are set depending on Type. AuthKeyID, TempKey and ExpiresAt (unix seconds, temporary keys only) describe the auth key of key events. Conn WireConn Err error ExpiresAt int64 Latency time.Duration MessageID int64 Old and New are session ids or salts. Old and New are session ids or salts. Reason string SeqNo int32 TempKey bool Type WireEventType TypeID uint32 func WireTracer.OnEvent(e WireEvent)
WireEventType is the type of a WireEvent. String implements fmt.Stringer. WireEventType : fmt.Stringer const WireConnDown const WireConnStart const WireConnUp const WireDecryptFailed const WireKeyCreated const WireKeySet const WireRejected const WireRequest const WireRequestDone const WireRequestResend const WireSaltChange const WireSessionNew
WireMessage is the header of a traced message. AuthKeyID is the id of the auth key the message is encrypted with. Conn WireConn Direction WireDirection MessageID int64 Salt int64 SeqNo int32 SessionID int64 TempKey is true if the message is encrypted with a temporary (PFS) key. func WireTracer.OnMessage(m WireMessage, body []byte)
WireTracer observes the plaintext MTProto traffic and the lifecycle of a connection, e.g. to record wire traces for debugging or for comparing the client behavior with other implementations. Callbacks are called synchronously from the connection goroutines, so implementations must be safe for concurrent use and must return quickly. Calls are not ordered by wire order: incoming messages are decrypted concurrently, and outgoing messages are reported by concurrent writers just before they are written, so a reported outgoing message may never reach the wire if the write fails. Order by message id where needed. The tracer never receives auth key material: only auth key ids. OnEvent is called on connection, key, session and request lifecycle events. OnMessage is called for every encrypted message: outgoing messages just before encryption and incoming messages after decryption and msg_key check, before session and msg_id checks (rejected messages are reported too, followed by a WireRejected event). The body is the serialized message body as sent or received (including gzip_packed and msg_container). It is only valid during the call: the tracer must not modify or retain it, and must copy it if needed.
Package-Level Functions (total 12, in which 3 are exported)
New creates new unstarted connection.
NewServerTime creates a ServerTime over the base clock (clock.System if nil), starting with the given offset, e.g. a persisted one. The offset is replaced by the first observed server time.
NewSessionState returns an empty SessionState.
Package-Level Variables (total 10, in which 2 are exported)
ErrPFSDropKeysRequired is returned when stored permanent key should be dropped and generated again on the next connection attempt.
ErrPFSReconnectRequired is returned when connection should be recreated to continue PFS flow (e.g. temp key renewal).
Package-Level Constants (total 30, in which 14 are exported)
WireConnDown is reported when the connection is closed, Err is the reason (nil on graceful close).
WireConnStart is reported before dialing.
WireConnUp is reported when the transport connection is established.
WireDecryptFailed is reported when an incoming message can't be decrypted or fails the msg_key check: Err.
WireIn is a message received from the server.
WireKeyCreated is reported when a new auth key is created by key exchange: AuthKeyID, TempKey and ExpiresAt (temporary keys).
WireKeySet is reported when the connection starts using an auth key for messages, including after the key is re-created because the server did not find it: AuthKeyID, TempKey and ExpiresAt (temporary keys).
WireOut is a message sent by the client.
WireRejected is reported when a decrypted incoming message is rejected: MessageID and Reason ("bad_session" or "bad_msg_id").
WireRequest is reported when a request is going to be sent: MessageID, SeqNo and TypeID (of the encoded request, e.g. a wrapper like invokeWithLayer).
WireRequestDone is reported when a request is finished: MessageID, Err (nil on success, RPC or context error otherwise) and Latency.
WireRequestResend is reported when a request is re-encoded and sent again after bad_server_salt: MessageID and Reason ("bad_server_salt"). Retransmits after an ack timeout reuse the message id and are only visible as repeated outgoing messages.
WireSaltChange is reported when the server salt changes: Old and New. Salts set by key exchange are implied by WireKeyCreated.
WireSessionNew is reported when the client session id changes: Old and New.