class ECRECPrecompiledContract extends AbstractPrecompiledContract {

  @Override
  public Bytes compute(final Bytes input, final MessageFrame messageFrame) {
    final int size = input.size();
    final Bytes d = size >= 128 ? input : Bytes.wrap(input, MutableBytes.create(128 - size));
    final Bytes32 h = Bytes32.wrap(d, 0);
    // Note that the Yellow Paper defines v as the next 32 bytes (so 32..63). Yet, v is a simple
    // byte in ECDSARECOVER and the Yellow Paper is not very clear on this mismatch but it appears
    // it is simply the last byte of those 32 bytes that needs to be used. It does appear we need
    // to check the rest of the bytes are zero though.
    if (!d.slice(32, 31).isZero()) {
      return Bytes.EMPTY;
    }

    final int recId = d.get(63) - V_BASE;
    final BigInteger r = d.slice(64, 32).toUnsignedBigInteger();
    final BigInteger s = d.slice(96, 32).toUnsignedBigInteger();

    final Signature signature;
    try {
      signature = Signature.create(r, s, (byte) recId);
    } catch (final IllegalArgumentException e) {
      return Bytes.EMPTY;
    }

    // SECP256K1#PublicKey#recoverFromSignature throws an Illegal argument exception
    // when it is unable to recover the key. There is not a straightforward way to
    // check the arguments ahead of time to determine if the fail will happen and
    // the library needs to be updated.
    try {
      final Optional<PublicKey> recovered = PublicKey.recoverFromSignature(h, signature);
      if (!recovered.isPresent()) {
        return Bytes.EMPTY;
      }

      final Bytes32 hashed = Hash.hash(recovered.get().getEncodedBytes());
      final MutableBytes32 result = MutableBytes32.create();
      hashed.slice(12).copyTo(result, 12);
      return result;
    } catch (final IllegalArgumentException e) {
      return Bytes.EMPTY;
    }
  }

  public  ECRECPrecompiledContract(final GasCalculator gasCalculator);

}