lib/bitcoin/protocol/tx.rb in bitcoin-ruby-0.0.7 vs lib/bitcoin/protocol/tx.rb in bitcoin-ruby-0.0.8
- old
+ new
@@ -65,18 +65,30 @@
buf = data.is_a?(String) ? StringIO.new(data) : data
payload_start = buf.pos
@ver = buf.read(4).unpack("V")[0]
+ return false if buf.eof?
+
in_size = Protocol.unpack_var_int_from_io(buf)
@in = []
- in_size.times{ @in << TxIn.from_io(buf) }
+ in_size.times{
+ break if buf.eof?
+ @in << TxIn.from_io(buf)
+ }
+ return false if buf.eof?
+
out_size = Protocol.unpack_var_int_from_io(buf)
@out = []
- out_size.times{ @out << TxOut.from_io(buf) }
+ out_size.times{
+ break if buf.eof?
+ @out << TxOut.from_io(buf)
+ }
+ return false if buf.eof?
+
@lock_time = buf.read(4).unpack("V")[0]
payload_end = buf.pos;
buf.seek(payload_start)
@payload = buf.read( payload_end-payload_start )
@@ -223,10 +235,11 @@
'vin_sz' => @in.size, 'vout_sz' => @out.size,
'lock_time' => @lock_time, 'size' => (@payload ||= to_payload).bytesize,
'in' => @in.map{|i| i.to_hash(options) },
'out' => @out.map{|o| o.to_hash(options) }
}
+ h['nid'] = normalized_hash if options[:with_nid]
h
end
# generates rawblock json as seen in the block explorer.
def to_json(options = {:space => ''}, *a)
@@ -238,17 +251,20 @@
def to_json_file(path)
File.open(path, 'wb'){|f| f.print to_json; }
end
# parse ruby hash (see also #to_hash)
- def self.from_hash(h)
+ def self.from_hash(h, do_raise=true)
tx = new(nil)
tx.ver, tx.lock_time = (h['ver'] || h['version']), h['lock_time']
ins = h['in'] || h['inputs']
outs = h['out'] || h['outputs']
ins .each{|input| tx.add_in TxIn.from_hash(input) }
outs.each{|output| tx.add_out TxOut.from_hash(output) }
tx.instance_eval{ @hash = hash_from_payload(@payload = to_payload) }
+ unless h['hash'] == tx.hash
+ raise "Tx hash mismatch! Claimed: #{h['hash']}, Actual: #{tx.hash}" if do_raise
+ end
tx
end
# convert ruby hash to raw binary
def self.binary_from_hash(h); from_hash(h).to_payload; end