wownero-python/monero/address.py

176 lines
6.2 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-30 03:19:58 +00:00
import struct
2017-11-24 02:05:16 +00:00
from sha3 import keccak_256
from . import base58
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}$')
2017-11-24 02:05:16 +00:00
class Address(object):
2018-01-16 21:07:51 +00:00
"""Monero address.
2018-02-15 20:20:48 +00:00
Address of this class is the master address for a :class:`Wallet <monero.wallet.Wallet>`.
2018-01-16 21:07:51 +00:00
:param address: a Monero address as string-like object
:param label: a label for the address (defaults to `None`)
"""
label = None
2018-05-21 15:25:28 +00:00
_valid_netbytes = (18, 53, 24)
# NOTE: _valid_netbytes order is (mainnet, testnet, stagenet)
2017-11-30 02:43:34 +00:00
2018-01-30 08:43:08 +00:00
def __init__(self, addr, label=None):
addr = str(addr)
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 _decode(self, address):
2017-11-30 03:19:58 +00:00
self._decoded = bytearray(unhexlify(base58.decode(address)))
2017-11-24 02:05:16 +00:00
checksum = self._decoded[-4:]
if checksum != keccak_256(self._decoded[:-4]).digest()[:4]:
2018-01-30 18:56:36 +00:00
raise ValueError("Invalid checksum in address {}".format(address))
2017-11-30 02:43:34 +00:00
if self._decoded[0] not in self._valid_netbytes:
raise ValueError("Invalid address netbyte {nb}. Allowed values are: {allowed}".format(
2017-11-30 03:25:42 +00:00
nb=self._decoded[0],
2017-11-30 02:43:34 +00:00
allowed=", ".join(map(lambda b: '%02x' % b, self._valid_netbytes))))
2017-11-24 02:05:16 +00:00
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]
def view_key(self):
2018-01-16 21:07:51 +00:00
"""Returns public view key.
:rtype: str
"""
2017-11-24 02:05:16 +00:00
return hexlify(self._decoded[33:65]).decode()
def spend_key(self):
2018-01-16 21:07:51 +00:00
"""Returns public spend key.
:rtype: str
"""
2017-11-24 02:05:16 +00:00
return hexlify(self._decoded[1:33]).decode()
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)))
def __repr__(self):
return base58.encode(hexlify(self._decoded))
def __eq__(self, other):
if isinstance(other, Address):
return str(self) == str(other)
if isinstance(other, str):
return str(self) == other
2018-01-30 08:43:08 +00:00
return super(Address, self).__eq__(other)
2017-11-24 02:05:16 +00:00
2017-11-30 02:43:34 +00:00
class SubAddress(Address):
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):
2017-11-29 03:37:01 +00:00
address = 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
"""
2017-11-29 03:37:01 +00:00
addr = 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)))