2018-05-25 08:03:25 +02:00
|
|
|
import logging
|
2018-07-29 02:52:54 +02:00
|
|
|
import typing
|
|
|
|
from typing import List, Iterable, Optional
|
2018-05-25 15:54:01 +02:00
|
|
|
from binascii import hexlify
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-11-04 06:55:50 +01:00
|
|
|
from torba.client.basescript import BaseInputScript, BaseOutputScript
|
|
|
|
from torba.client.baseaccount import BaseAccount
|
|
|
|
from torba.client.constants import COIN, NULL_HASH32
|
|
|
|
from torba.client.bcd_data_stream import BCDataStream
|
|
|
|
from torba.client.hash import sha256, TXRef, TXRefImmutable
|
|
|
|
from torba.client.util import ReadOnlyList
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
if typing.TYPE_CHECKING:
|
2018-11-04 06:55:50 +01:00
|
|
|
from torba.client import baseledger
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
log = logging.getLogger()
|
|
|
|
|
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
class TXRefMutable(TXRef):
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
__slots__ = ('tx',)
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, tx: 'BaseTransaction') -> None:
|
|
|
|
super().__init__()
|
2018-07-15 03:34:07 +02:00
|
|
|
self.tx = tx
|
|
|
|
|
|
|
|
@property
|
|
|
|
def id(self):
|
|
|
|
if self._id is None:
|
|
|
|
self._id = hexlify(self.hash[::-1]).decode()
|
|
|
|
return self._id
|
|
|
|
|
|
|
|
@property
|
|
|
|
def hash(self):
|
|
|
|
if self._hash is None:
|
|
|
|
self._hash = sha256(sha256(self.tx.raw))
|
|
|
|
return self._hash
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-10-11 03:29:29 +02:00
|
|
|
@property
|
|
|
|
def height(self):
|
|
|
|
return self.tx.height
|
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
def reset(self):
|
|
|
|
self._id = None
|
|
|
|
self._hash = None
|
|
|
|
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
class TXORef:
|
|
|
|
|
|
|
|
__slots__ = 'tx_ref', 'position'
|
|
|
|
|
|
|
|
def __init__(self, tx_ref: TXRef, position: int) -> None:
|
|
|
|
self.tx_ref = tx_ref
|
|
|
|
self.position = position
|
|
|
|
|
|
|
|
@property
|
|
|
|
def id(self):
|
|
|
|
return '{}:{}'.format(self.tx_ref.id, self.position)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_null(self):
|
|
|
|
return self.tx_ref.is_null
|
|
|
|
|
|
|
|
@property
|
|
|
|
def txo(self) -> Optional['BaseOutput']:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
class TXORefResolvable(TXORef):
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
__slots__ = ('_txo',)
|
2018-07-15 03:34:07 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, txo: 'BaseOutput') -> None:
|
|
|
|
assert txo.tx_ref is not None
|
|
|
|
assert txo.position is not None
|
|
|
|
super().__init__(txo.tx_ref, txo.position)
|
2018-07-15 03:34:07 +02:00
|
|
|
self._txo = txo
|
2018-06-08 05:47:46 +02:00
|
|
|
|
|
|
|
@property
|
2018-07-15 03:34:07 +02:00
|
|
|
def txo(self):
|
|
|
|
return self._txo
|
|
|
|
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
class InputOutput:
|
2018-07-15 03:34:07 +02:00
|
|
|
|
|
|
|
__slots__ = 'tx_ref', 'position'
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, tx_ref: TXRef = None, position: int = None) -> None:
|
|
|
|
self.tx_ref = tx_ref
|
|
|
|
self.position = position
|
2018-06-08 05:47:46 +02:00
|
|
|
|
2018-05-25 08:03:25 +02:00
|
|
|
@property
|
2018-07-29 02:52:54 +02:00
|
|
|
def size(self) -> int:
|
2018-05-25 08:03:25 +02:00
|
|
|
""" Size of this input / output in bytes. """
|
|
|
|
stream = BCDataStream()
|
|
|
|
self.serialize_to(stream)
|
|
|
|
return len(stream.get_bytes())
|
|
|
|
|
2018-08-03 16:41:40 +02:00
|
|
|
def get_fee(self, ledger):
|
|
|
|
return self.size * ledger.fee_per_byte
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def serialize_to(self, stream, alternate_script=None):
|
|
|
|
raise NotImplementedError
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
|
|
|
|
class BaseInput(InputOutput):
|
|
|
|
|
2018-06-11 15:33:32 +02:00
|
|
|
script_class = BaseInputScript
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
NULL_SIGNATURE = b'\x00'*72
|
|
|
|
NULL_PUBLIC_KEY = b'\x00'*33
|
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
__slots__ = 'txo_ref', 'sequence', 'coinbase', 'script'
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, txo_ref: TXORef, script: BaseInputScript, sequence: int = 0xFFFFFFFF,
|
|
|
|
tx_ref: TXRef = None, position: int = None) -> None:
|
|
|
|
super().__init__(tx_ref, position)
|
2018-07-15 03:34:07 +02:00
|
|
|
self.txo_ref = txo_ref
|
2018-05-25 08:03:25 +02:00
|
|
|
self.sequence = sequence
|
2018-07-15 03:34:07 +02:00
|
|
|
self.coinbase = script if txo_ref.is_null else None
|
2018-07-29 02:52:54 +02:00
|
|
|
self.script = script if not txo_ref.is_null else None
|
2018-07-15 03:34:07 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_coinbase(self):
|
|
|
|
return self.coinbase is not None
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@classmethod
|
2018-07-29 02:52:54 +02:00
|
|
|
def spend(cls, txo: 'BaseOutput') -> 'BaseInput':
|
2018-05-25 08:03:25 +02:00
|
|
|
""" Create an input to spend the output."""
|
2018-07-15 03:34:07 +02:00
|
|
|
assert txo.script.is_pay_pubkey_hash, 'Attempting to spend unsupported output.'
|
2018-05-25 08:03:25 +02:00
|
|
|
script = cls.script_class.redeem_pubkey_hash(cls.NULL_SIGNATURE, cls.NULL_PUBLIC_KEY)
|
2018-07-15 03:34:07 +02:00
|
|
|
return cls(txo.ref, script)
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@property
|
2018-07-29 02:52:54 +02:00
|
|
|
def amount(self) -> int:
|
2018-05-25 08:03:25 +02:00
|
|
|
""" Amount this input adds to the transaction. """
|
2018-07-15 03:34:07 +02:00
|
|
|
if self.txo_ref.txo is None:
|
|
|
|
raise ValueError('Cannot resolve output to get amount.')
|
|
|
|
return self.txo_ref.txo.amount
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-09-26 00:02:50 +02:00
|
|
|
@property
|
2018-09-26 00:14:28 +02:00
|
|
|
def is_my_account(self) -> Optional[bool]:
|
2018-09-26 00:02:50 +02:00
|
|
|
""" True if the output this input spends is yours. """
|
|
|
|
if self.txo_ref.txo is None:
|
2018-10-03 13:08:02 +02:00
|
|
|
return False
|
2018-09-26 00:02:50 +02:00
|
|
|
return self.txo_ref.txo.is_my_account
|
|
|
|
|
2018-05-25 08:03:25 +02:00
|
|
|
@classmethod
|
|
|
|
def deserialize_from(cls, stream):
|
2018-10-11 03:39:36 +02:00
|
|
|
tx_ref = TXRefImmutable.from_hash(stream.read(32), -1)
|
2018-07-15 03:34:07 +02:00
|
|
|
position = stream.read_uint32()
|
2018-05-25 08:03:25 +02:00
|
|
|
script = stream.read_string()
|
|
|
|
sequence = stream.read_uint32()
|
|
|
|
return cls(
|
2018-07-15 03:34:07 +02:00
|
|
|
TXORef(tx_ref, position),
|
|
|
|
cls.script_class(script) if not tx_ref.is_null else script,
|
2018-05-25 08:03:25 +02:00
|
|
|
sequence
|
|
|
|
)
|
|
|
|
|
|
|
|
def serialize_to(self, stream, alternate_script=None):
|
2018-07-15 03:34:07 +02:00
|
|
|
stream.write(self.txo_ref.tx_ref.hash)
|
|
|
|
stream.write_uint32(self.txo_ref.position)
|
2018-05-25 08:03:25 +02:00
|
|
|
if alternate_script is not None:
|
|
|
|
stream.write_string(alternate_script)
|
|
|
|
else:
|
|
|
|
if self.is_coinbase:
|
|
|
|
stream.write_string(self.coinbase)
|
|
|
|
else:
|
|
|
|
stream.write_string(self.script.source)
|
|
|
|
stream.write_uint32(self.sequence)
|
|
|
|
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
class BaseOutputEffectiveAmountEstimator:
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
__slots__ = 'txo', 'txi', 'fee', 'effective_amount'
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, ledger: 'baseledger.BaseLedger', txo: 'BaseOutput') -> None:
|
2018-06-04 02:13:30 +02:00
|
|
|
self.txo = txo
|
2018-06-08 05:47:46 +02:00
|
|
|
self.txi = ledger.transaction_class.input_class.spend(txo)
|
2018-08-03 16:41:40 +02:00
|
|
|
self.fee: int = self.txi.get_fee(ledger)
|
2018-07-29 02:52:54 +02:00
|
|
|
self.effective_amount: int = txo.amount - self.fee
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
def __lt__(self, other):
|
|
|
|
return self.effective_amount < other.effective_amount
|
|
|
|
|
|
|
|
|
|
|
|
class BaseOutput(InputOutput):
|
|
|
|
|
2018-06-11 15:33:32 +02:00
|
|
|
script_class = BaseOutputScript
|
2018-06-08 05:47:46 +02:00
|
|
|
estimator_class = BaseOutputEffectiveAmountEstimator
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-09-26 00:02:50 +02:00
|
|
|
__slots__ = 'amount', 'script', 'is_change', 'is_my_account'
|
2018-07-15 03:34:07 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def __init__(self, amount: int, script: BaseOutputScript,
|
2018-09-26 00:02:50 +02:00
|
|
|
tx_ref: TXRef = None, position: int = None,
|
|
|
|
is_change: Optional[bool] = None, is_my_account: Optional[bool] = None
|
|
|
|
) -> None:
|
2018-07-29 02:52:54 +02:00
|
|
|
super().__init__(tx_ref, position)
|
2018-07-15 03:34:07 +02:00
|
|
|
self.amount = amount
|
|
|
|
self.script = script
|
2018-09-26 00:02:50 +02:00
|
|
|
self.is_change = is_change
|
|
|
|
self.is_my_account = is_my_account
|
2018-07-15 03:34:07 +02:00
|
|
|
|
2018-10-05 01:27:39 +02:00
|
|
|
def update_annotations(self, annotated):
|
|
|
|
if annotated is None:
|
|
|
|
self.is_change = False
|
|
|
|
self.is_my_account = False
|
|
|
|
else:
|
|
|
|
self.is_change = annotated.is_change
|
|
|
|
self.is_my_account = annotated.is_my_account
|
|
|
|
|
2018-07-15 03:34:07 +02:00
|
|
|
@property
|
|
|
|
def ref(self):
|
|
|
|
return TXORefResolvable(self)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def id(self):
|
|
|
|
return self.ref.id
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-08-06 06:15:19 +02:00
|
|
|
def get_address(self, ledger):
|
|
|
|
return ledger.hash160_to_address(
|
|
|
|
self.script.values['pubkey_hash']
|
|
|
|
)
|
|
|
|
|
2018-06-08 05:47:46 +02:00
|
|
|
def get_estimator(self, ledger):
|
|
|
|
return self.estimator_class(ledger, self)
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def pay_pubkey_hash(cls, amount, pubkey_hash):
|
|
|
|
return cls(amount, cls.script_class.pay_pubkey_hash(pubkey_hash))
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def deserialize_from(cls, stream):
|
|
|
|
return cls(
|
|
|
|
amount=stream.read_uint64(),
|
|
|
|
script=cls.script_class(stream.read_string())
|
|
|
|
)
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def serialize_to(self, stream, alternate_script=None):
|
2018-05-25 08:03:25 +02:00
|
|
|
stream.write_uint64(self.amount)
|
|
|
|
stream.write_string(self.script.source)
|
|
|
|
|
|
|
|
|
|
|
|
class BaseTransaction:
|
|
|
|
|
2018-06-11 15:33:32 +02:00
|
|
|
input_class = BaseInput
|
|
|
|
output_class = BaseOutput
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-10-03 13:08:02 +02:00
|
|
|
def __init__(self, raw=None, version: int = 1, locktime: int = 0, is_verified: bool = False,
|
2018-09-26 00:14:28 +02:00
|
|
|
height: int = -1, position: int = -1) -> None:
|
2018-05-25 08:03:25 +02:00
|
|
|
self._raw = raw
|
2018-07-15 03:34:07 +02:00
|
|
|
self.ref = TXRefMutable(self)
|
2018-09-26 00:02:50 +02:00
|
|
|
self.version = version
|
|
|
|
self.locktime = locktime
|
|
|
|
self._inputs: List[BaseInput] = []
|
|
|
|
self._outputs: List[BaseOutput] = []
|
2018-10-03 13:08:02 +02:00
|
|
|
self.is_verified = is_verified
|
2018-09-22 04:18:30 +02:00
|
|
|
self.height = height
|
2018-09-26 00:02:50 +02:00
|
|
|
self.position = position
|
2018-05-25 08:03:25 +02:00
|
|
|
if raw is not None:
|
|
|
|
self._deserialize()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def id(self):
|
2018-07-15 03:34:07 +02:00
|
|
|
return self.ref.id
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def hash(self):
|
2018-07-15 03:34:07 +02:00
|
|
|
return self.ref.hash
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def raw(self):
|
|
|
|
if self._raw is None:
|
|
|
|
self._raw = self._serialize()
|
|
|
|
return self._raw
|
|
|
|
|
|
|
|
def _reset(self):
|
|
|
|
self._raw = None
|
2018-07-15 03:34:07 +02:00
|
|
|
self.ref.reset()
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@property
|
2018-09-26 00:02:50 +02:00
|
|
|
def inputs(self) -> ReadOnlyList[BaseInput]:
|
2018-05-25 08:03:25 +02:00
|
|
|
return ReadOnlyList(self._inputs)
|
|
|
|
|
|
|
|
@property
|
2018-09-26 00:02:50 +02:00
|
|
|
def outputs(self) -> ReadOnlyList[BaseOutput]:
|
2018-05-25 08:03:25 +02:00
|
|
|
return ReadOnlyList(self._outputs)
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def _add(self, new_ios: Iterable[InputOutput], existing_ios: List) -> 'BaseTransaction':
|
2018-06-08 05:47:46 +02:00
|
|
|
for txio in new_ios:
|
2018-07-15 03:34:07 +02:00
|
|
|
txio.tx_ref = self.ref
|
|
|
|
txio.position = len(existing_ios)
|
2018-06-08 05:47:46 +02:00
|
|
|
existing_ios.append(txio)
|
2018-05-25 08:03:25 +02:00
|
|
|
self._reset()
|
|
|
|
return self
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def add_inputs(self, inputs: Iterable[BaseInput]) -> 'BaseTransaction':
|
2018-06-08 05:47:46 +02:00
|
|
|
return self._add(inputs, self._inputs)
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def add_outputs(self, outputs: Iterable[BaseOutput]) -> 'BaseTransaction':
|
2018-06-08 05:47:46 +02:00
|
|
|
return self._add(outputs, self._outputs)
|
2018-05-25 08:03:25 +02:00
|
|
|
|
|
|
|
@property
|
2018-07-29 02:52:54 +02:00
|
|
|
def size(self) -> int:
|
2018-05-25 08:03:25 +02:00
|
|
|
""" Size in bytes of the entire transaction. """
|
|
|
|
return len(self.raw)
|
|
|
|
|
|
|
|
@property
|
2018-07-29 02:52:54 +02:00
|
|
|
def base_size(self) -> int:
|
2018-08-03 16:41:40 +02:00
|
|
|
""" Size of transaction without inputs or outputs in bytes. """
|
|
|
|
return (
|
|
|
|
self.size
|
|
|
|
- sum(txi.size for txi in self._inputs)
|
|
|
|
- sum(txo.size for txo in self._outputs)
|
|
|
|
)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def input_sum(self):
|
2018-09-26 04:39:20 +02:00
|
|
|
return sum(i.amount for i in self.inputs if i.txo_ref.txo is not None)
|
2018-08-03 16:41:40 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def output_sum(self):
|
|
|
|
return sum(o.amount for o in self.outputs)
|
|
|
|
|
2018-08-03 18:29:02 +02:00
|
|
|
@property
|
2018-09-26 00:02:50 +02:00
|
|
|
def net_account_balance(self) -> int:
|
|
|
|
balance = 0
|
|
|
|
for txi in self.inputs:
|
2018-09-26 04:39:20 +02:00
|
|
|
if txi.txo_ref.txo is None:
|
|
|
|
continue
|
2018-09-26 00:02:50 +02:00
|
|
|
if txi.is_my_account is None:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot access net_account_balance if inputs/outputs do not "
|
|
|
|
"have is_my_account set properly."
|
|
|
|
)
|
|
|
|
elif txi.is_my_account:
|
|
|
|
balance -= txi.amount
|
|
|
|
for txo in self.outputs:
|
|
|
|
if txo.is_my_account is None:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot access net_account_balance if inputs/outputs do not "
|
|
|
|
"have is_my_account set properly."
|
|
|
|
)
|
|
|
|
elif txo.is_my_account:
|
|
|
|
balance += txo.amount
|
|
|
|
return balance
|
|
|
|
|
|
|
|
@property
|
|
|
|
def fee(self) -> int:
|
2018-08-03 18:29:02 +02:00
|
|
|
return self.input_sum - self.output_sum
|
|
|
|
|
2018-09-26 00:02:50 +02:00
|
|
|
def get_base_fee(self, ledger) -> int:
|
2018-08-03 16:41:40 +02:00
|
|
|
""" Fee for base tx excluding inputs and outputs. """
|
|
|
|
return self.base_size * ledger.fee_per_byte
|
|
|
|
|
2018-09-26 00:02:50 +02:00
|
|
|
def get_effective_input_sum(self, ledger) -> int:
|
2018-08-03 16:41:40 +02:00
|
|
|
""" Sum of input values *minus* the cost involved to spend them. """
|
|
|
|
return sum(txi.amount - txi.get_fee(ledger) for txi in self._inputs)
|
|
|
|
|
2018-09-26 00:02:50 +02:00
|
|
|
def get_total_output_sum(self, ledger) -> int:
|
2018-08-03 16:41:40 +02:00
|
|
|
""" Sum of output values *plus* the cost involved to spend them. """
|
|
|
|
return sum(txo.amount + txo.get_fee(ledger) for txo in self._outputs)
|
2018-05-25 08:03:25 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def _serialize(self, with_inputs: bool = True) -> bytes:
|
2018-05-25 08:03:25 +02:00
|
|
|
stream = BCDataStream()
|
|
|
|
stream.write_uint32(self.version)
|
|
|
|
if with_inputs:
|
|
|
|
stream.write_compact_size(len(self._inputs))
|
|
|
|
for txin in self._inputs:
|
|
|
|
txin.serialize_to(stream)
|
|
|
|
stream.write_compact_size(len(self._outputs))
|
|
|
|
for txout in self._outputs:
|
|
|
|
txout.serialize_to(stream)
|
|
|
|
stream.write_uint32(self.locktime)
|
|
|
|
return stream.get_bytes()
|
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
def _serialize_for_signature(self, signing_input: int) -> bytes:
|
2018-05-25 08:03:25 +02:00
|
|
|
stream = BCDataStream()
|
|
|
|
stream.write_uint32(self.version)
|
|
|
|
stream.write_compact_size(len(self._inputs))
|
|
|
|
for i, txin in enumerate(self._inputs):
|
|
|
|
if signing_input == i:
|
2018-07-29 02:52:54 +02:00
|
|
|
assert txin.txo_ref.txo is not None
|
2018-07-15 03:34:07 +02:00
|
|
|
txin.serialize_to(stream, txin.txo_ref.txo.script.source)
|
2018-05-25 08:03:25 +02:00
|
|
|
else:
|
|
|
|
txin.serialize_to(stream, b'')
|
|
|
|
stream.write_compact_size(len(self._outputs))
|
|
|
|
for txout in self._outputs:
|
|
|
|
txout.serialize_to(stream)
|
|
|
|
stream.write_uint32(self.locktime)
|
2018-06-14 02:57:57 +02:00
|
|
|
stream.write_uint32(self.signature_hash_type(1)) # signature hash type: SIGHASH_ALL
|
2018-05-25 08:03:25 +02:00
|
|
|
return stream.get_bytes()
|
|
|
|
|
|
|
|
def _deserialize(self):
|
|
|
|
if self._raw is not None:
|
|
|
|
stream = BCDataStream(self._raw)
|
|
|
|
self.version = stream.read_uint32()
|
|
|
|
input_count = stream.read_compact_size()
|
|
|
|
self.add_inputs([
|
|
|
|
self.input_class.deserialize_from(stream) for _ in range(input_count)
|
|
|
|
])
|
|
|
|
output_count = stream.read_compact_size()
|
|
|
|
self.add_outputs([
|
|
|
|
self.output_class.deserialize_from(stream) for _ in range(output_count)
|
|
|
|
])
|
|
|
|
self.locktime = stream.read_uint32()
|
|
|
|
|
2018-06-08 05:47:46 +02:00
|
|
|
@classmethod
|
2018-07-29 19:13:40 +02:00
|
|
|
def ensure_all_have_same_ledger(cls, funding_accounts: Iterable[BaseAccount],
|
|
|
|
change_account: BaseAccount = None) -> 'baseledger.BaseLedger':
|
2018-06-08 05:47:46 +02:00
|
|
|
ledger = None
|
|
|
|
for account in funding_accounts:
|
|
|
|
if ledger is None:
|
2018-06-11 15:33:32 +02:00
|
|
|
ledger = account.ledger
|
|
|
|
if ledger != account.ledger:
|
2018-06-08 05:47:46 +02:00
|
|
|
raise ValueError(
|
|
|
|
'All funding accounts used to create a transaction must be on the same ledger.'
|
|
|
|
)
|
2018-06-11 15:33:32 +02:00
|
|
|
if change_account is not None and change_account.ledger != ledger:
|
2018-06-08 05:47:46 +02:00
|
|
|
raise ValueError('Change account must use same ledger as funding accounts.')
|
2018-07-29 02:52:54 +02:00
|
|
|
if ledger is None:
|
|
|
|
raise ValueError('No ledger found.')
|
2018-06-08 05:47:46 +02:00
|
|
|
return ledger
|
|
|
|
|
|
|
|
@classmethod
|
2018-10-15 04:16:51 +02:00
|
|
|
async def create(cls, inputs: Iterable[BaseInput], outputs: Iterable[BaseOutput],
|
2018-10-15 06:04:25 +02:00
|
|
|
funding_accounts: Iterable[BaseAccount], change_account: BaseAccount):
|
2018-08-03 16:41:40 +02:00
|
|
|
""" Find optimal set of inputs when only outputs are provided; add change
|
|
|
|
outputs if only inputs are provided or if inputs are greater than outputs. """
|
|
|
|
|
|
|
|
tx = cls() \
|
|
|
|
.add_inputs(inputs) \
|
|
|
|
.add_outputs(outputs)
|
2018-06-08 05:47:46 +02:00
|
|
|
|
|
|
|
ledger = cls.ensure_all_have_same_ledger(funding_accounts, change_account)
|
|
|
|
|
2018-08-03 16:41:40 +02:00
|
|
|
# value of the outputs plus associated fees
|
|
|
|
cost = (
|
|
|
|
tx.get_base_fee(ledger) +
|
|
|
|
tx.get_total_output_sum(ledger)
|
|
|
|
)
|
|
|
|
# value of the inputs less the cost to spend those inputs
|
|
|
|
payment = tx.get_effective_input_sum(ledger)
|
2018-06-08 05:47:46 +02:00
|
|
|
|
2018-06-26 23:22:05 +02:00
|
|
|
try:
|
2018-08-03 16:41:40 +02:00
|
|
|
|
2018-11-07 01:27:48 +01:00
|
|
|
for _ in range(5):
|
2018-11-07 01:16:27 +01:00
|
|
|
|
|
|
|
if payment < cost:
|
|
|
|
deficit = cost - payment
|
|
|
|
spendables = await ledger.get_spendable_utxos(deficit, funding_accounts)
|
|
|
|
if not spendables:
|
|
|
|
raise ValueError('Not enough funds to cover this transaction.')
|
|
|
|
payment += sum(s.effective_amount for s in spendables)
|
|
|
|
tx.add_inputs(s.txi for s in spendables)
|
|
|
|
|
2018-08-03 16:41:40 +02:00
|
|
|
cost_of_change = (
|
|
|
|
tx.get_base_fee(ledger) +
|
|
|
|
cls.output_class.pay_pubkey_hash(COIN, NULL_HASH32).get_fee(ledger)
|
|
|
|
)
|
2018-11-07 01:16:27 +01:00
|
|
|
if payment > cost:
|
|
|
|
change = payment - cost
|
|
|
|
if change > cost_of_change:
|
|
|
|
change_address = await change_account.change.get_or_create_usable_address()
|
|
|
|
change_hash160 = change_account.ledger.address_to_hash160(change_address)
|
|
|
|
change_amount = change - cost_of_change
|
|
|
|
change_output = cls.output_class.pay_pubkey_hash(change_amount, change_hash160)
|
|
|
|
change_output.is_change = True
|
|
|
|
tx.add_outputs([cls.output_class.pay_pubkey_hash(change_amount, change_hash160)])
|
|
|
|
|
|
|
|
if tx._outputs:
|
|
|
|
break
|
|
|
|
else:
|
2018-11-07 01:27:48 +01:00
|
|
|
# this condition and the outer range(5) loop cover an edge case
|
2018-11-07 01:16:27 +01:00
|
|
|
# whereby a single input is just enough to cover the fee and
|
|
|
|
# has some change left over, but the change left over is less
|
|
|
|
# than the cost_of_change: thus the input is completely
|
|
|
|
# consumed and no output is added, which is an invalid tx.
|
|
|
|
# to be able to spend this input we must increase the cost
|
|
|
|
# of the TX and run through the balance algorithm a second time
|
|
|
|
# adding an extra input and change output, making tx valid.
|
2018-11-07 01:27:48 +01:00
|
|
|
# we do this 5 times in case the other UTXOs added are also
|
|
|
|
# less than the fee, after 5 attempts we give up and go home
|
|
|
|
cost += cost_of_change + 1
|
2018-08-03 16:41:40 +02:00
|
|
|
|
2018-10-15 04:16:51 +02:00
|
|
|
await tx.sign(funding_accounts)
|
2018-06-26 23:22:05 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
except Exception as e:
|
2018-10-18 03:20:17 +02:00
|
|
|
log.exception('Failed to create transaction:')
|
2018-10-15 04:16:51 +02:00
|
|
|
await ledger.release_outputs(tx.outputs)
|
2018-07-29 02:52:54 +02:00
|
|
|
raise e
|
2018-06-08 05:47:46 +02:00
|
|
|
|
2018-10-15 04:16:51 +02:00
|
|
|
return tx
|
2018-06-08 05:47:46 +02:00
|
|
|
|
2018-07-29 02:52:54 +02:00
|
|
|
@staticmethod
|
|
|
|
def signature_hash_type(hash_type):
|
2018-06-14 02:57:57 +02:00
|
|
|
return hash_type
|
|
|
|
|
2018-10-15 04:16:51 +02:00
|
|
|
async def sign(self, funding_accounts: Iterable[BaseAccount]):
|
2018-06-08 05:47:46 +02:00
|
|
|
ledger = self.ensure_all_have_same_ledger(funding_accounts)
|
2018-05-25 08:03:25 +02:00
|
|
|
for i, txi in enumerate(self._inputs):
|
2018-07-29 02:52:54 +02:00
|
|
|
assert txi.script is not None
|
|
|
|
assert txi.txo_ref.txo is not None
|
2018-07-15 03:34:07 +02:00
|
|
|
txo_script = txi.txo_ref.txo.script
|
2018-05-25 08:03:25 +02:00
|
|
|
if txo_script.is_pay_pubkey_hash:
|
2018-06-11 15:33:32 +02:00
|
|
|
address = ledger.hash160_to_address(txo_script.values['pubkey_hash'])
|
2018-10-15 04:16:51 +02:00
|
|
|
private_key = await ledger.get_private_key_for_address(address)
|
2018-05-25 08:03:25 +02:00
|
|
|
tx = self._serialize_for_signature(i)
|
2018-06-14 02:57:57 +02:00
|
|
|
txi.script.values['signature'] = \
|
2018-07-29 02:52:54 +02:00
|
|
|
private_key.sign(tx) + bytes((self.signature_hash_type(1),))
|
2018-05-25 08:03:25 +02:00
|
|
|
txi.script.values['pubkey'] = private_key.public_key.pubkey_bytes
|
|
|
|
txi.script.generate()
|
2018-06-08 05:47:46 +02:00
|
|
|
else:
|
|
|
|
raise NotImplementedError("Don't know how to spend this output.")
|
2018-05-25 08:03:25 +02:00
|
|
|
self._reset()
|