Example #1
0
def sweep(ctx):
    """
Sweep your machine wallet to your primary wallet.

\b
Sweep your machine wallet to your primary wallet.
$ 21 sell sweep
"""

    manager = ctx.obj['manager']

    logger.info(click.style("Sweeping all service balances.", fg=cli_helpers.TITLE_COLOR))

    provider = TwentyOneProvider()
    try:
        wallet = Two1Wallet.import_from_mnemonic(provider, manager.get_services_mnemonic())
    except Exception:
        logger.info(click.style("Error: unable to import wallet mnemonic.  Please check to make "
                                "sure the mnemonic exists in %s "
                                "or contact [email protected]." % Two1Composer.COMPOSE_FILE,
                                fg="magenta"))

    utxos = wallet.get_utxos(include_unconfirmed=True, accounts=wallet._accounts)
    utxo_sum = wallet._sum_utxos(utxos)

    fee_amounts = txn_fees.get_fees()
    total_value, num_utxos = utxo_sum

    def fee_calc_small(num_utxos, total_value, fee_amounts):
        maybe_fee = _fee_calc(num_utxos, total_value, fee_amounts)
        return int(min([total_value / 2, maybe_fee]))

    fee = fee_calc_small(num_utxos, total_value, fee_amounts)

    if click.confirm(click.style("Sweeping %s satoshis to your primary wallet. This will incur a "
                                 "fee of approximately %d satoshis.\n"
                                 "Would you like to continue?" % (total_value, fee),
                                 fg=cli_helpers.PROMPT_COLOR)):
        master = Two1Wallet(manager.composer.wallet_file, provider)
        try:
            wallet.sweep(master.current_address, fee_calculator=fee_calc_small)
        except WalletBalanceError:
            cli_helpers.print_str("Sweep", ["Wallet balance (%d satoshis) is less than the dust "
                                            "limit. Not Sweeping." % total_value], "FAILED", False)
        except DustLimitError:
            cli_helpers.print_str("Sweep", ["Wallet balance (%d satoshis) would be below the "
                                            "dust limit when fees are deducted. "
                                            "Aborting sweep." % total_value], "FAILED", False)
        else:
            cli_helpers.print_str("Sweep", ["Swept %d satoshis, excluding %d satoshis of "
                                            "fees" % (total_value - fee, fee)], "SUCCESS", True)
    else:
        sys.exit()
def get_balances(services, client):
    """ Gets wallet balances of given services.
    """
    buffer_balance = get_buffer_balance(client)
    with open(Two1Composer.COMPOSE_FILE, "r") as f:
        services_info = yaml.load(f)

    balances = {}
    for service in services:
        template = {
            "buffer": buffer_balance,
            "wallet": None,
            "channels": None,
        }
        try:
            service_mnemonic = services_info.get('services').get(service).get(
                'environment').get('TWO1_WALLET_MNEMONIC')

            service_wallet = Two1Wallet.import_from_mnemonic(mnemonic=service_mnemonic)
            template["wallet"] = service_wallet.balances["total"]

            channel_client = channels.PaymentChannelClient(service_wallet)
            channel_client.sync()
            channel_urls = channel_client.list()
            channels_balance = sum(s.balance for s in (channel_client.status(url) for url in channel_urls)
                                   if s.state == channels.PaymentChannelState.READY)
            template["channels"] = channels_balance
        except AttributeError:
            template["wallet"] = 0
            template["channels"] = 0

        balances[service] = template
    return balances
Example #3
0
def get_balances(services, client):
    """ Gets wallet balances of given services.
    """
    buffer_balance = get_buffer_balance(client)
    with open(Two1Composer.SERVICES_WALLET_FILE, "r") as f:
        services_info = json.load(f)

    provider = TwentyOneProvider()
    balances = {}
    for service in services:
        template = {"buffer": None,
                    "wallet": None,
                    "channels": None}
        template["buffer"] = buffer_balance
        try:
            service_mnemonic = services_info.get(service).get("mnemonic")

            wallet = Two1Wallet.import_from_mnemonic(provider, service_mnemonic)
            template["wallet"] = wallet.balances["total"]

            channel_client = channels.PaymentChannelClient(wallet)
            channel_client.sync()
            channel_urls = channel_client.list()
            channels_balance = sum(s.balance for s in (channel_client.status(url) for url in channel_urls) if s.state == channels.PaymentChannelState.READY)
            template["channels"] = channels_balance
        except AttributeError:
            template["wallet"] = 0
            template["channels"] = 0

        balances[service] = template
    return balances
