Skip to content

Commit

Permalink
Sourcery refactored master branch (#43)
Browse files Browse the repository at this point in the history
* 'Refactored by Sourcery'

Co-authored-by: Sourcery AI <>
Co-authored-by: Ferdinando Ametrano <ferdinando@ametrano.net>
  • Loading branch information
sourcery-ai[bot] and fametrano committed Aug 9, 2020
1 parent 794bb3b commit e56557b
Show file tree
Hide file tree
Showing 29 changed files with 69 additions and 136 deletions.
3 changes: 1 addition & 2 deletions btclib/bech32.py
Expand Up @@ -74,8 +74,7 @@ def _create_checksum(hrp: str, data: List[int]) -> List[int]:
"""Compute the checksum values given HRP and data."""
values = _hrp_expand(hrp) + data
polymod = _polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
checksum = [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
return checksum
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]


def b32encode(hrp: str, data: List[int]) -> bytes:
Expand Down
10 changes: 3 additions & 7 deletions btclib/bech32address.py
Expand Up @@ -89,12 +89,12 @@ def _check_witness(witvers: int, witprog: bytes):
err_msg = "invalid witness program length for witness version zero: "
err_msg += f"{length} instead of 20 or 32"
raise ValueError(err_msg)
elif witvers < 0 or 16 < witvers:
elif witvers < 0 or witvers > 16:
err_msg = "invalid witness version: "
err_msg += f"{witvers} not in 0..16"
raise ValueError(err_msg)
else:
if length < 2 or 40 < length:
if length < 2 or length > 40:
err_msg = "invalid witness program length for witness version zero: "
err_msg += f"{length}, not in 2..40"
raise ValueError(err_msg)
Expand Down Expand Up @@ -142,11 +142,7 @@ def witness_from_b32address(b32addr: String) -> Tuple[int, bytes, str, bool]:
witprog = _convertbits(data[1:], 5, 8, False)
_check_witness(witvers, bytes(witprog))

if witvers == 0 and len(witprog) == 20:
is_script_hash = False
else:
is_script_hash = True

is_script_hash = False if witvers == 0 and len(witprog) == 20 else True
return witvers, bytes(witprog), network, is_script_hash


Expand Down
15 changes: 4 additions & 11 deletions btclib/bip32.py
Expand Up @@ -217,11 +217,7 @@ def xpub_from_xprv(xprv: BIP32Key) -> bytes:
private key (“neutered” as it removes the ability to sign transactions).
"""

if isinstance(xprv, dict):
xkey_dict = copy.copy(xprv)
else:
xkey_dict = deserialize(xprv)

xkey_dict = copy.copy(xprv) if isinstance(xprv, dict) else deserialize(xprv)
if xkey_dict["key"][0] != 0:
raise ValueError(f"not a private key: {serialize(xkey_dict).decode()}")

Expand Down Expand Up @@ -407,12 +403,12 @@ def _derive_from_account(
more_than_two_branches: bool = False,
) -> BIP32KeyDict:

if more_than_two_branches and 0x80000000 <= branch:
if more_than_two_branches and branch >= 0x80000000:
raise ValueError("invalid private derivation at branch level")
elif branch not in (0, 1):
raise ValueError(f"invalid branch: {branch} not in (0, 1)")

if 0x80000000 <= address_index:
if address_index >= 0x80000000:
raise ValueError("invalid private derivation at address index level")

if d["index"][0] < 0x80:
Expand Down Expand Up @@ -445,10 +441,7 @@ def crack_prvkey(parent_xpub: BIP32Key, child_xprv: BIP32Key) -> bytes:
m += f"{serialize(p).decode()}"
raise ValueError(m)

if isinstance(child_xprv, dict):
c = child_xprv
else:
c = deserialize(child_xprv)
c = child_xprv if isinstance(child_xprv, dict) else deserialize(child_xprv)
if c["key"][0] != 0:
m = f"extended child key is not a private key: {serialize(c).decode()}"
raise ValueError(m)
Expand Down
9 changes: 3 additions & 6 deletions btclib/blocks.py
Expand Up @@ -90,7 +90,7 @@ def deserialize(cls: Type[_Block], data: BinaryData) -> _Block:
transactions: List[tx.Tx] = []
coinbase = tx.Tx.deserialize(stream)
transactions.append(coinbase)
for x in range(transaction_count - 1):
for _ in range(transaction_count - 1):
transaction = tx.Tx.deserialize(stream)
transactions.append(transaction)
block = cls(header=header, transactions=transactions)
Expand All @@ -110,15 +110,12 @@ def size(self) -> int:

@property
def weight(self) -> int:
weight = 0
for t in self.transactions:
weight += t.weight
return weight
return sum(t.weight for t in self.transactions)

def assert_valid(self) -> None:
for transaction in self.transactions[1:]:
transaction.assert_valid()
if not _generate_merkle_root(self.transactions) == self.header.merkleroot:
if _generate_merkle_root(self.transactions) != self.header.merkleroot:
raise ValueError(
"The block merkle root is not the merkle root of the block transactions"
)
Expand Down
2 changes: 1 addition & 1 deletion btclib/bms.py
Expand Up @@ -314,7 +314,7 @@ def assert_as_valid(msg: String, addr: String, sig: BMSig) -> None:
err_msg = f"invalid recovery flag: {rf} (base58 address {addr!r})"
raise ValueError(err_msg)
else:
if rf > 38 or (30 < rf and rf < 35): # P2WPKH
if rf > 38 or rf > 30 and rf < 35: # P2WPKH
if hash160(pubkey) != h160:
raise ValueError(f"wrong p2wpkh address: {addr!r}")
else:
Expand Down
12 changes: 3 additions & 9 deletions btclib/curve.py
Expand Up @@ -107,11 +107,7 @@ def __str__(self) -> str:

def __repr__(self) -> str:
result = "Curve("
if self.p > _HEXTHRESHOLD:
result += f"'{hex_string(self.p)}'"
else:
result += f"{self.p}"

result += f"'{hex_string(self.p)}'" if self.p > _HEXTHRESHOLD else f"{self.p}"
if self._a > _HEXTHRESHOLD or self._b > _HEXTHRESHOLD:
result += f", '{hex_string(self._a)}', '{hex_string(self._b)}'"
else:
Expand Down Expand Up @@ -173,9 +169,7 @@ def _jac_equality(self, QJ: JacPoint, PJ: JacPoint) -> bool:
return False
PJ3 = PJ2 * PJ[2]
QJ3 = QJ2 * QJ[2]
if QJ[1] * PJ3 % self.p != PJ[1] * QJ3 % self.p:
return False
return True
return QJ[1] * PJ3 % self.p == PJ[1] * QJ3 % self.p

# methods using _a, _b, _p

Expand Down Expand Up @@ -254,7 +248,7 @@ def _y2(self, x: int) -> int:
# skipping a crucial check here:
# if sqrt(y*y) does not exist, then x is not valid.
# This is a good reason to keep this method private
return ((x * x + self._a) * x + self._b) % self.p
return ((x**2 + self._a) * x + self._b) % self.p

def y(self, x: int) -> int:
"""Return the y coordinate from x, as in (x, y)."""
Expand Down
4 changes: 2 additions & 2 deletions btclib/curvegroupf.py
Expand Up @@ -26,7 +26,7 @@ def find_all_points(ec: CurveGroup) -> List[Point]:
Very unsofisticated walk-through approach,
for didactical sake only.
"""
if 10000 < ec.p:
if ec.p > 10000:
m = f"p is too big to count all group points: {ec.p}"
raise ValueError(m)

Expand All @@ -50,7 +50,7 @@ def find_subgroup_points(ec: CurveGroup, G: Point) -> List[Point]:
Very unsofisticated walk-through approach,
for didactical sake only.
"""
if 10000 < ec.p:
if ec.p > 10000:
m = f"p is too big to count all subgroup points: {ec.p}"
raise ValueError(m)

Expand Down
2 changes: 1 addition & 1 deletion btclib/curvemult.py
Expand Up @@ -96,7 +96,7 @@ def _multi_mult(
continue
x.append((-n, PJ))

if len(x) == 0:
if not x:
return INFJ

heapq.heapify(x)
Expand Down
3 changes: 1 addition & 2 deletions btclib/electrum.py
Expand Up @@ -111,8 +111,7 @@ def entropy_from_mnemonic(mnemonic: Mnemonic, lang: str = "en") -> BinStr:

indexes = _indexes_from_mnemonic(mnemonic, lang)
base = _wordlists.language_length(lang)
entropy = _entropy_from_indexes(indexes, base)
return entropy
return _entropy_from_indexes(indexes, base)


def _seed_from_mnemonic(mnemonic: Mnemonic, passphrase: str) -> Tuple[str, bytes]:
Expand Down
2 changes: 1 addition & 1 deletion btclib/entropy.py
Expand Up @@ -242,7 +242,7 @@ def collect_rolls(bits: int) -> Tuple[int, List[int]]:
msg += "; prefix with 'a' to automate rolls, hit enter for 'a6'): "
dice_sides_str = input(msg)
dice_sides_str = dice_sides_str.lower()
if dice_sides_str == "" or dice_sides_str == "a":
if dice_sides_str in ["", "a"]:
automate = True
dice_sides = 6
else:
Expand Down
3 changes: 1 addition & 2 deletions btclib/mnemonic.py
Expand Up @@ -128,5 +128,4 @@ def _indexes_from_mnemonic(mnemonic: Mnemonic, lang: str) -> List[int]:

words = mnemonic.split()
wordlist = _wordlists.wordlist(lang)
indexes = [wordlist.index(w) for w in words]
return indexes
return [wordlist.index(w) for w in words]
6 changes: 2 additions & 4 deletions btclib/network.py
Expand Up @@ -120,26 +120,24 @@ def network_from_key_value(key: str, prefix: Union[str, bytes, Curve]) -> str:

def xpubversions_from_network(network: str) -> List[bytes]:
network = network.lower()
result = [
return [
NETWORKS[network]["bip32_pub"],
NETWORKS[network]["slip132_p2wsh_p2sh_pub"],
NETWORKS[network]["slip132_p2wpkh_p2sh_pub"],
NETWORKS[network]["slip132_p2wpkh_pub"],
NETWORKS[network]["slip132_p2wsh_pub"],
]
return result


def xprvversions_from_network(network: str) -> List[bytes]:
network = network.lower()
result = [
return [
NETWORKS[network]["bip32_prv"],
NETWORKS[network]["slip132_p2wsh_p2sh_prv"],
NETWORKS[network]["slip132_p2wpkh_p2sh_prv"],
NETWORKS[network]["slip132_p2wpkh_prv"],
NETWORKS[network]["slip132_p2wsh_prv"],
]
return result


_XPRV_VERSIONS_ALL = (
Expand Down
24 changes: 8 additions & 16 deletions btclib/psbt.py
Expand Up @@ -34,10 +34,7 @@ def decode_der_path(path: bytes) -> str:
for x in range(len(path) // 4):
out += "/"
index = int.from_bytes(path[4 * x : 4 * (x + 1)], "little")
if index >= 0x80000000:
out += str(index - 0x80000000) + "h"
else:
out += str(index)
out += str(index - 0x80000000) + "h" if index >= 0x80000000 else str(index)
return out


Expand Down Expand Up @@ -122,7 +119,6 @@ def decode(cls: Type[_PsbtInput], input_map: Dict[bytes, bytes]) -> _PsbtInput:
elif key[0] == 0x08:
assert len(key) == 1
final_script_witness = witness_deserialize(value)
pass
elif key[0] == 0x09:
assert len(key) == 1
por_commitment = value.hex() # TODO: bip127
Expand Down Expand Up @@ -348,7 +344,7 @@ def deserialize(cls: Type[_PSbt], string: str) -> _PSbt:
output_len = len(tx.vout)

inputs = []
for i in range(input_len):
for _ in range(input_len):
input_map, data = deserialize_map(data)
inputs.append(PsbtInput.decode(input_map))

Expand Down Expand Up @@ -488,16 +484,12 @@ def _combine_field(
) -> None:
item: Union[Union[int, Tx, TxOut], Dict[str, str]] = getattr(psbt_map, key)
a: Union[Union[int, Tx, TxOut], Dict[str, str]] = getattr(out, key)
if isinstance(item, dict):
if a and isinstance(a, dict):
a.update(item)
else:
setattr(out, key, item)
if isinstance(item, dict) and a and isinstance(a, dict):
a.update(item)
elif isinstance(item, dict) or item and not a:
setattr(out, key, item)
elif item:
if a:
assert item == a, key
else:
setattr(out, key, item)
assert item == a, key


def combine_psbts(psbts: List[Psbt]) -> Psbt:
Expand All @@ -522,7 +514,7 @@ def combine_psbts(psbts: List[Psbt]) -> Psbt:
_combine_field(psbt.inputs[x], final_psbt.inputs[x], "proprietary")
_combine_field(psbt.inputs[x], final_psbt.inputs[x], "unknown")

for y in range(len(final_psbt.outputs)):
for _ in final_psbt.outputs:
_combine_field(psbt.outputs[x], final_psbt.outputs[x], "redeem_script")
_combine_field(psbt.outputs[x], final_psbt.outputs[x], "witness_script")
_combine_field(psbt.outputs[x], final_psbt.outputs[x], "hd_keypaths")
Expand Down
18 changes: 3 additions & 15 deletions btclib/scriptpubkey.py
Expand Up @@ -109,11 +109,7 @@ def scriptPubKey_from_payload(


def payload_from_nulldata_scriptPubKey(script: Script) -> Tuple[str, Payloads, int]:
if isinstance(script, list):
s = encode(script)
else:
s = bytes_from_octets(script)

s = encode(script) if isinstance(script, list) else bytes_from_octets(script)
length = len(s)

# nulldata [OP_RETURN, data]
Expand Down Expand Up @@ -142,11 +138,7 @@ def payload_from_nulldata_scriptPubKey(script: Script) -> Tuple[str, Payloads, i


def payload_from_pms_scriptPubKey(script: Script) -> Tuple[str, Payloads, int]:
if isinstance(script, list):
s = encode(script)
else:
s = bytes_from_octets(script)

s = encode(script) if isinstance(script, list) else bytes_from_octets(script)
# p2ms [m, pubkeys, n, OP_CHECKMULTISIG]
script = decode(s)
m = int(script[0])
Expand All @@ -171,11 +163,7 @@ def payload_from_pms_scriptPubKey(script: Script) -> Tuple[str, Payloads, int]:
def payload_from_scriptPubKey(script: Script) -> Tuple[str, Payloads, int]:
"Return (scriptPubKey type, payload, m) from the input script."

if isinstance(script, list):
s = encode(script)
else:
s = bytes_from_octets(script)

s = encode(script) if isinstance(script, list) else bytes_from_octets(script)
length = len(s)

# p2pk [pubkey, OP_CHECKSIG]
Expand Down
9 changes: 2 additions & 7 deletions btclib/scriptpubkey_address.py
Expand Up @@ -27,11 +27,7 @@ def has_segwit_prefix(addr: String) -> bool:
else:
str_addr = addr.decode("ascii")

for net in NETWORKS:
if str_addr.startswith(NETWORKS[net]["p2w"] + "1"):
return True

return False
return any(str_addr.startswith(NETWORKS[net]["p2w"] + "1") for net in NETWORKS)


def scriptPubKey_from_address(addr: String) -> Tuple[bytes, str]:
Expand Down Expand Up @@ -78,8 +74,7 @@ def address_from_scriptPubKey(s: Script, network: str = "mainnet") -> bytes:

def tx_out_from_address(address: str, value: int) -> TxOut:
scriptPubKey = scriptPubKey_from_address(address)[0]
tx_out = TxOut(value, decode(scriptPubKey))
return tx_out
return TxOut(value, decode(scriptPubKey))


def address_from_tx_out(tx_out: TxOut) -> str:
Expand Down
9 changes: 3 additions & 6 deletions btclib/sighash.py
Expand Up @@ -44,7 +44,7 @@ def SegwitV0SignatureHash(
else:
hashSequence = b"\x00" * 32

if not hashtype_hex[1] == "2" and not hashtype_hex[1] == "3":
if hashtype_hex[1] != "2" and hashtype_hex[1] != "3":
hashOutputs = b""
for vout in transaction.vout:
hashOutputs += vout.serialize()
Expand All @@ -70,8 +70,7 @@ def SegwitV0SignatureHash(
preimage += transaction.nLockTime.to_bytes(4, "little")
preimage += bytes.fromhex(hashtype_hex)

sig_hash = hash256(preimage)
return sig_hash
return hash256(preimage)


# FIXME: remove OP_CODESEPARATOR only if executed
Expand Down Expand Up @@ -119,11 +118,9 @@ def get_sighash(
scriptCode = _get_witness_v0_scriptCodes(
script.decode(transaction.vin[input_index].txinwitness[-1])
)[0]
sighash = SegwitV0SignatureHash(
return SegwitV0SignatureHash(
bytes.fromhex(scriptCode), transaction, input_index, sighash_type, value
)

return sighash
raise RuntimeError("Legacy transactions not supported yet")


Expand Down
6 changes: 1 addition & 5 deletions btclib/signtocontract.py
Expand Up @@ -76,11 +76,7 @@ def ecdsa_commit_sign(
) -> Tuple[Tuple[int, int], Receipt]:
"""Include a commitment c inside an ECDSA signature."""

if k is None:
k = _rfc6979(m, prvkey, ec, hf)
else:
k = int_from_prvkey(k, ec)

k = _rfc6979(m, prvkey, ec, hf) if k is None else int_from_prvkey(k, ec)
# commit
R, new_k = _tweak(c, k, ec, hf)
# sign
Expand Down

0 comments on commit e56557b

Please sign in to comment.