package proto

import (
	
	
	
	
)

// Message identifiers are coupled to message creation time.
//
// https://core.telegram.org/mtproto/description#message-identifier-msg-id

const (
	yieldClient         = 0
	yieldServerResponse = 1
	yieldFromServer     = 3

	messageIDModulo = 4
)

func ( int64,  int) int64 {
	return newMessageIDJitter(, , 0)
}

// newMessageIDJitter returns a message id for the time point nowNano: unix
// seconds in the upper 32 bits and the fraction of the second in units of
// 2^-32 s in the lower 32 bits (msg_id approximately equals unixtime * 2^32),
// with the lower bits XORed with jitter (TDLib XORs 22 random bits, about
// 1 ms, for clocks of low precision) and the two lowest bits set to yield.
func ( int64,  int,  uint32) int64 {
	const  = 1e9

	// Important: to counter replay-attacks the lower 32 bits of msg_id
	// passed by the client must not be empty and must present a
	// fractional part of the time point when the message was created.
	 :=  / 
	 := uint64(%) << 32 / 
	 ^= uint64()

	// Ensure that frac % 4 == 0 and add modulo 4 yield to ensure message
	// type.
	 = &^(messageIDModulo-1) | uint64()

	return <<32 | int64()
}

// MessageID represents 64-bit message id.
type MessageID int64

func ( MessageID) () string {
	return fmt.Sprintf("%x (%s, %s)",
		int64(), .Type(), .Time().Format(time.RFC3339),
	)
}

// MessageType is type of message determined by message id.
//
// A message is rejected over 300 seconds after it is created or
// 30 seconds before it is created (this is needed to protect from replay attacks).
//
// The identifier of a message container must be strictly greater than those of
// its nested messages.
type MessageType byte

const (
	// MessageUnknown reports that message id has unknown time and probably
	// should be ignored.
	MessageUnknown MessageType = iota
	// MessageFromClient is client message identifiers.
	MessageFromClient
	// MessageServerResponse is a response to a client message.
	MessageServerResponse
	// MessageFromServer is a message from the server.
	MessageFromServer
)

func ( MessageType) () string {
	switch  {
	case MessageFromClient:
		return "FromClient"
	case MessageServerResponse:
		return "ServerResponse"
	case MessageFromServer:
		return "FromServer"
	default:
		return "Unknown"
	}
}

// Time returns approximate time when MessageID were generated.
func ( MessageID) () time.Time {
	 := int64() >> 32
	// The lower 32 bits are the fraction of the second in units of 2^-32 s.
	 := int64(uint64(uint32()) * 1e9 >> 32)
	return time.Unix(, ).UTC()
}

// Type returns message type.
func ( MessageID) () MessageType {
	switch  % messageIDModulo {
	case yieldClient:
		return MessageFromClient
	case yieldServerResponse:
		return MessageServerResponse
	case yieldFromServer:
		return MessageFromServer
	default:
		return MessageUnknown
	}
}

// NewMessageID returns new message id for provided time and type.
func ( time.Time,  MessageType) MessageID {
	return NewMessageIDNano(.UnixNano(), )
}

// NewMessageIDNano returns new message id for provided current unix
// nanoseconds and type.
func ( int64,  MessageType) MessageID {
	return MessageID(newMessageID(, messageYield()))
}

// messageYield returns the two lowest bits of message ids of type typ.
func ( MessageType) int {
	switch  {
	case MessageFromServer:
		return yieldFromServer
	case MessageServerResponse:
		return yieldServerResponse
	default:
		return yieldClient
	}
}

// MessageIDGen is message id generator that provides collision prevention.
//
// Ids follow TDLib (AuthData::next_message_id): the time of now() with 22
// random bits XORed into the fraction, and if that is not above the last id
// (now() returned the same or an earlier time, e.g. after a correction of the
// server time offset), the last id plus a random multiple of 4. So ids always
// increase, and their lower bits don't reveal the clock resolution.
type MessageIDGen struct {
	mux  sync.Mutex
	last int64
	now  func() time.Time
}

// jitterBits is the number of random lower bits of generated ids (TDLib).
const jitterBits = 22

// New generates new message id for provided type, protecting from collisions
// that are caused by low system time resolution.
func ( *MessageIDGen) ( MessageType) int64 {
	.mux.Lock()
	defer .mux.Unlock()

	 := rand.Uint32() // #nosec G404: jitter, not a secret
	 := newMessageIDJitter(.now().UnixNano(), messageYield(), &(1<<jitterBits-1))
	if  <= .last {
		 := int64(>>jitterBits&1023) + 1
		 = (.last&^(messageIDModulo-1) + messageIDModulo*) | int64(messageYield())
	}
	.last = 
	return 
}

// Reset forgets the last generated id, so the next ids follow the current
// time again even if earlier ones were higher, e.g. generated before the
// server time offset was corrected. Ids must keep increasing within a
// server session, so Reset is for a new session only.
func ( *MessageIDGen) () {
	.mux.Lock()
	.last = 0
	.mux.Unlock()
}

// NewMessageIDGen creates new message id generator.
//
// Current time will be provided by now() function, e.g. the server time of
// mtproto.ServerTime.
func ( func() time.Time) *MessageIDGen {
	return &MessageIDGen{
		now: ,
	}
}

// MessageIDBuf stores the last N received message ids and is used in replay
// attack mitigation.
//
// It works like TDLib's MessageIdDuplicateChecker: ids are kept sorted in a
// buffer of 2N, so an id is checked by binary search, an increasing id (the
// common case) is appended, and the oldest N are dropped at once when the
// buffer is full.
type MessageIDBuf struct {
	mux sync.Mutex
	// buf[:end] holds the stored ids in increasing order.
	buf []int64
	end int
	n   int
}

// NewMessageIDBuf initializes new message id buffer for last N stored values.
func ( int) *MessageIDBuf {
	if  < 1 {
		 = 1
	}
	return &MessageIDBuf{
		buf: make([]int64, 2*),
		n:   ,
	}
}

// Reset forgets all stored message ids, e.g. when a new session is started.
func ( *MessageIDBuf) () {
	.mux.Lock()
	defer .mux.Unlock()

	.end = 0
}

// Consume returns false if message should be discarded.
func ( *MessageIDBuf) ( int64) bool {
	// In addition, the identifiers (msg_id) of the last N messages received
	// from the other side must be stored, and if a message comes in with an
	// msg_id lower than all or equal to any of the stored values, that message
	// is to be ignored. Otherwise, the new message msg_id is added to the set,
	// and, if the number of stored msg_id values is greater than N, the oldest
	// (i. e. the lowest) is discarded.
	//
	// https://core.telegram.org/mtproto/security_guidelines#checking-msg-id
	if  <= 0 {
		return false
	}

	.mux.Lock()
	defer .mux.Unlock()

	if .end == len(.buf) {
		// Forget the oldest N ids.
		copy(.buf[:.n], .buf[.n:])
		.end = .n
	}
	if .end == 0 ||  > .buf[.end-1] {
		// Fast path: ids mostly increase.
		.buf[.end] = 
		.end++
		return true
	}
	if .end >= .n &&  < .buf[0] {
		// Lower than all of the last N stored ids.
		return false
	}

	// Binary search for the first stored id >= newID.
	,  := 0, .end
	for  <  {
		 := int(uint(+) >> 1)
		if .buf[] <  {
			 =  + 1
		} else {
			 = 
		}
	}
	if .buf[] ==  {
		// Equal to a stored id.
		return false
	}
	copy(.buf[+1:.end+1], .buf[:.end])
	.buf[] = 
	.end++
	return true
}