fromBytes static method

Point fromBytes(
  1. Uint8List bytes
)

Implementation

static Point fromBytes(Uint8List bytes) {
  // first byte is prefix, rest is data
  final int head = bytes[0];
  final Uint8List tail = bytes.sublist(1);

  final BigInt x = Utilities.sliceBytes(tail, 0, fLen);
  final int len = bytes.length;

  Point? p;
  // next 32 bytes are x coordinate
  if (len == 33 && [0x02, 0x03].contains(head)) {
    // compressed points: 33b, start
    if (!Utilities.fe(x)) {
      // with byte 0x02 or 0x03. Check if 0<x<P
      throw Exception('Point hex invalid: x not FE');
    }
    // x³ + ax + b is right side of equation

    BigInt y = Utilities.sqrt(Utilities.crv(x));
    // y² is equivalent left-side. Calculate y²:
    final bool isYOdd = (y & BigInt.one) == BigInt.one;
    // y = √y²; there are two solutions: y, -y
    final bool headOdd = (head & 1) == 1;

    // determine proper solution
    if (headOdd != isYOdd) {
      y = Utilities.mod(-y);
    }
    // create point
    p = Point(x, y, BigInt.one);
  }

  // Uncompressed points: 65b, start with 0x04
  if (len == 65 && head == 0x04) {
    p = Point(x, Utilities.sliceBytes(tail, fLen, 2 * fLen), BigInt.one);
  }

  if (p != null) {
    // Verify the result
    return p.ok();
  }
  throw Exception('Point is not on curve');
}