wownero-python/monero/address.py

200 lines
7.0 KiB
Python
Raw Normal View History

2017-11-24 02:05:16 +00:00
from binascii import hexlify, unhexlify
2017-12-10 01:54:09 +00:00
import re
2017-11-24 02:05:16 +00:00
from sha3 import keccak_256
2020-01-13 09:42:50 +00:00
import six
2019-01-03 18:03:33 +00:00
import struct
2017-11-24 02:05:16 +00:00
from . import base58
2018-11-30 00:23:49 +00:00
from . import ed25519
2017-12-27 00:49:59 +00:00
from . import numbers
2017-11-24 02:05:16 +00:00
2017-12-10 01:54:09 +00:00
_ADDR_REGEX = re.compile(r'^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{95}$')
_IADDR_REGEX = re.compile(r'^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{106}$')
2018-12-15 03:53:19 +00:00
class BaseAddress(object):
label = None
2017-11-30 02:43:34 +00:00
2018-01-30 08:43:08 +00:00
def __init__(self, addr, label=None):
2019-10-07 13:10:54 +00:00
addr = addr.decode() if isinstance(addr, bytes) else str(addr)
2018-01-30 08:43:08 +00:00
if not _ADDR_REGEX.match(addr):
2017-12-10 01:54:09 +00:00
raise ValueError("Address must be 95 characters long base58-encoded string, "
2018-01-30 08:43:08 +00:00
"is {addr} ({len} chars length)".format(addr=addr, len=len(addr)))
self._decode(addr)
self.label = label or self.label
2017-11-24 02:05:16 +00:00
def view_key(self):
"""Returns public view key.
:rtype: str
"""
return hexlify(self._decoded[33:65]).decode()
def spend_key(self):
"""Returns public spend key.
:rtype: str
"""
return hexlify(self._decoded[1:33]).decode()
2018-05-21 15:25:28 +00:00
def is_mainnet(self):
"""Returns `True` if the address belongs to mainnet.
:rtype: bool
"""
return self._decoded[0] == self._valid_netbytes[0]
2017-11-24 02:05:16 +00:00
def is_testnet(self):
2018-01-16 21:07:51 +00:00
"""Returns `True` if the address belongs to testnet.
:rtype: bool
"""
2017-11-30 02:43:34 +00:00
return self._decoded[0] == self._valid_netbytes[1]
2017-11-24 02:05:16 +00:00
2018-05-21 15:25:28 +00:00
def is_stagenet(self):
"""Returns `True` if the address belongs to stagenet.
:rtype: bool
"""
return self._decoded[0] == self._valid_netbytes[2]
2018-12-15 03:53:19 +00:00
def _decode(self, address):
self._decoded = bytearray(unhexlify(base58.decode(address)))
checksum = self._decoded[-4:]
if checksum != keccak_256(self._decoded[:-4]).digest()[:4]:
raise ValueError("Invalid checksum in address {}".format(address))
if self._decoded[0] not in self._valid_netbytes:
raise ValueError("Invalid address netbyte {nb}. Allowed values are: {allowed}".format(
nb=self._decoded[0],
allowed=", ".join(map(lambda b: '%02x' % b, self._valid_netbytes))))
def __repr__(self):
return base58.encode(hexlify(self._decoded))
def __eq__(self, other):
if isinstance(other, BaseAddress):
return str(self) == str(other)
2020-01-13 09:42:50 +00:00
elif isinstance(other, six.text_type) or isinstance(other, six.string_types):
return str(self) == six.ensure_str(other)
2018-12-15 03:53:19 +00:00
return super(BaseAddress, self).__eq__(other)
def __hash__(self):
return hash(str(self))
2019-10-04 12:38:17 +00:00
def __format__(self, spec):
return format(str(self), spec)
2018-12-15 03:53:19 +00:00
class Address(BaseAddress):
"""Monero address.
Address of this class is the master address for a :class:`Wallet <monero.wallet.Wallet>`.
:param address: a Monero address as string-like object
:param label: a label for the address (defaults to `None`)
"""
_valid_netbytes = (18, 53, 24)
# NOTE: _valid_netbytes order is (mainnet, testnet, stagenet)
2018-11-30 00:23:49 +00:00
def check_private_view_key(self, key):
"""Checks if private view key matches this address.
:rtype: bool
"""
return ed25519.public_from_secret_hex(key) == self.view_key()
def check_private_spend_key(self, key):
"""Checks if private spend key matches this address.
:rtype: bool
"""
return ed25519.public_from_secret_hex(key) == self.spend_key()
2017-11-24 02:05:16 +00:00
def with_payment_id(self, payment_id=0):
2018-01-16 21:07:51 +00:00
"""Integrates payment id into the address.
2018-02-15 20:20:48 +00:00
:param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
(max 64-bit long)
2018-01-16 21:07:51 +00:00
2018-02-15 20:20:48 +00:00
:rtype: `IntegratedAddress`
:raises: `TypeError` if the payment id is too long
2018-01-16 21:07:51 +00:00
"""
2018-01-06 22:12:42 +00:00
payment_id = numbers.PaymentID(payment_id)
if not payment_id.is_short():
2018-01-18 02:03:18 +00:00
raise TypeError("Payment ID {0} has more than 64 bits and cannot be integrated".format(payment_id))
2018-05-21 15:25:28 +00:00
prefix = 54 if self.is_testnet() else 25 if self.is_stagenet() else 19
2018-01-06 22:12:42 +00:00
data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))
2017-11-30 03:19:58 +00:00
checksum = bytearray(keccak_256(data).digest()[:4])
2017-11-24 02:05:16 +00:00
return IntegratedAddress(base58.encode(hexlify(data + checksum)))
2018-12-15 03:53:19 +00:00
class SubAddress(BaseAddress):
2018-01-16 21:07:51 +00:00
"""Monero subaddress.
2018-02-15 20:20:48 +00:00
Any type of address which is not the master one for a wallet.
2018-01-16 21:07:51 +00:00
"""
2018-05-21 15:25:28 +00:00
_valid_netbytes = (42, 63, 36)
# NOTE: _valid_netbytes order is (mainnet, testnet, stagenet)
2017-11-30 02:43:34 +00:00
def with_payment_id(self, _):
2017-12-10 01:54:09 +00:00
raise TypeError("SubAddress cannot be integrated with payment ID")
2017-11-30 02:43:34 +00:00
2017-11-24 02:05:16 +00:00
class IntegratedAddress(Address):
2018-01-16 21:07:51 +00:00
"""Monero integrated address.
A master address integrated with payment id (short one, max 64 bit).
"""
2018-05-21 15:25:28 +00:00
_valid_netbytes = (19, 54, 25)
# NOTE: _valid_netbytes order is (mainnet, testnet, stagenet)
2017-11-30 02:43:34 +00:00
2017-11-24 02:05:16 +00:00
def __init__(self, address):
2019-10-07 13:10:54 +00:00
address = address.decode() if isinstance(address, bytes) else str(address)
2017-12-10 01:54:09 +00:00
if not _IADDR_REGEX.match(address):
raise ValueError("Integrated address must be 106 characters long base58-encoded string, "
"is {addr} ({len} chars length)".format(addr=address, len=len(address)))
2017-11-24 02:05:16 +00:00
self._decode(address)
def payment_id(self):
2018-01-16 21:07:51 +00:00
"""Returns the integrated payment id.
2018-02-15 20:20:48 +00:00
:rtype: :class:`PaymentID <monero.numbers.PaymentID>`
2018-01-16 21:07:51 +00:00
"""
2018-01-06 22:12:42 +00:00
return numbers.PaymentID(hexlify(self._decoded[65:-4]).decode())
2017-11-24 02:05:16 +00:00
def base_address(self):
2018-01-16 21:07:51 +00:00
"""Returns the base address without payment id.
2018-02-15 20:20:48 +00:00
:rtype: :class:`Address`
2018-01-16 21:07:51 +00:00
"""
2018-05-21 15:25:28 +00:00
prefix = 53 if self.is_testnet() else 24 if self.is_stagenet() else 18
2017-11-30 03:19:58 +00:00
data = bytearray([prefix]) + self._decoded[1:65]
2017-11-24 02:05:16 +00:00
checksum = keccak_256(data).digest()[:4]
return Address(base58.encode(hexlify(data + checksum)))
def address(addr, label=None):
2018-01-16 21:07:51 +00:00
"""Discover the proper class and return instance for a given Monero address.
:param addr: the address as a string-like object
:param label: a label for the address (defaults to `None`)
2018-02-15 20:20:48 +00:00
:rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`
2018-01-16 21:07:51 +00:00
"""
2019-10-07 13:10:54 +00:00
addr = addr.decode() if isinstance(addr, bytes) else str(addr)
2017-12-10 01:54:09 +00:00
if _ADDR_REGEX.match(addr):
2017-11-30 03:19:58 +00:00
netbyte = bytearray(unhexlify(base58.decode(addr)))[0]
2017-11-30 02:43:34 +00:00
if netbyte in Address._valid_netbytes:
return Address(addr, label=label)
2017-11-30 02:43:34 +00:00
elif netbyte in SubAddress._valid_netbytes:
return SubAddress(addr, label=label)
2018-01-30 08:43:08 +00:00
raise ValueError("Invalid address netbyte {nb:x}. Allowed values are: {allowed}".format(
nb=netbyte,
2017-11-30 02:43:34 +00:00
allowed=", ".join(map(
lambda b: '%02x' % b,
sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))
2017-12-10 01:54:09 +00:00
elif _IADDR_REGEX.match(addr):
2017-11-24 02:05:16 +00:00
return IntegratedAddress(addr)
2017-12-10 01:54:09 +00:00
raise ValueError("Address must be either 95 or 106 characters long base58-encoded string, "
2018-01-30 08:43:08 +00:00
"is {addr} ({len} chars length)".format(addr=addr, len=len(addr)))