In the java version of Ethereum, I see the signature code as follows:

public ECDSASignature sign(byte[] messageHash) {
    ECDSASignature sig = doSign(messageHash);
    // Now we have to work backwards to figure out the recId needed to recover the signature.
    int recId = -1;
    byte[] thisKey = this.pub.getEncoded(/* compressed */ false);
    for (int i = 0; i < 4; i++) {
        byte[] k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash);
        if (k != null && Arrays.equals(k, thisKey)) {
            recId = i;
    if (recId == -1)
        throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
    sig.v = (byte) (recId + 27);
    return sig;

Why this code use loop (for (int i = 0; i < 4; i++)) to get v (aka recId)? It can change the signature code and get v from the signing process. Can you please tell me? Thank you.

  • Is anyone can help? Thank you. – Felix LL Feb 13 at 11:10

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.