trySign function

SchnorrSignature? trySign(
  1. List<int> msg,
  2. BigInt k,
  3. BigInt privKey,
  4. List<int> pubKey
)

Implementation

SchnorrSignature? trySign(
    List<int> msg, BigInt k, BigInt privKey, List<int> pubKey) {
  bool isZero(BigInt test) =>
      test.compareTo(BigInt.from(0)) != 0 ? false : true;
  bool isGteCurve(BigInt test) => test.compareTo(params.n) > 1 ? true : false;

  if (isZero(privKey)) {
    throw 'Bad private key.';
  }
  if (isGteCurve(privKey)) {
    throw 'Bad private key';
  }

  /// 1a. check that k is not 0
  if (isZero(k)) {
    return null;
  }

  /// 1b. check that k is < the order of the group
  if (isGteCurve(k)) {
    return null;
  }

  /// 2. Compute commitment Q = kG, where g is the base point
  ECPoint Q = (params.G * k)!;

  /// convert the commitment to octets first
  BigInt compressedQ = numbers.bytesToInt(Q.getEncoded());

  /// 3. Compute the challenge r = H(Q || pubKey || msg)
  /// mod reduce the r value by the order of secp256k1, n

  BigInt r = hash(compressedQ, pubKey, msg) % (params.n);

  BigInt h = r;

  if (isZero(h)) {
    return null;
  }

  /// 4. Compute s = k - r * prv
  /// 4a. Compute r * prv
  BigInt s = (h * privKey) % (params.n);

  /// 4b. Compute s = k - r * prv mod n
  s = (k - s) % (params.n);

  if (isZero(s)) {
    return null;
  }

  return new SchnorrSignature(r, s);
}