Skip to content

Commit

Permalink
new method to estimate vSize of unsigned transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
eric-volz committed Oct 6, 2023
1 parent 756a542 commit 8feea32
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
2 changes: 1 addition & 1 deletion defichain/transactions/rawtransactions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
from .witness import WitnessHash, Witness

# Fee
from .fee import estimate_fee
from .fee import estimate_size, estimate_fee, estimate_vsize
43 changes: 36 additions & 7 deletions defichain/transactions/rawtransactions/fee.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,56 @@
import math

from defichain.transactions.constants import TxSize
from .txinput import TxP2PKHInput, TxP2SHInput, TxP2WPKHInput
from .tx import Transaction


def estimate_fee(tx: Transaction, feePerByte: float):
def estimate_size(tx: Transaction):
"""
Signes the transaction to find out the real size
Estimates the size of the later signed transaction.
:param tx: (required) the transaction object
:param tx: (required) the unsigned transaction object
:type tx: Transaction
:param feePerByte: (required) the amount of fee to pay per byte
:type feePerByte: float
:return: "int" - the amount of fee to pay
:return: "int" - size of the signed transaction
"""
# Current Size
size = tx.size()

# Add witniss and signature size
# Add witness and signature size
for input in tx.get_inputs():
if isinstance(input, TxP2SHInput) or isinstance(input, TxP2WPKHInput):
size += TxSize.WITNESS_SIGNATURE_LENGTH + TxSize.WITNESS_SIGNATURE + \
TxSize.PUBLIC_KEY_LENGTH + TxSize.PUBLIC_KEY
elif isinstance(input, TxP2PKHInput):
size += TxSize.SCRIPTSIG_SIGNATURE
return size


def estimate_fee(tx: Transaction, feePerByte: float):
"""
Estimates fees for unsigned transaction
:param tx: (required) the unsigned transaction object
:type tx: Transaction
:param feePerByte: (required) the amount of fee to pay per byte
:type feePerByte: float
:return: "int" - the amount of fee to pay
"""

size = estimate_size(tx)

return round(size * feePerByte)


def estimate_vsize(tx: Transaction):
"""
Estimates the vSize of the later signed transaction.
:param tx: (required) the unsigned transaction object
:type tx: Transaction
:return: "int" - vSize of the signed transaction
"""
unsigned_size = tx.size()
signed_size = estimate_size(tx)

return math.ceil(unsigned_size + (signed_size - unsigned_size) / 4)

0 comments on commit 8feea32

Please sign in to comment.