lib/bitcoin/protocol/txout.rb in bitcoin-ruby-0.0.1 vs lib/bitcoin/protocol/txout.rb in bitcoin-ruby-0.0.2

- old
+ new

@@ -1,5 +1,7 @@ +# encoding: ascii-8bit + module Bitcoin module Protocol class TxOut @@ -21,32 +23,44 @@ @value == other.value && @pk_script == other.pk_script end # parse raw binary data for transaction output def parse_data(data) - idx = 0 - @value = data[idx...idx+=8].unpack("Q")[0] - @pk_script_length, tmp = Protocol.unpack_var_int(data[idx..-1]) - idx += data[idx..-1].bytesize - tmp.bytesize - @pk_script = data[idx...idx+=@pk_script_length] - idx + buf = data.is_a?(String) ? StringIO.new(data) : data + parse_data_from_io(buf) + buf.pos end + def self.from_io(buf) + txout = new; txout.parse_data_from_io(buf); txout + end + + # parse raw binary data for transaction output + def parse_data_from_io(buf) + @value = buf.read(8).unpack("Q")[0] + @pk_script_length = Protocol.unpack_var_int_from_io(buf) + @pk_script = buf.read(@pk_script_length) + end + alias :parse_payload :parse_data def to_payload - buf = [ @value ].pack("Q") - buf << Protocol.pack_var_int(@pk_script_length) - buf << @pk_script if @pk_script_length > 0 - buf + [@value].pack("Q") << Protocol.pack_var_int(@pk_script_length) << @pk_script end - def to_hash - { 'value' => "%.8f" % (@value / 100000000.0), - 'scriptPubKey' => Bitcoin::Script.new(@pk_script).to_string } + def to_null_payload + self.class.new(-1, '').to_payload end + def to_hash(options = {}) + script = Bitcoin::Script.new(@pk_script) + h = { 'value' => "%.8f" % (@value / 100000000.0), + 'scriptPubKey' => script.to_string } + h["address"] = script.get_address if script.is_hash160? && options[:with_address] + h + end + def self.from_hash(output) amount = output['value'].gsub('.','').to_i script = Script.binary_from_string(output['scriptPubKey']) new(amount, script) end @@ -62,9 +76,10 @@ # create output spending +value+ btc (base units) to +address+ def self.value_to_address(value, address) pk_script = Bitcoin::Script.to_address_script(address) + raise "Script#pk_script nil with address #{address}" unless pk_script new(value, pk_script) end end