mirror of
https://github.com/trezor/trezor-firmware.git
synced 2024-11-18 13:38:12 +00:00
core/common: Add BytearrayReader and basic reader functions.
This commit is contained in:
parent
99f01cd316
commit
9459c5a5c2
25
core/src/apps/bitcoin/readers.py
Normal file
25
core/src/apps/bitcoin/readers.py
Normal file
@ -0,0 +1,25 @@
|
||||
from apps.common.readers import BytearrayReader, read_bitcoin_varint
|
||||
|
||||
|
||||
def read_bytes_prefixed(r: BytearrayReader) -> bytes:
|
||||
n = read_bitcoin_varint(r)
|
||||
return r.read(n)
|
||||
|
||||
|
||||
def read_op_push(r: BytearrayReader) -> int:
|
||||
prefix = r.get()
|
||||
if prefix < 0x4C:
|
||||
n = prefix
|
||||
elif prefix == 0x4C:
|
||||
n = r.get()
|
||||
elif prefix == 0x4D:
|
||||
n = r.get()
|
||||
n += r.get() << 8
|
||||
elif prefix == 0x4E:
|
||||
n = r.get()
|
||||
n += r.get() << 8
|
||||
n += r.get() << 16
|
||||
n += r.get() << 24
|
||||
else:
|
||||
raise ValueError
|
||||
return n
|
47
core/src/apps/common/readers.py
Normal file
47
core/src/apps/common/readers.py
Normal file
@ -0,0 +1,47 @@
|
||||
if False:
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class BytearrayReader:
|
||||
def __init__(self, data: bytes):
|
||||
self.data = data
|
||||
self.offset = 0
|
||||
|
||||
def get(self) -> int:
|
||||
ret = self.data[self.offset]
|
||||
self.offset += 1
|
||||
return ret
|
||||
|
||||
def peek(self) -> int:
|
||||
return self.data[self.offset]
|
||||
|
||||
def read(self, i: Optional[int] = None) -> bytes:
|
||||
if i is None:
|
||||
ret = self.data[self.offset :]
|
||||
self.offset = len(self.data)
|
||||
elif 0 <= i <= len(self.data) - self.offset:
|
||||
ret = self.data[self.offset : self.offset + i]
|
||||
self.offset += i
|
||||
else:
|
||||
raise IndexError
|
||||
return ret
|
||||
|
||||
def remaining_count(self) -> int:
|
||||
return len(self.data) - self.offset
|
||||
|
||||
|
||||
def read_bitcoin_varint(r: BytearrayReader) -> int:
|
||||
prefix = r.get()
|
||||
if prefix < 253:
|
||||
n = prefix
|
||||
elif prefix == 253:
|
||||
n = r.get()
|
||||
n += r.get() << 8
|
||||
elif prefix == 254:
|
||||
n = r.get()
|
||||
n += r.get() << 8
|
||||
n += r.get() << 16
|
||||
n += r.get() << 24
|
||||
else:
|
||||
raise ValueError
|
||||
return n
|
Loading…
Reference in New Issue
Block a user