fix BCDataStream.read_bytes (#5991)

* fix BCDataStream.read_bytes

* followup fix BCDataStream.read_bytes: fix TestBCDataStream.test_bytes
This commit is contained in:
zebra-lucky 2020-02-25 20:58:03 +02:00 committed by GitHub
parent aaf174ef3e
commit c0be0471f2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 6 deletions

View file

@ -58,8 +58,12 @@ class TestBCDataStream(ElectrumTestCase):
s.write(b'foobar')
self.assertEqual(s.read_bytes(3), b'foo')
self.assertEqual(s.read_bytes(2), b'ba')
self.assertEqual(s.read_bytes(4), b'r')
self.assertEqual(s.read_bytes(1), b'')
with self.assertRaises(transaction.SerializationError):
s.read_bytes(4)
self.assertEqual(s.read_bytes(0), b'')
self.assertEqual(s.read_bytes(1), b'r')
self.assertEqual(s.read_bytes(0), b'')
class TestTransaction(ElectrumTestCase):

View file

@ -272,12 +272,16 @@ class BCDataStream(object):
self.write(string)
def read_bytes(self, length) -> bytes:
try:
result = self.input[self.read_cursor:self.read_cursor+length] # type: bytearray
assert length >= 0
input_len = len(self.input)
read_begin = self.read_cursor
read_end = read_begin + length
if 0 <= read_begin <= input_len and read_end <= input_len:
result = self.input[read_begin:read_end] # type: bytearray
self.read_cursor += length
return bytes(result)
except IndexError:
raise SerializationError("attempt to read past end of buffer") from None
else:
raise SerializationError('attempt to read past end of buffer')
def can_read_more(self) -> bool:
if not self.input: