In my recent endeavor to learn Scala, reading the Scala book by Martin Odersky et al. I remember being struck by the emphasis placed by the authors on the difficulty of properly overriding the equals and hashCode methods of our user-defined types. In particular, I remember that failing to define equals and hashCode consistently may lead to subtle bugs in code which handle hash-maps and dictionaries. Now the ECKey class of bitcoinj seems to suffer from such inconsistency. I was wondering if anyone knew the background to this, whether this is an oversight or a deliberate choice, or if there is a fundamental reason why equality between keys should take creation time into account (for example) while hashCode should ignore it. Am I being pedantic or should equals and hashCode be consistent?

import org.bitcoinj.core.ECKey;

public class Test {

  public static void main(String[] args){

  // random compressed key
  ECKey k1 = new ECKey(); 

  // same key, but creation time is different
  ECKey k2 = ECKey.fromPrivate(k1.getPrivKey());

  // The two keys are deemed different, due to creation time
  System.out.println(k1.equals(k2));  // false

  // yet hashCode ignores time of creation
  System.out.println(k1.hashCode() == k2.hashCode()); // true

  • 1
    This is a side note, but if you are interested in Scala & bitcoin feel free to look at / contribute to bitcoin-s github.com/bitcoin-s/bitcoin-s-core . We are trying to fix some of the warts bitcoinj has such as what you mentioned above – Chris Stewart Aug 21 '16 at 16:11
  • Thank you Chris, yes I am definitely interested in a Scala bitcoin library. I am still in a learning phase, but I will definitely look at this. – Sven Williamson Aug 21 '16 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.