From 08402f1b02e52136933e59ad434407e555368925 Mon Sep 17 00:00:00 2001 From: Micah Winkelspecht Date: Wed, 18 Dec 2013 21:53:11 -0800 Subject: [PATCH] Fixing a bug where calling #compressed or #uncompressed on a PublicKey errantly mutated the object rather than returning a deep clone. --- lib/money-tree/key.rb | 4 +-- lib/money-tree/node.rb | 3 ++- spec/lib/money-tree/public_key_spec.rb | 36 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/lib/money-tree/key.rb b/lib/money-tree/key.rb index 71a70c7..4253182 100644 --- a/lib/money-tree/key.rb +++ b/lib/money-tree/key.rb @@ -180,13 +180,13 @@ def compression=(compression_type = :compressed) end def compressed - compressed_key = self.dup + compressed_key = self.class.new raw_key # deep clone compressed_key.set_point to_i, compressed: true compressed_key end def uncompressed - uncompressed_key = self.dup + uncompressed_key = self.class.new raw_key # deep clone uncompressed_key.set_point to_i, compressed: false uncompressed_key end diff --git a/lib/money-tree/node.rb b/lib/money-tree/node.rb index 7deae28..a9f3d91 100644 --- a/lib/money-tree/node.rb +++ b/lib/money-tree/node.rb @@ -179,7 +179,8 @@ def node_for_path(path) nodes << self else i = parse_index(part) - nodes << nodes.last.subnode(i) + node = nodes.last || self + nodes << node.subnode(i) end end if force_public or parts.first == 'M' diff --git a/spec/lib/money-tree/public_key_spec.rb b/spec/lib/money-tree/public_key_spec.rb index b31bb63..0268b95 100644 --- a/spec/lib/money-tree/public_key_spec.rb +++ b/spec/lib/money-tree/public_key_spec.rb @@ -121,4 +121,40 @@ lambda { @key = MoneyTree::PublicKey.new 'THISISNOTAVALIDKEY' }.should raise_error(MoneyTree::Key::KeyFormatNotFound) end end + + describe "recalcuating public key" do + it "produces same results" do + results = [] + 100.times do + results << MoneyTree::PublicKey.new('042dfc2557a007c93092c2915f11e8aa70c4f399a6753e2e908330014091580e4b11203096f1a1c5276a73f91b9465357004c2103cc42c63d6d330df589080d2e4').to_s + end + results.uniq.length.should == 1 + end + end + + describe "#uncompressed" do + before do + @key = MoneyTree::PublicKey.new('022dfc2557a007c93092c2915f11e8aa70c4f399a6753e2e908330014091580e4b') + end + + it "does not mutate key" do + before_str = @key.to_s + @key.uncompressed + after_str = @key.to_s + before_str.should == after_str + end + end + + describe "#compressed" do + before do + @key = MoneyTree::PublicKey.new('042dfc2557a007c93092c2915f11e8aa70c4f399a6753e2e908330014091580e4b11203096f1a1c5276a73f91b9465357004c2103cc42c63d6d330df589080d2e4') + end + + it "does not mutate key" do + before_str = @key.to_s + @key.compressed + after_str = @key.to_s + before_str.should == after_str + end + end end