Example #4
0
def get_balances(services, client):
    """ Gets wallet balances of given services.
    """
    buffer_balance = get_buffer_balance(client)
    with open(Two1Composer.COMPOSE_FILE, "r") as f:
        services_info = yaml.load(f)

    balances = {}
    for service in services:
        template = {
            "buffer": buffer_balance,
            "wallet": None,
            "channels": None,
        }
        try:
            service_mnemonic = services_info.get('services').get(service).get(
                'environment').get('TWO1_WALLET_MNEMONIC')

            service_wallet = Two1Wallet.import_from_mnemonic(mnemonic=service_mnemonic)
            template["wallet"] = service_wallet.balances["total"]

            channel_client = channels.PaymentChannelClient(service_wallet)
            channel_client.sync()
            channel_urls = channel_client.list()
            channels_balance = sum(s.balance for s in (channel_client.status(url) for url in channel_urls)
                                   if s.state == channels.PaymentChannelState.READY)
            template["channels"] = channels_balance
        except AttributeError:
            template["wallet"] = 0
            template["channels"] = 0

        balances[service] = template
    return balances
Example #5
0
def sweep(ctx):
    """
Sweep your machine wallet to your primary wallet.

\b
Sweep your machine wallet to your primary wallet.
$ 21 sell sweep
"""

    manager = ctx.obj['manager']

    logger.info(click.style("Sweeping all service balances.", fg=cli_helpers.TITLE_COLOR))

    provider = TwentyOneProvider()
    try:
        wallet = Two1Wallet.import_from_mnemonic(provider, manager.get_services_mnemonic())
    except Exception:
        logger.info(click.style("Error: unable to import wallet mnemonic.  Please check to make "
                                "sure the mnemonic exists in %s "
                                "or contact [email protected]." % Two1Composer.COMPOSE_FILE,
                                fg="magenta"))

    utxos = wallet.get_utxos(include_unconfirmed=True, accounts=wallet._accounts)
    utxo_sum = wallet._sum_utxos(utxos)

    fee_amounts = txn_fees.get_fees()
    total_value, num_utxos = utxo_sum

    def fee_calc_small(num_utxos, total_value, fee_amounts):
        maybe_fee = _fee_calc(num_utxos, total_value, fee_amounts)
        return int(min([total_value / 2, maybe_fee]))

    fee = fee_calc_small(num_utxos, total_value, fee_amounts)

    if click.confirm(click.style("Sweeping %s satoshis to your primary wallet. This will incur a "
                                 "fee of approximately %d satoshis.\n"
                                 "Would you like to continue?" % (total_value, fee),
                                 fg=cli_helpers.PROMPT_COLOR)):
        master = Two1Wallet(manager.composer.wallet_file, provider)
        try:
            wallet.sweep(master.current_address, fee_calculator=fee_calc_small)
        except WalletBalanceError:
            cli_helpers.print_str("Sweep", ["Wallet balance (%d satoshis) is less than the dust "
                                            "limit. Not Sweeping." % total_value], "FAILED", False)
        except DustLimitError:
            cli_helpers.print_str("Sweep", ["Wallet balance (%d satoshis) would be below the "
                                            "dust limit when fees are deducted. "
                                            "Aborting sweep." % total_value], "FAILED", False)
        else:
            cli_helpers.print_str("Sweep", ["Swept %d satoshis, excluding %d satoshis of "
                                            "fees" % (total_value - fee, fee)], "SUCCESS", True)
    else:
        sys.exit()
