Encoding from Extended Coordinates

To encode a Ristretto point represented by the point $$(X:Y:Z:T)$$ in extended coordinates, an implementation proceeds as follows.

1. $$u_1 \gets (Z_0 + Y_0)(Z_0 - Y_0)$$.
2. $$u_2 \gets X_0 Y_0$$.
3. $$I \gets \mathrm{invsqrt}(u_1 u_2^2)$$.
4. $$D_1 \gets u_1 I$$.
5. $$D_2 \gets u_2 I$$.
6. $$Z_{inv} \gets D_1 D_2 T_0$$.
7. If $$T_0 Z_{inv}$$ is negative:
1. $$(X, Y) \gets (Y_0 (\pm 1/\sqrt{a}), X_0 (\mp \sqrt{a}))$$.
2. $$D \gets D_1 / \sqrt{a-d}$$.
8. Otherwise:
1. $$(X, Y) \gets (X_0, Y_0)$$.
2. $$D \gets D_2$$.
9. If $$X Z_{inv}$$ is negative, set $$Y \gets - Y$$.
10. Compute $$s \gets |\sqrt{-a} (Z - Y) D|$$, i..e, compute $$\sqrt{-a} (Z - Y) D$$ and negate it if it is negative.
11. Return the canonical byte encoding of $$s$$.

Since $$a = \pm 1$$, implementations can replace multiplications by $$a$$ with sign changes, as appropriate.

When $$a = -1$$, (10) becomes $$s \gets |(Z-Y)D|$$, and choosing $$Q_4 = (i, 0)$$ is convenient since it simplifies (7.1) to $$(X,Y) \gets (iY_0, iX_0)$$.

The inverse square root in step 3 always exists when $$(X:Y:Z:T)$$ is a valid representative.