def main(ctx, config_file, config): """Mine bitcoin and use it to buy and sell digital goods. \b Usage ----- Mine bitcoin, list your balance, and buy a search query without ads. $ {0} mine $ {0} status $ {0} buy search "Satoshi Nakamoto" \b For further details on how you can use your mined bitcoin to buy digital goods both at the command line and programmatically, visit 21.co/learn """ create_wallet_and_account = ctx.invoked_subcommand not in \ ('help', 'update', 'publish', 'sell', 'rate', 'search', 'login') try: cfg = Config(config_file, config, create_wallet=create_wallet_and_account) except DataProviderUnavailableError: raise TwoOneError(UxString.Error.connection_cli) except DataProviderError: raise TwoOneError(UxString.Error.server_err) if create_wallet_and_account: try: check_setup_twentyone_account(cfg) except UnloggedException: sys.exit(1) ctx.obj = dict(config=cfg)
def payUser(): payee = request.args.get('user') amount = int(request.args.get('amount')) payer = Config().username description = request.args.get('description', 'Reward from ' + payer) return "", sendBittransfer(payee, amount, description).raise_for_status()
def sendBittransfer(payee_username, amount, description=""): """Create and redeem a BitTransfer.""" wallet = Wallet() username = Config().username bittransfer, signature = createBittransfer( wallet, username, payee_username, amount, description) return redeemBittransfer(bittransfer, signature, payee_username)
def check_endpoints(self): """Crawl 402 endpoints""" # create 402 client self.bitrequests = BitTransferRequests(Wallet(), Config().username) # crawl endpoints, check headers self.logger.info("\nCrawling machine-payable endpoints...") for endpoint in self.endpoint_list: # extract domain name name = endpoint.split('/', 1)[0].split('.', 1)[1] # get server ip server_ip = socket.gethostbyname(name) # self.logger.info("Checking {0} on port {1}".format(server_ip, port)) self.logger.info("Checking {}...".format(endpoint)) # configure socket module sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_state = sock.connect_ex((server_ip, 80)) sock.close() if server_state == 0: try: self.logger.info( "Server state: {} is up!".format(endpoint)) response = self.bitrequests.get_402_info('https://' + endpoint) self.logger.info("Price: {}".format(response['price'])) self.logger.info("Address: {}".format( response['bitcoin-address'])) except Exception as e: self.logger.info("Could not read 402 payment headers.") else: self.logger.info( "Server state: {} is down!".format('https://' + endpoint)) self.logger.info("Timestamp: {}\n".format(datetime.datetime.now()))
import click # import from the 21 Bitcoin Developer Library from two1.commands.config import Config from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests username = Config().username wallet = Wallet() requests = BitTransferRequests(wallet, username) @click.command() @click.argument('file_name', required=False) @click.option('--server', default='localhost:5001', help='ip:port to connect to') def img2txt21(server, file_name): """ Call the img to text api hosted on the micropayments server""" ## If a file isn't specified, read image from stdin if file_name: upload = requests.post('http://' + server + '/upload', files={'file': open(file_name, 'rb')}) else: file = click.get_binary_stream('stdin') file_name = 'test.jpg' upload = requests.post('http://' + server + '/upload', files={'file': (file_name, file)}) # convert image to text
from two1.blockchain.exceptions import DataProviderError from two1.wallet.exceptions import WalletBalanceError from two1.commands.util.decorators import json_output from two1.commands.config import Config from two1 import TWO1_HOST conf = Config() def send(address, satoshis, use_unconfirmed): print(address, satoshis) w = conf.wallet balance = min(w.confirmed_balance(), w.unconfirmed_balance()) try: txids = w.send_to(address=address, amount=satoshis, use_unconfirmed=use_unconfirmed) # For now there is only a single txn created, so assume it's 0 txid = txids[0]["txid"] tx = txids[0]["txn"] print("Successfully sent %s satoshis to %s.\n" "txid: %s\n" "tx: %s\n" "To see in the blockchain: " "https://blockexplorer.com/tx/%s\n" % (satoshis, address, txid, tx, txid)) except ValueError as e: # This will trigger if there's a below dust-limit output. print(str(e)) except WalletBalanceError:
from flask.ext.admin.contrib.fileadmin import FileAdmin # Setup the dashboard from two1.commands import status from two1.commands import log from two1.commands import flush from two1.commands import mine from two1.wallet import Wallet from two1.server.machine_auth_wallet import MachineAuthWallet from two1.server import rest_client from two1.commands.config import Config from two1 import TWO1_HOST wallet = Wallet() host = TWO1_HOST conf = Config() username = Config().username client = rest_client.TwentyOneRestClient(host, MachineAuthWallet(wallet), username) admin = Admin(app, name='Admin', template_mode='bootstrap3') class DashboardView(BaseView): @expose('/', methods=('GET', 'POST')) def dashboard(self): flush_message = "" status_mining = status.status_mining(client) if request.method == 'POST': print(request.form) if request.form['submit'] == 'Flush Earnings':
import os import json from flask import Flask from flask import request from two1.lib.server import rest_client from two1.commands.config import TWO1_HOST from two1.commands.config import Config from two1.lib.wallet import Wallet from two1.lib.bitserv.flask import Payment app = Flask(__name__) wallet = Wallet() config = Config() payment = Payment(app, wallet) client = rest_client.TwentyOneRestClient(TWO1_HOST, config.machine_auth, config.username) class Charity(object): name = "" address = "" # The class "constructor" - It's actually an initializer def __init__(self, name, address): self.name = name self.address = address bitGive = Charity("Bit Give", "1PEoUKNxTZsc5rFSQvQjeTVwDE9vEDCRWm") charities = [bitGive] # endpoint to look up avaialable charities to donate to