Signature.createSignature constructor
Implementation
factory Signature.createSignature(
Uint8List payload,
Uint8List privateKey, {
TransactionType txType = TransactionType.Legacy,
int? chainId,
bool hashPayload = true,
}) {
final digest = SHA256Digest();
final signer = ECDSASigner(null, HMac(digest, 64));
final params = ECCurve_secp256k1();
final key = ECPrivateKey(bytesToUnsignedInt(privateKey), params);
signer.init(true, PrivateKeyParameter(key));
if (hashPayload) {
payload = keccak256(payload);
}
var sig = signer.generateSignature(payload) as ECSignature;
if (sig.s.compareTo(params.n >> 1) > 0) {
final canonicalS = params.n - sig.s;
sig = ECSignature(sig.r, canonicalS);
}
final publickey =
bytesToUnsignedInt(privateKeyToPublic(bytesToUnsignedInt(privateKey)));
final rcID = EC.secp256k1.calculateRecoveryId(publickey, sig, payload);
if (rcID == null) {
throw Exception('Failed to calculate recovery id');
}
final int v = switch (txType) {
TransactionType.Legacy =>
chainId != null ? (rcID + (chainId * 2 + 35)) : (rcID + 27),
TransactionType.Type1 || TransactionType.Type2 => rcID,
};
return Signature(sig.r, sig.s, v);
}