예제 #1
0
class Sensor():

    app = Flask(__name__)
    wallet = Wallet()
    payment = Payment(app, wallet)

    @app.route('/info')
    def get_info():
        """Returns details about available endpoints"""

        info = {
            'endpoints': {
                'per-req': 1,
                'returns': {
                    'name': 'timestamp',
                    'description': 'Python UTC timestamp'
                },
                'name': 'value',
                'description': '21BC hashrate in GH/s',
                'route': '/measurement',
                'description': 'Current 21BC mininig hashrate in GH/s'
            }
        }

        return jsonify(info)

    # Charge a fixed fee of 10 satoshis per request to the
    # /measurement endpoint

    @app.route('/measurement')
    @payment.required(1)
    def measurement():

        data = check_output(['21', 'status'])
        timestamp = time.time()

        data = str(data)
        index0 = data.find('Hashrate')
        index1 = data[index0:].find(':')
        index2 = data[index0:].find('GH/s')

        try:
            data = float(data[index0 + index1 + 2:index0 + index2 - 1])

        except:
            data = data[index0 + index1 + 2:index0 + index2 - 1]

        measurement = {'timestamp': timestamp, 'value': data}

        measurement_json = json.dumps(measurement)

        return measurement_json

    # Initialize and run the server
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=3002)
예제 #2
0
    def __init__(self, url, wallet=None):
        """Instantiate a Test Payment Channel Server interface for the
        specified URL.

        Args:
            url (str): URL of Test server.
            wallet (two1.lib.wallet.Wallet): Wallet instance.

        Returns:
            TestPaymentChannelServer: instance of TestPaymentChannelServer.

        """
        super().__init__()
        self._wallet = wallet if wallet else Wallet()
예제 #3
0
    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()))
예제 #4
0
from flask import abort

# import from the 21 Developer Library
from two1.lib.bitcoin.txn import Transaction
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.wallet import Wallet, exceptions
from two1.lib.bitserv.flask import Payment

USCENT = 2801

pp = pprint.PrettyPrinter(indent=2)

db = srvdb.SrvDb('turk.db')

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)


def check_timestamp(tstamp):
    curtime = int(time.time())
    min_time = min(tstamp, curtime)
    max_time = max(tstamp, curtime)
    time_diff = max_time - min_time
    if (time_diff > 15):
        return False
    return True


@app.route('/task/<id>')
@payment.required(int(USCENT / 100))
예제 #5
0
파일: cli.py 프로젝트: erikvold/two1
def main(ctx, json):
    """Top-level command line call that configures the command context."""
    client = PaymentChannelClient(Wallet(WALLET_PATH), CHANNELS_DB_PATH)
    ctx.obj = {'client': client, 'json': json}
예제 #6
0
#!/usr/bin/env python3
import json
import os

# import from the 21 Developer Library
from two1.commands.config import Config
from two1.lib.wallet import Wallet
from two1.lib.bitrequests import BitTransferRequests
import two1.lib.bitcoin as bitcoin
from two1.lib.wallet import Wallet

wallet = Wallet()

address = input("Please enter the address of your script")
amount = int(input("Please enter the amount of satoshis you'd like to pay"))

if address and amount:
    deposit_tx_obj = wallet.send_to(address, 25000, False, 5000, [])
    deposit_tx = deposit_tx_obj[0]["txn"]
    deposit_tx_id = deposit_tx_obj[0]["txid"]
    deposit_utxo_index = deposit_tx.output_index_for_address(address)

    print("--------------------")
    print(
        "Please copy the deposit and the deposit index for later use. You can paste the deposit ID into block explorer if you want to track your transaction."
    )
    print("--------------------")
    print("Deposit: {}\n".format(deposit_tx.to_hex()))
    print("Deposit index: {}\n".format(deposit_utxo_index))
    print("Deposit ID: {}\n".format(deposit_tx_id))
else:
예제 #7
0
from flask import Flask
from flask import request
from flask import abort

# import from the 21 Developer Library
from two1.lib.bitcoin.txn import Transaction
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.wallet import Wallet, exceptions
from two1.lib.bitserv.flask import Payment

connection = apsw.Connection("signing.db")

SRV_ACCT = 'signing'

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)

# Create wallet account for these contracts
try:
    wallet.create_account(SRV_ACCT)
except exceptions.AccountCreationError:
    pass


def srvdb_last_idx(cursor):
    row = cursor.execute("SELECT MAX(hd_index) FROM metadata").fetchone()
    if row is None:
        return 0
    return int(row[0])
예제 #8
0
def main(ctx, json):
    client = PaymentChannelClient(Wallet(WALLET_PATH), CHANNELS_DB_PATH)
    ctx.obj = {'client': client, 'json': json}
예제 #9
0
from flask import Flask
from flask import request
from flask import abort

# import from the 21 Developer Library
from two1.lib.bitcoin.txn import Transaction
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.wallet import Wallet, exceptions
from two1.lib.bitserv.flask import Payment

connection = apsw.Connection("signing.db")

SRV_ACCT = 'signing'

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)

# Create wallet account for these contracts
try:
    wallet.create_account(SRV_ACCT)
except exceptions.AccountCreationError:
    pass

def srvdb_last_idx(cursor):
    row = cursor.execute("SELECT MAX(hd_index) FROM metadata").fetchone()
    if row is None:
        return 0
    return int(row[0])

@app.route('/new')
예제 #10
0
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.bitcoin.txn import Transaction
from two1.lib.wallet import Wallet
from two1.lib.bitcoin.script import Script
from two1.lib.blockchain.twentyone_provider import TwentyOneProvider
import two1.lib.bitcoin as bitcoin

provider = TwentyOneProvider()
wallet = Wallet()

pubkey = input("Please enter the public key that was used to create the script")
tx_hex = input("Please enter the transaction hex")
server_pubkey = input("Please enter server pub key")
white_pubkey = input("Please enter white pub key")
black_pubkey = input("Please enter black pub key")


their_pubkey = PublicKey.from_bytes(pubkey)
tx = Transaction.from_hex(tx_hex)

private_key = wallet.get_private_for_public(their_pubkey)
public_keys = [PublicKey.from_bytes(server_pubkey).compressed_bytes, PublicKey.from_bytes(white_pubkey).compressed_bytes, PublicKey.from_bytes(black_pubkey).compressed_bytes]
redeem_script = Script.build_multisig_redeem(2, public_keys)

for i, inp in enumerate(tx.inputs):
   tx.sign_input(i, bitcoin.Transaction.SIG_HASH_ALL, private_key, redeem_script)

txid = provider.broadcast_transaction(tx.to_hex())

print("Transaction ID: {}".format(txid))
예제 #11
0
from two1.lib.bitcoin.crypto import PublicKey
from two1.lib.wallet import Wallet
from two1.lib.bitcoin.utils import bytes_to_str

wallet = Wallet()
pubkey = wallet.get_payout_public_key()
compressed = pubkey.compressed_bytes
str = bytes_to_str(pubkey.compressed_bytes).upper()

print("Payout public key: %s" % (str))