Example #6
0
def get_payments_server_balance(provider):
    with open(Two1Composer.PAYMENTS_WALLET_FILE, "r") as f:
        info = json.load(f)

    mnemonic = info["mnemonic"]
    wallet = Two1Wallet.import_from_mnemonic(provider, mnemonic)

    balances = {"onchain": None,
                "channels": None}

    balances["onchain"] = wallet.balances["total"]

    channel_client = channels.PaymentChannelClient(wallet)
    channel_client.sync()
    channel_urls = channel_client.list()
    channels_balance = sum(s.balance for s in (channel_client.status(url) for url in channel_urls) if s.state == channels.PaymentChannelState.READY)

    balances["channels"] = channels_balance

    return balances
def get_payments_server_balance(provider):
    with open(Two1Composer.COMPOSE_FILE, "r") as f:
        info = yaml.load(f)

    mnemonic = info['services']['payments']['environment']['TWO1_WALLET_MNEMONIC']
    payments_wallet = Two1Wallet.import_from_mnemonic(data_provider=provider, mnemonic=mnemonic)

    balances = {
        "onchain": payments_wallet.balances["total"],
        "channels": None
    }

    channel_client = channels.PaymentChannelClient(payments_wallet)
    channel_client.sync()
    channel_urls = channel_client.list()
    channels_balance = sum(s.balance for s in (channel_client.status(url) for url in channel_urls)
                           if s.state == channels.PaymentChannelState.READY)

    balances["channels"] = channels_balance

    return balances
Example #8
0
def get_payments_server_balance(provider):
    with open(Two1Composer.COMPOSE_FILE, "r") as f:
        info = yaml.load(f)

    mnemonic = info['services']['payments']['environment'][
        'TWO1_WALLET_MNEMONIC']
    payments_wallet = Two1Wallet.import_from_mnemonic(data_provider=provider,
                                                      mnemonic=mnemonic)

    balances = {"onchain": payments_wallet.balances["total"], "channels": None}

    channel_client = channels.PaymentChannelClient(payments_wallet)
    channel_client.sync()
    channel_urls = channel_client.list()
    channels_balance = sum(s.balance for s in (channel_client.status(url)
                                               for url in channel_urls)
                           if s.state == channels.PaymentChannelState.READY)

    balances["channels"] = channels_balance

    return balances
Example #9
0
# this line is already in your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# load environment variables from .env
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

# load database from the DATABASE_URL environment variable
DATABASES = {}
DATABASES['default'] = dj_database_url.config(conn_max_age=600)

TWO1_WALLET_MNEMONIC = os.environ.get("TWO1_WALLET_MNEMONIC")
TWO1_USERNAME = os.environ.get("TWO1_USERNAME")
WALLET = Two1Wallet.import_from_mnemonic(mnemonic=TWO1_WALLET_MNEMONIC)

HASHIDS_SALT = os.environ.get("HASHIDS_SALT")

DEBUG = os.environ.get('DEBUG', 'False').lower() in ['t', 'true', '1']

# unused in this app
SECRET_KEY = 'g!&#vtozb7t363_5ow+p%rhm53w31rr=abf%c!0f$4#8jb!7us'

