def test_bittransfer_request(): """Test that it handles bit-transfer requests.""" bit_req = BitTransferRequests(wallet, config.username) test_max_price = 10000 price = 1000 address = 'test_bitserv_host_address' user = '******' mock_request = MockRequest() headers = {'price': price, 'bitcoin-address': address, 'username': user} url = 'http://localhost:8000/weather/current-temperature?place=94102' setattr(mock_request, 'headers', headers) setattr(mock_request, 'url', url) # Test that we can make a successful 402 payment bittransfer_pmt = bit_req.make_402_payment(mock_request, test_max_price) assert type(bittransfer_pmt) == dict bit_transfer = json.loads(bittransfer_pmt['Bitcoin-Transfer']) assert bit_transfer['payee_address'] == address assert bit_transfer['payee_username'] == user assert bit_transfer['amount'] == price assert bit_transfer['description'] == url # Test that an error is raised if the server doesn't support bittransfers with pytest.raises(BitRequestsError): headers = {'price': price} setattr(mock_request, 'headers', headers) bit_req.make_402_payment(mock_request, test_max_price)
def test_bittransfer_request(): """Test that it handles bit-transfer requests.""" bit_req = BitTransferRequests(wallet, config.username, client) test_max_price = 10000 price = 1000 address = 'test_bitserv_host_address' user = '******' mock_request = MockRequest() headers = {'price': price, 'bitcoin-address': address, 'username': user} url = 'http://localhost:8000/weather/current-temperature?place=94102' setattr(mock_request, 'headers', headers) setattr(mock_request, 'url', url) # Test that we can make a successful 402 payment bittransfer_pmt = bit_req.make_402_payment(mock_request, test_max_price) assert type(bittransfer_pmt) == dict bit_transfer = json.loads(bittransfer_pmt['Bitcoin-Transfer']) assert bit_transfer['payee_address'] == address assert bit_transfer['payee_username'] == user assert bit_transfer['amount'] == price assert bit_transfer['description'] == url # Test that an error is raised if the server doesn't support bittransfers with pytest.raises(BitRequestsError): headers = {'price': price} setattr(mock_request, 'headers', headers) bit_req.make_402_payment(mock_request, test_max_price)
def test_bittransfer_default_config(): """Test that it looks up a username using the default Config.""" current_username = config.username bit_req = BitTransferRequests(wallet) assert bit_req.username == current_username # Test that we can still use a custom username bit_req = BitTransferRequests(wallet, 'new_username') assert bit_req.username == 'new_username'
def cli(raw_msg): msg = urllib.parse.quote_plus(raw_msg) requests = BitTransferRequests(wallet) # purchase the bitcoin payable endpoint response = requests.get('http://10.244.107.98:3003/write-message?message={}'.format(raw_msg)) # print out the transaction click.echo("Transaction ID Number: {}".format(response.text)) click.echo("Find your notary at https://live.blockcypher.com/btc/tx/{}".format(response.text))
def write_message(raw_msg): msg = urllib.parse.quote_plus(raw_msg) requests = BitTransferRequests(wallet) # purchase the bitcoin payable endpoint response = requests.get('http://localhost:5000/write-ew-message?message={}'.format(msg)) # print out the transaction print("Transaction: {}".format(response.text)) print("View it live at http://eternitywall.it/m/{}".format(response.text))
def cli(raw_msg): msg = urllib.parse.quote_plus(raw_msg) requests = BitTransferRequests(wallet) # purchase the bitcoin payable endpoint response = requests.get('http://localhost:5000/write-message?message={}'.format(raw_msg)) # print out the transaction click.echo("Transaction: {}".format(response.text)) click.echo("View it live at https://live.blockcypher.com/btc/tx/{}".format(response.text))
def test_get_402_info(monkeypatch): # Patch requests from making actual http requests monkeypatch.setattr(requests, 'get', mockrequest) # Test that OnChainRequests 402 info returns a dict of headers bit_req = OnChainRequests(wallet) headers = bit_req.get_402_info('fakeurl') assert type(headers) == dict assert headers['price'] == 1337 assert headers['bitcoin-address'] == '1THISISANADDRESS' # Test that BitTransferRequests 402 info returns a dict of headers def mock_bittransfer_request(*args, **kwargs): mock_req = mockrequest(*args, **kwargs) mock_req.headers['username'] = '******' mock_req.headers['bitcoin-address'] = '3NEWADDRESS' return mock_req monkeypatch.setattr(requests, 'get', mock_bittransfer_request) bit_req = BitTransferRequests(wallet, config.username) headers = bit_req.get_402_info('fakeurl') assert type(headers) == dict assert headers['price'] == 1337 assert headers['bitcoin-address'] == '3NEWADDRESS' assert headers['username'] == 'long john silver'
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 random import randint from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests import hashlib from getpass import getpass from requests import get wallet = Wallet() requests = BitTransferRequests(wallet) srv = "http://21.browntech.space:8383/" print("Welcome to BitMon Client! :)") answer = int(input("Would you like to login[1] or register[2]?: ")) ipaddr = get('https://api.ipify.org').text if answer == 1: user = input("User name: ").lower() password = getpass("Password: "******"User name: ").lower() if not user.isalnum() or not 6 <= len(user) <= 12: print( "Please enter only numbers and letters, between 6 and 12 characters." ) exit() password = getpass("Password: ")
import logging import os from transcodeE16 import TranscodeE16 from two1.commands.util import config from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests requests = BitTransferRequests(Wallet(), config.Config().username) log = logging.getLogger('werkzeug') log.setLevel(logging.INFO) def testDuration(): """ Tests getting the duration for a sample video. """ try: log.warning("In testDuration()") dataDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') # Create the speed testing client transcoder = TranscodeE16(dataDir) duration = transcoder.getDuration('http://www.esixteen.co/video/sample.mp4') log.info("Success!") log.info("Duration test completed with duration: {}", duration) except Exception as err: log.warning('Client test failed')
#!/usr/bin/env python3 import urllib.parse from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests wallet = Wallet() requests = BitTransferRequests(wallet) # request the bitcoin-enabled endpoint that you're hosting def testendpoint(sms='I just paid you bitcoin to send you this message!'): # In a real application you would escape this message to prevent injections message = urllib.parse.quote_plus(sms) response = requests.get(url='http://localhost:5000/send-sms?text='+message) print(response.text) if __name__ == '__main__': import sys testendpoint(sys.argv[1])
# Loading developer libraries import json from two1.commands.config import Config from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests wallet = Wallet() username = Config().username requests = BitTransferRequests(wallet, username) # Set up the server to run locally #server_url = 'http://localhost:5000/' server_url = 'http://10.244.117.238:5000/' # Request the 402 end-points from the server and assign price and address to variables. info = requests.get_402_info(url=server_url+'top-stories') endpoint_info = dict(info) price = int(endpoint_info['price']) address = str(endpoint_info['bitcoin-address']) # Array of all the top-story sections sections = ["home", "world", "national", "politics", "nyregion", "business", "opinion", "technology", "health", "sports", "arts", "fashion", "dining", "travel", "magazine", "realestate"] def get_top_stories(section): params = {
from werkzeug.datastructures import Headers from two1.wallet import Wallet #originally handled by the requesting client #Now outsourced to payment_handler.py from two1.bitrequests import BitTransferRequests from two1.bitrequests import BitRequestsError app = Flask(__name__) #instantiate a wallet _wallet = Wallet() #this function handles bitcoin micropayments using the wallet object btc_requests = BitTransferRequests(_wallet) ''' simple satoshi-payment proxy with one function: receive request from client and process payment on destination server address passed as url parameter in proxy client GET request ''' @app.route('/') def main(): try: #create a response object to hold request result based on param url received from client res = btc_requests.request( method=request.method, url=request.url, data=request.data if request.data else None,
# Loading developer libraries import json from two1.commands.config import Config from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests wallet = Wallet() username = Config().username requests = BitTransferRequests(wallet, username) # Set up the server to run locally #server_url = 'http://localhost:5000/' server_url = 'http://10.244.117.238:5000/' # Request the 402 end-points from the server and assign price and address to variables. info = requests.get_402_info(url=server_url + 'top-stories') endpoint_info = dict(info) price = int(endpoint_info['price']) address = str(endpoint_info['bitcoin-address']) # Array of all the top-story sections sections = [ "home", "world", "national", "politics", "nyregion", "business", "opinion", "technology", "health", "sports", "arts", "fashion", "dining", "travel", "magazine", "realestate" ] def get_top_stories(section): params = {'section': section}
#!/usr/bin/env python3 from flask import Flask from flask import jsonify from flask import request from flask import abort from two1.wallet import Wallet from two1.bitrequests import BitTransferRequests # set up bitrequest client for BitTransfer requests wallet = Wallet() requests = BitTransferRequests(wallet) # server address server_url = 'http://localhost:8000/' # Start flask service app = Flask(__name__) # definition of micropayment_sendvote function def micropayment_sendvote(proposal): ''' Function: micropayment_sendvote() Arguments: - proposal: sting. Possible values: yes / no ''' ans = str(proposal) sel_url = server_url + 'write-vote?proposal={0}'
def buy(config, resource, data, method, data_file, output_file, payment_method, max_price, info_only): """Buy from any machine payable endpoint Note: The two1lib _buy function does not support simply returning an object, until then, include a local copy here """ # If resource is a URL string, then bypass seller search if URL_REGEXP.match(resource): target_url = resource seller = target_url elif resource in DEMOS: target_url = TWO1_WWW_HOST + DEMOS[resource]["path"] data = json.dumps(data) else: raise NotImplementedError('Endpoint search is not implemented!') # Change default HTTP method from "GET" to "POST", if we have data if method == "GET" and (data or data_file): method = "POST" # Set default headers for making bitrequests with JSON-like data headers = {'Content-Type': 'application/json'} try: # Find the correct payment method if payment_method == 'offchain': bit_req = BitTransferRequests(config.machine_auth, config.username) elif payment_method == 'onchain': bit_req = OnChainRequests(config.wallet) else: raise Exception('Payment method does not exist.') # Make the request if info_only: res = bit_req.get_402_info(target_url) else: res = bit_req.request(method.lower(), target_url, max_price=max_price, data=data or data_file, headers=headers) except ResourcePriceGreaterThanMaxPriceError as e: config.log( uxstring.Error.resource_price_greater_than_max_price.format(e)) return except Exception as e: if 'Insufficient funds.' in str(e): config.log( uxstring.Error.insufficient_funds_mine_more.format( DEFAULT_ONCHAIN_BUY_FEE)) else: config.log(str(e), fg="red") return # Output results to user if output_file: # Write response output file output_file.write(res.content) elif info_only: # Print headers that are related to 402 payment required for key, val in res.items(): config.log('{}: {}'.format(key, val)) elif resource in DEMOS: config.log(DEMOS[resource]["formatter"](res)) else: response = res.json() # Clean up names for index, elem in enumerate(response): if elem['name'] is None: response[index]['name'] = 'Please name me' elif len(elem['name']) == 0: response[index]['name'] = 'Please name me' else: response[index]['name'] = response[index]['name'].title() print(elem['description']) if elem['description'] is None: try: response[index]['description'] = elem['owner'].title( ) + ' is a bad endpoint operator and forgot to place a description' except: response[index][ 'description'] = 'Anonymous is a bad endpoint operator and forgot to place a description' # Any description greater than 66 characters causes the text to overflow, this enforces a limit elif len(elem['description']) > 63: response[index]['description'] = response[index][ 'description'][:63] + '...' # Write response to console return response # Write the amount paid out if something was truly paid if not info_only and hasattr(res, 'amount_paid'): client = rest_client.TwentyOneRestClient(TWO1_HOST, config.machine_auth, config.username) user_balances = _get_balances(config, client) if payment_method == 'offchain': balance_amount = user_balances.twentyone balance_type = '21.co' elif payment_method == 'onchain': balance_amount = user_balances.onchain balance_type = 'blockchain' # Record the transaction if it was a payable request if hasattr(res, 'paid_amount'): config.log_purchase(s=seller, r=resource, p=res.paid_amount, d=str(datetime.datetime.today()))