From 6937b87a7cb4686971d30595d6ef0929c9fa75c7 Mon Sep 17 00:00:00 2001 From: SomberNight Date: Tue, 25 Feb 2020 20:05:46 +0100 Subject: [PATCH] transaction.BCDataStream: minor fixes - fix read/write_boolean (though unused...) - sanity check in read_bytes --- electrum/tests/test_transaction.py | 14 ++++++++++++++ electrum/transaction.py | 13 ++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/electrum/tests/test_transaction.py b/electrum/tests/test_transaction.py index b130db707..852d3fd86 100644 --- a/electrum/tests/test_transaction.py +++ b/electrum/tests/test_transaction.py @@ -55,6 +55,8 @@ class TestBCDataStream(ElectrumTestCase): def test_bytes(self): s = transaction.BCDataStream() + with self.assertRaises(transaction.SerializationError): + s.read_bytes(1) s.write(b'foobar') self.assertEqual(s.read_bytes(3), b'foo') self.assertEqual(s.read_bytes(2), b'ba') @@ -64,6 +66,18 @@ class TestBCDataStream(ElectrumTestCase): self.assertEqual(s.read_bytes(1), b'r') self.assertEqual(s.read_bytes(0), b'') + def test_bool(self): + s = transaction.BCDataStream() + s.write(b'f\x00\x00b') + self.assertTrue(s.read_boolean()) + self.assertFalse(s.read_boolean()) + self.assertFalse(s.read_boolean()) + self.assertTrue(s.read_boolean()) + s.write_boolean(True) + s.write_boolean(False) + self.assertEqual(b'\x01\x00', s.read_bytes(2)) + self.assertFalse(s.can_read_more()) + class TestTransaction(ElectrumTestCase): diff --git a/electrum/transaction.py b/electrum/transaction.py index 923ae0e49..908bda7af 100644 --- a/electrum/transaction.py +++ b/electrum/transaction.py @@ -244,7 +244,8 @@ class BCDataStream(object): self.input = None self.read_cursor = 0 - def write(self, _bytes): # Initialize with string of _bytes + def write(self, _bytes: Union[bytes, bytearray]): # Initialize with string of _bytes + assert isinstance(_bytes, (bytes, bytearray)) if self.input is None: self.input = bytearray(_bytes) else: @@ -271,12 +272,14 @@ class BCDataStream(object): self.write_compact_size(len(string)) self.write(string) - def read_bytes(self, length) -> bytes: + def read_bytes(self, length: int) -> bytes: + if self.input is None: + raise SerializationError("call write(bytes) before trying to deserialize") 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: + if 0 <= read_begin <= read_end <= input_len: result = self.input[read_begin:read_end] # type: bytearray self.read_cursor += length return bytes(result) @@ -288,7 +291,7 @@ class BCDataStream(object): return False return self.read_cursor < len(self.input) - def read_boolean(self): return self.read_bytes(1)[0] != chr(0) + def read_boolean(self) -> bool: return self.read_bytes(1) != b'\x00' def read_int16(self): return self._read_num('