signMessage method

String signMessage(
  1. String message, {
  2. bool compressed = true,
})

Returns a Bitcoin compact signature in hex

Implementation

String signMessage(String message, {bool compressed = true}) {
  final m = singleHash(magicMessage(message));
  final sign = ec.sign(m, toBytes());
  int prefix = 27;
  if (compressed) {
    prefix += 4;
  }
  final address = getPublic().toAddress(compressed: compressed);
  for (int i = prefix; i < prefix + 4; i++) {
    try {
      final sig = Uint8List.fromList(
          [...utf8.encode(String.fromCharCode(i)), ...sign]);
      final pub = ECPublic.getSignaturPublic(message, sig);
      if (pub?.toAddress(compressed: compressed).getH160 == address.getH160) {
        return bytesToHex(sig);
      }
    } catch (e) {
      continue;
    }
  }
  throw Exception("cannot validate message");
}