def __init__(self, txo, mainnet): self.n = -1 self.value = -1 self.address = '' self.tx_idx = -1 self.isMainNet = mainnet if self.isMainNet == True: setup('mainnet') else: setup('testnet') if txo is not None: if 'vout' in txo: self.n = txo['vout'] elif 'n' in txo: self.n = txo['n'] if 'value_int' in txo: self.value = txo['value_int'] # Gets the address or the scriptpubkey (if an address isn't associated to the txo) if 'addresses' in txo: addresses = txo['addresses'] if len(addresses) > 0: self.address = addresses[0] elif 'type' in txo: if txo['type'] == 'witness_v0_keyhash': if 'script_pub_key' in txo: script_pub_key = txo['script_pub_key'] hex = script_pub_key['hex'] if self.isMainNet == True: self.address = boltzmann.utils.segwit_addr.encode( 'bc', 0, bytes.fromhex(hex[4:])) else: self.address = boltzmann.utils.segwit_addr.encode( 'tb', 0, bytes.fromhex(hex[4:])) elif 'witness' in txo: witness = txo['witness'] if len(witness) >= 1: pubkey_hex = witness[1] pubkey = PublicKey.unhexlify(pubkey_hex) segwit_address = P2wpkhAddress(pubkey.hash(), version=0) self.address = str(segwit_address) else: self.address = txo['type'] else: self.address = txo['type'] elif 'script_sig' in txo: script_sig = txo['script_sig'] self.address = script_sig['hex'] elif 'script_pub_key' in txo: script_pub_key = txo['script_pub_key'] self.address = script_pub_key['hex'] else: raise ValueError("Could not assign address to txo") self.tx_idx = None
def __init__(self, network="testnet", version=2): # Bitcoin transaction self.transaction = None # Signed raw, type and fee self._signed_raw, self._type, self._fee = None, None, 0 # Bitcoin setup network if network not in ["mainnet", "testnet"]: raise ValueError("invalid network, please choose only mainnet or testnet networks") self.network, self.version = network, version setup(self.network, strict=True)
def __init__(self, network: str = config["network"], version: int = config["version"]): if not is_network(network=network): raise NetworkError(f"Invalid Bitcoin '{network}' network", "choose only 'mainnet' or 'testnet' networks.") self._network: str = network self._mainnet: bool = True if network == "mainnet" else False self._version: int = version self._transaction: Optional[MutableTransaction] = None self._type: Optional[str] = None self._signed_raw: Optional[str] = None self._fee: int = 0 setup(network, strict=True, force=True)
def __init__(self, version=2, network="testnet"): # Transaction build version self.version, self.transaction = version, None # Bitcoin network self.mainnet, self.network = None, network if self.network == "mainnet": self.mainnet = True elif self.network == "testnet": self.mainnet = False else: raise ValueError("invalid network, please choose only mainnet or testnet") # Bitcoin fee and type self._fee, self._type = 0, None # Setting network setup(network, strict=True)
def __init__(self, version=2, network="testnet"): # Transaction build version self.version = version # Transaction self.transaction = None # Bitcoin network self.mainnet = None self.network = network if self.network == "mainnet": self.mainnet = True elif self.network == "testnet": self.mainnet = False else: raise ValueError("invalid network, only mainnet or testnet") # Bitcoin fee self.fee = int() # Setting testnet setup(network, strict=True)
def __init__(self, network: str, privkey: bytearray = None, from_string: str = None, from_wif: str = None) -> None: ''' High level helper class for handling public key cryptography. : privkey - privatekey bytes : from_wif - <WIF> import private key from your wallet in WIF format : from_bytes - import private key in binary format : network - specify network [ppc, tppc, btc] : from_string - specify seed (string) to make the privkey from ''' self.network = network try: if self.network.startswith('t') or self.network.endswith( '-testnet'): setup('testnet') else: setup('mainnet') except ValueError: pass if privkey is not None: self._private_key = PrivateKey(privkey) if from_string is not None: self._private_key = PrivateKey( sha256(from_string.encode()).digest()) if from_wif is not None: self._private_key = PrivateKey.from_wif(from_wif) if not privkey: if from_string == from_wif is None: # generate a new privkey self._private_key = PrivateKey(bytearray(urandom(32))) self.privkey = str(self._private_key) self._public_key = PublicKey.from_priv(self._private_key) self.pubkey = str(self._public_key)
# LICENSE.md file. import sys import copy import unittest from functools import partial from argparse import ArgumentParser from .regtest import Manager from btcpy.structs.hd import ExtendedPrivateKey, ExtendedPublicKey from btcpy.structs.transaction import Transaction, Sequence, TxOut, Locktime, TxIn, MutableTransaction, MutableTxIn from btcpy.structs.sig import * from btcpy.structs.script import * from btcpy.setup import setup setup('regtest') keys = [('tpubDHVQPtNuLdRLj7FU348D5PcrkkPj5ibhN52cfjthEH9KTfwTaVmo' 'dTn1Ekpge6PhUjW1noZ452xesirHgBKbzmY6hz4eoVXDwHcjczDT7zb', 'tprv8koNFULfCFjfqeDg9QTcfyxkBisnvPQnnmRqPDrPp1LvdBggx6xD' 'SyA94cjpAXS7ccGhsQ7w6q7Y9Ku31e1eTDztU49LVBz9B1sCDoeE6Jc'), ('tpubDEhdzhXujo86G6PXroPKQJSCJi8qbdQvrALhTNiExsGKfFHXtVbT' 'E9tnLBCAP7nqQrqfUSVTCDuqv6RMHu8PDL5a8G43b5N2zKsF89nmLd6', 'tprv8i1brHVfbRSRNdMjy9iiztn5jgcuSJE2GrjvArfwYbTvpm2mG6ms' '3fGvA5kdZ3qZ7KB26VehAudSCUURKT56Hej2pBgj26ZkNbdD1YMdTiD'), ('tpubDDqNYkcvEKbQJKtda5miuWCBWqX2Bd8qJWgSNbsiqfSHRzNpsjpX' 'HAMiNYNHZw9FCnkuJpVAJjZkTeujhT4h293w6YMexGyAgNGRYWVtJ1D', 'tprv8h9LQLag5wujQrrqgS78W6Y4wp162HwvjD5f65qRRPdtbW84FLzw' '6fjrCNeqEvsKqiDxLtzJ9oHUGVTL17KptjbDVqgJ2XvAs2LcvSWrTUh'), ('tpubDATAg7GX3FHknHSDzfVEgwo8U1aEWPNdkgRjs4dBF244x9xC6tRq' 'UkM8ZMk8JNHnmQMqNG1evQBNKwt97G348FXaWjhT88UWbwqrBTpmwe3',
import requests from btcpy.setup import setup from btcpy.structs.hd import ExtendedPublicKey from btcpy.structs.address import P2shAddress, P2wpkhAddress from .. import Account setup('mainnet') # TO DO: # Separate addresses into different balances (name each, e.g. 'change0, spend1') # Alternatives for address='nested' class btc_xpub(Account): def __init__(self, **kwargs): super().__init__(**kwargs) self.xpub = ExtendedPublicKey.decode(self.address) def load_balance(self): bal = 0 for change in [0, 1]: used = True i = 0 while True: pk = derive_key(self.xpub, change, index=i) i += 1 url = 'https://api.blockcypher.com/v1/btc/main/addrs/' + pk + '/balance' data = requests.get(url, timeout=10).json() b = float(data['balance']) / 100000000 bal += b
from btcpy.setup import setup from btcpy.structs.address import P2pkhAddress from btcpy.structs.crypto import PublicKey, PrivateKey from btcpy.structs.script import Hashlock256Script from btcpy.structs.sig import * from btcpy.structs.transaction import TransactionFactory, HeightBasedSequence, TimeBasedSequence from btcpy.structs.transaction import TxIn, Sequence, TxOut, Locktime, MutableTransaction from utils import * import hashlib import datetime # global setup('testnet', strict=True) coin_symbol = 'btc-testnet' api_key = 'fe4a832ab7d14936b5731aa79cfa58ae' # committer pubk_hex = '0380557a219119218f7830bf3cdb2bb3c8220cac15db97e255498fb992e68c04a9' pubk = PublicKey.unhexlify(pubk_hex) address = P2pkhAddress(pubk.hash()) privk_hex = '385acd25450e50ecd5ad0fffec7b871c8f75eb3ba9ecded8d35a0765f4763d7e' privk = PrivateKey.unhexlify(privk_hex) # recipient pubk_hex2 = '03fb2cd4d0b5248c5f62296e55ce59eab79d68b90fc1d9865bafbcaa556e1c766c' pubk2 = PublicKey.unhexlify(pubk_hex2) # a sample of secret secret = 'I have an apple'.encode() secret_hash = hashlib.sha256(hashlib.sha256(secret).digest()).digest()
import random from bit.network import NetworkAPI from btcpy.setup import setup from btcpy.structs.crypto import PublicKey from btcpy.structs.transaction import Transaction from flask import Flask, jsonify, request, abort from app import app import model ADDRESS = "mvmSpLUxCXkMGj3CTAsudaB148YypZodDm" setup('testnet') @app.route('/health-check') def health_check(): return "OK" @app.route('/current-order') def current_order(): order = model.create_order(int(random.uniform(0.01, 1.1) * 10**4)) return jsonify(id=order.id, amount=order.amount, state=order.state, destination=ADDRESS) @app.route('/orders/<order_id>/pay', methods=['POST'])