# TODO: Set this to your specific hostname when you turn off DEBUG
# or else you will get 400 errors.
ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = (
Example #10
0
# Load .env file for local use
dotenv_file = ".env"
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

client = TwilioRestClient(account=os.environ.get('TWILIO_ACCOUNT'),
                          token=os.environ.get('TWILIO_AUTH_TOKEN'))

validationclient = TwilioLookupsClient(account=os.environ.get('TWILIO_ACCOUNT'),
                                       token=os.environ.get('TWILIO_AUTH_TOKEN'))

app = Flask(__name__)

TWO1_WALLET_MNEMONIC = os.environ.get("TWO1_WALLET_MNEMONIC")
TWO1_USERNAME = os.environ.get("TWO1_USERNAME")
wallet = Two1Wallet.import_from_mnemonic(mnemonic=TWO1_WALLET_MNEMONIC)

payment = Payment(app, wallet, username=TWO1_USERNAME)


@app.route('/buy', methods=["POST"])
def start():
    to = ""
    post_data = request.get_json()
    if(post_data is None):
        return "You need to provide post data", 500
    try:
        response = validationclient.phone_numbers.get(post_data['phone'])
        if(response.country_code != "US"):
            return "Only numbers in the US are supported"
        to = response.phone_number
Example #11
0
 def __init__(self):
     self._connected = ComposerState.DISCONNECTED
     self.provider = TwentyOneProvider()
     self.default_wallet = Two1Wallet(self.wallet_file, self.provider)
Example #12
0
import codecs
import pytest
import two1.bitcoin as bitcoin

from two1.bitserv import OnChain
from two1.bitserv.models import OnChainSQLite3
from two1.wallet import Two1Wallet

from two1.bitserv.payment_methods import InsufficientPaymentError
from two1.bitserv.payment_methods import InvalidPaymentParameterError
from two1.bitserv.payment_methods import DuplicatePaymentError
from two1.bitserv.payment_methods import TransactionBroadcastError
from two1.bitserv.payment_methods import PaymentBelowDustLimitError


test_wallet = Two1Wallet.import_from_mnemonic(mnemonic='six words test wallet on fleek')


def _build_void_transaction(price=None, address=None):
    price = price or 1000
    address = address or '19tAqnusJv2XoyxsC1UzuBTdG9dCAgafEX'
    _, hash160 = bitcoin.utils.address_to_key_hash(address)
    h = codecs.encode(b'test hash for a fake payment txn', 'hex_codec').decode()
    outpoint = bitcoin.Hash(h)
    inputs = [bitcoin.TransactionInput(
        outpoint=outpoint, outpoint_index=0, script=bitcoin.Script(), sequence_num=0xffffffff
    )]
    outputs = [bitcoin.TransactionOutput(value=price, script=bitcoin.Script.build_p2pkh(hash160))]
    txn = bitcoin.Transaction(
        version=bitcoin.Transaction.DEFAULT_TRANSACTION_VERSION, inputs=inputs, outputs=outputs, lock_time=0
    )
Example #13
0
File: sell.py Project: shayanb/two1
def sweep(ctx, services, all, channels):
    """
Sweep service wallets to primary wallet.

\b
Sweep all service wallets to primary wallet.
$ 21 sell sweep --all

\b
Sweep the wallets of services to primary wallet.
$ 21 sell sweep <services>...
"""
    services_present = len(services) > 0
    all_present = all is True
    channels_present = channels is True

    if services_present + all_present + channels_present != 1:
        logger.info(ctx.command.get_help(ctx))
        sys.exit()

    manager = ctx.obj['manager']

    provider = TwentyOneProvider()
    master = Two1Wallet(manager.composer.PRIMARY_WALLET_FILE, provider)

    if not channels_present:
        try:
            with open(manager.composer.SERVICES_WALLET_FILE, "r") as f:
                services_info = json.load(f)
        except:
            logger.info(click.style("The services wallet information file seems to be corrupted, exiting..."), fg="magenta")
            sys.exit()

        requested_services_set = frozenset(services)
        available_services_set = frozenset(services_info.keys())

        if all:
            start_string = "Sweeping all service balances..."
            clients = {service_name: Two1Wallet.import_from_mnemonic(provider, service_details['mnemonic'])
                       for service_name, service_details in services_info.items()}
        elif requested_services_set.issubset(available_services_set):
            start_string = "Sweeping balances for " + ", ".join(services) + "..."
            clients = {service_name: Two1Wallet.import_from_mnemonic(provider, services_info[service_name]['mnemonic'])
                       for service_name in services}
        else:
            unavailable_requested_services = requested_services_set.difference(available_services_set)
            if len(unavailable_requested_services) > 1:
                logger.info(click.style("Services {} aren't available to be sweeped".format(", ".join(unavailable_requested_services)), fg="magenta"))
            else:
                logger.info(click.style("Service {} isn't available to be sweeped".format(", ".join(unavailable_requested_services)), fg="magenta"))
            sys.exit()
        logger.info(click.style(start_string, fg=cli_helpers.TITLE_COLOR))
    else:
        logger.info(click.style("Sweeping payment server balances...", fg=cli_helpers.TITLE_COLOR))
        try:
            with open(manager.composer.PAYMENTS_WALLET_FILE, "r") as f:
                payments_info = json.load(f)
        except:
            logger.info(click.style("The payment server wallet information file seems to be corrupted, exiting..."), fg="magenta")
            sys.exit()
        clients = {"payment channels": Two1Wallet.import_from_mnemonic(provider, payments_info['mnemonic'])}

    logger.info(click.style(start_string, fg=cli_helpers.TITLE_COLOR))

    utxo_sums = {}
    for service_name, wallet in clients.items():
        utxos_by_addr = wallet.get_utxos(include_unconfirmed=True,
                                         accounts=wallet._accounts)
        utxo_sums[service_name] = wallet._sum_utxos(utxos_by_addr)

    fee_dict = {}
    fee_amounts = txn_fees.get_fees()
    for service_name, utxo_sum in utxo_sums.items():
        total_value, num_utxos = utxo_sum
        fee_dict[service_name] = fee_calc_small(num_utxos, total_value, fee_amounts)
    fees = sum(fee_dict.values())

    if click.confirm(click.style("This will incur a fee of approximately %d satoshis in total. "
                                 "Would you like to continue?" % fees, fg=cli_helpers.PROMPT_COLOR)):
        for service_name, wallet in clients.items():
            try:
                wallet.sweep(master.current_address, fee_calculator=fee_calc_small)
            except WalletBalanceError:
                cli_helpers.print_str(service_name, ["Wallet balance (%d satoshis) is less than the dust limit. Not Sweeping." % utxo_sums[service_name][0]], "FALSE", False)
            except DustLimitError:
                cli_helpers.print_str(service_name, ["Wallet balance (%d satoshis) would be below the dust limit when fees are deducted. Not Sweeping." % utxo_sums[service_name][0]], "FALSE", False)
            else:
                total_value = utxo_sums[service_name][0]
                fees_incurred = fee_dict[service_name]
                cli_helpers.print_str(service_name, ["Sweeped %d satoshis, excluding %d satoshis of fees" % (total_value - fees_incurred, fees_incurred)], "TRUE", True)
    else:
        sys.exit()
Example #14
0
from os.path import expanduser
from two1.wallet import Two1Wallet
from two1.bitcoin.crypto import HDPublicKey, PublicKey
from two1.bitcoin.txn import Transaction
from two1.blockchain.twentyone_provider import TwentyOneProvider
from two1.bitcoin.script import Script
from two1.commands.util.currency import Price
from two1.bitcoin.utils import bytes_to_str
from two1.wallet.base_wallet import convert_to_satoshis

with open('{}/.two1/wallet/default_wallet.json'.format(
        expanduser('~'))) as data_file:
    wallet_data = json.load(data_file)

wallet = None
wallet = wallet or Two1Wallet.import_from_mnemonic(
    mnemonic=wallet_data['master_seed'])
provider = TwentyOneProvider()


def execute(wallet_method):
    methodToCall = getattr(wallet, wallet_method)
    result = json.dumps({wallet_method: methodToCall()})
    print(result)


# Loop through methods
del sys.argv[0]
if sys.argv[0] == 'sign':
    pubkey = HDPublicKey.from_hex(sys.argv[1])
    server_privkey = wallet.get_private_for_public(pubkey)
    tx = Transaction.from_hex(sys.argv[2])
Example #15
0
import os

from flask import Flask

from two1.wallet import Two1Wallet
from two1.bitserv.flask import Payment

application = Flask(__name__)
payment = Payment(
    application,
    Two1Wallet.import_from_mnemonic(
        mnemonic=os.getenv('TWO1_WALLET_MNEMONIC')),  # noqa: E501
    username=os.getenv('TWO1_USERNAME'))

import translator.views  # noqa: E402,F401