def lift_x(x: int) -> Optional[Point]:
This is a function that given an X coordinate, computes one of the two corresponding Y coordinates on the curve; specifically, the even one.
Every possible value in the field of coordinates (integers modulo p, where p = 2256 - 232 - 977) has exactly 0 points on the curve y2 = x3 + 7, or exactly two. In case there are two points with a given X coordinate, the corresponding Y coordinates will be each other's negation (modulo p), and one will be even, and one will be odd. This lift_x function returns the one with the even Y.
y_sq = (pow(x, 3, p) + 7) % p #<-the curve
This computes y_sq = y2, using the fact that it equals x3 + 7 (mod p), using the curve equation.
y = pow(y_sq, (p + 1) // 4, p) # why is this __floordiv__ 4?
This computes the square root y of the value y_sq we determined in the previous now. In general, modular square roots can be computed using the Tonelli-Shanks algorithm, but for the secp256k1 modulus, this algorithm simply boils down to computing y_sq(p+1)/4 mod p. In Python, we need to write this (p+1)/4 as (p+1)//4 because we want exact integer arithmetic. (p+1)/4 would compute an approximate floating point number only.
if pow(y, 2, p) != y_sq:
return None
This verifies whether the computed value y is actually the modular square root of y_sq. If the input x value was not a valid X coordinate on the curve, then x3 + 7 won't be a square, and thus won't have a square root. However, the formula y_sq(p+1)/4 always yields a result, even when y_sq doesn't have a square root. So we need to check whether y2 = y_sq. If not, we return None immediately: the input X has no corresponding Y coordinates.
return (x, y if y & 1 == 0 else p-y) # make y odd if there is a sqrt?
This simply negates y (modulo p) if y is odd, thereby finding the other (even) solution. This guarantees returning the even Y coordinate out of the two solutions.