コード例 #1
0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8566" %
                                  ('user', 'pass'))

# create raw transaction

# here we can load raw transaction information from csv and pass it to paicoind-cli using bellow method
tx_hex_string = rpc_connection.createrawtransaction([{
    "txid": "dbdc2e2c7f143af70c5e7e8725f55d226b3c058d7bf34a303091b3c6a514848c",
    "vout": 1
}], {"Mj8ntt66KnQniKvRny6o8kxiWgz5xhycGx":
     0.00011})
print(tx_hex_string)

#signing raw transacion
rpc_connection.signrawtransaction(tx_hex_string, [{
    "txid": tx_hex_string,
    "vout": "%s",
    "scriptPubKey": "%s"
}], ["private_key_data"])

# sending raw transaction
rpc_connection.sendrawtransaction(tx_hex_string)

### getting transaction fee

print(
    rpc_connection.gettransaction('transaction_id_which_we_want_to_use')
    ['fee'])
コード例 #2
0
ファイル: genBlocks.py プロジェクト: rulebreakerdude/BitRank

def get_block_with_hash(hsh, api_code=None):
    resource = 'block/{0}.json'.format(hsh)
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = net_util.call_api(resource)
    json_response = json.loads(response)
    return json_response


if __name__ == '__main__':
    rpc_user = "******"
    rpc_password = "******"
    # rpc_user and rpc_password are set in the bitcoin.conf file
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                      (rpc_user, rpc_password))

    script_dir = os.path.dirname(__file__)
    blocks = []
    start_height = int(raw_input("Enter start height: "))
    end_height = int(raw_input("Enter end height: "))
    step = 10  #int(raw_input("Enter step size: "))

    #integer division is being performed
    #start_height = ((start_height / step) * step)
    if ((end_height % step) != 0):
        end_height = (((end_height / step) + 1) * step)

    init = start_height
    for i in range(start_height + step, (end_height + 1), step):
        commands = [["getblockhash", height] for height in range(init, i)]
コード例 #3
0
ファイル: crypto.py プロジェクト: viadata/sodogetip
def get_rpc():
    return AuthServiceProxy(
        "http://%s:%s@%s:%s" %
        (config.rpc_config['rpc_username'], config.rpc_config['rpc_password'],
         config.rpc_config['rpc_host'], config.rpc_config['rpc_port']),
        timeout=config.rpc_config['timeout'])
コード例 #4
0
    def do(self):
        rpc = AuthServiceProxy('http://' + settings.BITCOIN_RPC_USERNAME +
                               ':' + settings.BITCOIN_RPC_PASSWORD + '@' +
                               settings.BITCOIN_RPC_IP + ':' +
                               str(settings.BITCOIN_RPC_PORT))

        # Total number of blocks
        blocks = rpc.getblockcount()
        blocks_processed_queryset = CurrentBlockHeight.objects.order_by(
            '-block_height')
        blocks_processed = blocks_processed_queryset[
            0].block_height if blocks_processed_queryset.count() else 0

        # Now incoming transactions will be processed and added to database. Transactions
        # from new blocks are selected, but also transactions from several older blocks.
        # These extra transactions are updated in case something (for example fork?) is
        # able to modify transactions in old blocks.
        EXTRA_BLOCKS_TO_PROCESS = 6
        process_since = max(0, blocks_processed - EXTRA_BLOCKS_TO_PROCESS)
        process_since_hash = rpc.getblockhash(process_since)

        # Just to be sure: Reconstruct list of transactions, in case
        # there are receiving to same address in same transaction.
        txs_raw = rpc.listsinceblock(process_since_hash)['transactions']
        txs = []
        for tx_raw in txs_raw:
            # Skip other than receiving transactions
            if tx_raw['category'] != 'receive':
                continue

            # Search for duplicate transaction/address pair
            tx = None
            for tx_find in txs:
                if tx_find['txid'] == tx_raw['txid'] and tx_find[
                        'address'] == tx_raw['address']:
                    tx = tx_find
                    break

            # Create new transaction, or update old one
            if not tx:
                txs.append({
                    'txid': tx_raw['txid'],
                    'address': tx_raw['address'],
                    'amount': tx_raw['amount'],
                    'blockhash': tx_raw.get('blockhash'),
                    'timereceived': tx_raw['timereceived'],
                })
            else:
                assert tx['txid'] == tx_raw['txid']
                assert tx['address'] == tx_raw['address']
                assert tx['blockhash'] == tx_raw.get('blockhash')
                assert tx['timereceived'] == tx_raw['timereceived']
                tx['amount'] += tx_raw['amount']

        # Get already existing transactions, so they are not created twice.
        # This list is also used to delete those Transactions that might have
        # disappeared because of fork or other rare event. Better be sure.
        old_txs = Transaction.objects.filter(incoming_txid__isnull=False)
        old_txs = old_txs.filter(
            Q(block_height__isnull=True) | Q(block_height__gt=process_since))
        old_txs = list(old_txs)

        # Go through transactions and create Transaction objects.
        for tx in txs:
            # Get required info
            txid = tx['txid']
            address = tx['address']
            amount = tx['amount']
            block_hash = tx['blockhash']
            block_height = rpc.getblock(
                block_hash)['height'] if block_hash else None
            created_at = datetime.datetime.utcfromtimestamp(
                tx['timereceived']).replace(tzinfo=pytz.utc)

            # Skip transaction if it doesn't belong to any Wallet
            try:
                address = Address.objects.get(address=address)
            except Address.DoesNotExist:
                continue

            # Check if transaction already exists
            already_found = False
            for old_tx in old_txs:
                if old_tx.incoming_txid == txid and old_tx.receiving_address == address:
                    assert old_tx.amount == amount
                    # Check if transaction was confirmed
                    if block_height and not old_tx.block_height:
                        old_tx.block_height = block_height
                        old_tx.save(update_fields=['block_height'])
                    # Do nothing more with transaction, as it already exists in database.
                    old_txs.remove(old_tx)
                    already_found = True
                    break

            # If transaction is new one
            if not already_found:
                new_tx = Transaction.objects.create(
                    wallet=address.wallet,
                    amount=amount,
                    description='Received',
                    incoming_txid=txid,
                    block_height=block_height,
                    receiving_address=address,
                )
                new_tx.created_at = created_at
                new_tx.save(update_fields=['created_at'])

        # Clean remaining old transactions.
        # The list should be empty, unless
        # fork or something similar has happened.
        for old_tx in old_txs:
            old_tx.delete()

        # Mark down what the last processed block was
        blocks = rpc.getblockcount()
        if blocks_processed_queryset.exists():
            blocks_processed_queryset.update(block_height=blocks)
        else:
            CurrentBlockHeight.objects.create(block_height=blocks)
コード例 #5
0
ファイル: feeloop.py プロジェクト: Nugetzrul3/CoreFeeHelper
import time
from bitcoinrpc.authproxy import AuthServiceProxy
import tweepy
import urllib.request
import json
import re
import sys

# Requires running Core RPC server on standard mainnet RPC port
if len(sys.argv) < 7:
    raise Exception('feeloop.py <RPC username> <RPC password> <oauth1> <oauth2> <token1> <token2>')

while True:
    bitcoin_req = "http://"+sys.argv[1]+":"+sys.argv[2]+"@127.0.0.1:8332"
    bitcoin = AuthServiceProxy(bitcoin_req)

    def get_rounded_feerate(result):
        rate = str(int(result*1000000)/10.0)+" sat/byte "
        if len(re.split("\.", rate)[0]) == 1:
            rate = " "+rate
        return rate

    try:
        mempool_info = bitcoin.getmempoolinfo()
        nextblock = ["Next: ", bitcoin.estimatesmartfee(1, "ECONOMICAL")["feerate"]]
        hour = ["1h:   ", bitcoin.estimatesmartfee(6, "ECONOMICAL")["feerate"]]
        six_hours = ["6h:   ", bitcoin.estimatesmartfee(6*6, "ECONOMICAL")["feerate"]]
        twelve_hours = ["12h:  ", bitcoin.estimatesmartfee(6*12, "ECONOMICAL")["feerate"]]
        day = ["1d:   ", bitcoin.estimatesmartfee(144, "ECONOMICAL")["feerate"]]
        half_week = ["3d:   ", bitcoin.estimatesmartfee(int(144*3.5), "ECONOMICAL")["feerate"]]
コード例 #6
0
ファイル: wallet.py プロジェクト: tehranifar/ZTipBot
def connect():
    return AuthServiceProxy("http://%s:%[email protected]:8332" %
                            (rpc_user, rpc_password))
コード例 #7
0
            sys.exit()
        if m > max_unused_key:
            sys.exit()


# for testnet
rpcuser = '******'
rpcpassword = '******'
rpcbindip = 'test.stats.dash.org'
rpcport = 587
max_unused_key = 30
max_child_index = 2000

serverURL = 'https://' + rpcuser + ':' + rpcpassword + '@' + rpcbindip + ':' + str(
    rpcport)
access = AuthServiceProxy(serverURL)

# http://chaeplin.github.io/bip39/
# tpub of m/44'/1'/0'/0

BIP32_EXTENDED_KEY = input("Please enter BIP32 Extended Public Key: ")

if not BIP32_EXTENDED_KEY.startswith('tpub'):
    sys.exit("\n\t===> not bip32 ext pub key for testnet\n")

try:
    bip32_tpub = get_bip32_unused(BIP32_EXTENDED_KEY)
    print('index\tseq\taddress')
    while True:
        bip32_unused_index, bip32_unused_seq, bip32_unused_address = bip32_tpub.__next__(
        )
コード例 #8
0
def main(args):

    logo_show()

    ssl._create_default_https_context = ssl._create_unverified_context

    serverURL = 'https://' + rpcuser + ':' + rpcpassword + '@' + rpcbindip + \
        ':' + str(rpcport if USE_SSH_TUNNEL is False else SSH_LOCAL_PORT)

    access = AuthServiceProxy(serverURL)

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):
        client, signing, mpath = check_hw_wallet()

    else:
        client, signing, bip32, mpath, xpub = check_hw_wallet()

    if client is None:
        sys.exit()

    if len(args.account_number) > 0:
        for i in args.account_number:
            account_no = i

            bip32_path = "44'/5'/" + str(
                account_no) + "'/0" if MAINNET else "44'/165'/" + str(
                    account_no) + "'/0"

            if TYPE_HW_WALLET.lower().startswith("ledgernanos"):

                try:

                    print('**** ====> account_no : %s' % i)

                    for i in range(max_gab):
                        addr_path = bip32_path + '/' + str(i)
                        nodedata = client.getWalletPublicKey(addr_path)
                        address = (nodedata.get('address')).decode("utf-8")

                        addr_balance = round(
                            Decimal(
                                getaddressbalancewithoutexcept(
                                    address, access) / 1e8), 8)

                        print(coin_name + ' address: ' +
                              '{:20}'.format(addr_path) + ' ' + address + ' ' +
                              '{:13.8f}'.format(addr_balance))
                    print()

                except AssertionError as e:
                    err_msg = str(e.args)
                    print_err_exit(get_caller_name(), get_function_name(),
                                   err_msg)

                except Exception as e:
                    err_msg = str(e.args)
                    print_err_exit(get_caller_name(), get_function_name(),
                                   err_msg)

                except KeyboardInterrupt:
                    print_err_exit(get_caller_name(), get_function_name(),
                                   "KeyboardInterrupt")

            else:
                keypath = bip32_path

                try:
                    #bip32_path = client.expand_path(keypath)
                    # xpub = bip32.serialize(
                    #    client.get_public_node(bip32_path).node,
                    #    (0x0488B21E if MAINNET else 0x043587CF))

                    print('**** ====> account_no : %s' % i)

                    for i in range(max_gab):
                        child_path = '%s%s' % (keypath + '/', str(i))
                        address = client.get_address(
                            coin_name, client.expand_path(child_path))
                        publicnode = client.get_public_node(
                            client.expand_path(
                                child_path)).node.public_key.hex()

                        addr_balance = round(
                            Decimal(
                                getaddressbalancewithoutexcept(
                                    address, access) / 1e8), 8)

                        print(coin_name + ' address: ' +
                              '{:20}'.format(child_path) + ' ' + address +
                              ' ' + '{:13.8f}'.format(addr_balance))

                except AssertionError as e:
                    err_msg = str(e.args)
                    print_err_exit(get_caller_name(), get_function_name(),
                                   err_msg)

                except Exception as e:
                    err_msg = str(e.args)
                    print_err_exit(get_caller_name(), get_function_name(),
                                   err_msg)

                except KeyboardInterrupt:
                    print_err_exit(get_caller_name(), get_function_name(),
                                   "KeyboardInterrupt")

    else:
        print('--> enter at leat one account_number')
        sys.exit()
コード例 #9
0
from bitcoinrpc.authproxy import AuthServiceProxy

#Génère un block depuis chaque noeud
for x in range(1, 4):
    access = AuthServiceProxy("http://*****:*****@172.17.0."+str(x+1)+":18332")
    access.generate(1)
コード例 #10
0
    def check_conflicts(self):
        has_conflicts = False
        heading_font = QFont("Arial", 10)
        self.dialog = QDialog()
        connection = AuthServiceProxy("http://%s:%[email protected]:8374" %
                                      (rpcuser, rpcpassword))

        v_box = QVBoxLayout()

        same_iscc = connection.liststreamkeyitems('test_iscc', self.iscc)
        if len(same_iscc) > 0:
            heading = QLabel("Same ISCC:")
            heading.setFont(heading_font)
            v_box.addWidget(heading)
            has_conflicts = True
            for iscc_entry in same_iscc:
                v_box.addWidget(QLabel("Key: {}".format(iscc_entry['key'])))
                v_box.addWidget(
                    QLabel("Data: {}".format(
                        codecs.decode(iscc_entry['data'],
                                      'hex').decode('ascii'))))
                v_box.addWidget(
                    QLabel("Publishers: {}".format(", ".join(
                        self.get_node_alias(iscc_entry['publishers'])))))

        names = ['Meta', 'Content', 'Data', 'Instance']
        conflicts = [list(), list(), list(), list()]
        other_iscc = connection.liststreamitems('test_iscc')
        for iscc in other_iscc:
            key = iscc['key']
            if len(key.split('-')) != 4:
                continue
            if key != self.iscc:
                for i in range(4):
                    if key.split('-')[i] == self.iscc.split('-')[i]:
                        conflicts[i].append(key)
        for i, conflict_items in enumerate(conflicts):
            if len(conflict_items) > 0:
                has_conflicts = True
                heading = QLabel("Conflicts in {}-ID:".format(names[i]))
                heading.setFont(heading_font)
                v_box.addWidget(heading)
                for conflict_key in conflict_items:
                    for iscc_entry in connection.liststreamkeyitems(
                            'test_iscc', conflict_key):
                        v_box.addWidget(
                            QLabel("Key: {}".format(iscc_entry['key'])))
                        v_box.addWidget(
                            QLabel("Data: {}".format(
                                codecs.decode(iscc_entry['data'],
                                              'hex').decode('ascii'))))
                        v_box.addWidget(
                            QLabel("Publishers: {}".format(", ".join(
                                self.get_node_alias(
                                    iscc_entry['publishers'])))))

        if has_conflicts:
            tmp = QWidget()
            tmp.setLayout(v_box)
            scrollarea = QScrollArea()
            scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            scrollarea.setWidget(tmp)
            main_v_box = QVBoxLayout()
            main_v_box.addWidget(scrollarea)

            button_h_box = QHBoxLayout()
            btn_add_extra = QPushButton("Add Extra")
            btn_add_extra.clicked.connect(self.do_add_extra)
            button_h_box.addWidget(btn_add_extra)
            btn_accept_conflict = QPushButton("Accept Conflict")
            btn_accept_conflict.clicked.connect(self.do_accept_conflict)
            button_h_box.addWidget(btn_accept_conflict)
            main_v_box.addLayout(button_h_box)

            self.dialog.setLayout(main_v_box)
            self.dialog.setWindowTitle('Conflicts')
            self.dialog.exec_()
        else:
            return True
コード例 #11
0
         )  # Change working dir - tells script where Zeronet install is.

# Parameters to sign and publish
command_sign_publish = [
    sys.executable, "zeronet.py", "siteSign", "--publish", config["site"],
    config["privatekey"]
]
if sys.platform == 'win32':
    command_sign_publish = ['"%s"' % param for param in command_sign_publish]

# Initialize rpc connection
rpc_auth, rpc_timeout = initRpc(namecoin_location + "namecoin.conf")

if not config["lastprocessed"]:  # Start processing from last block
    config["lastprocessed"] = int(
        AuthServiceProxy(rpc_auth, timeout=rpc_timeout).getinfo()["blocks"])

# processBlock(223911) # Testing zeronetwork.bit
# processBlock(227052) # Testing brainwallets.bit
# processBlock(236824) # Utf8 domain name (invalid should skip)
# processBlock(236752) # Uppercase domain (invalid should skip)
# processBlock(236870) # Encoded domain (should pass)
# sys.exit(0)

while 1:
    print "Waiting for new block"
    sys.stdout.flush()
    while 1:
        try:
            rpc = AuthServiceProxy(rpc_auth, timeout=rpc_timeout)
            if (int(rpc.getinfo()["blocks"]) > config["lastprocessed"]):
コード例 #12
0
ファイル: trade-api.py プロジェクト: bhok/alexandria-tradebot
def get_flo_balance():
    access = AuthServiceProxy("http://%s:%[email protected]:%s" % (app.config['CURRENCY_B_RPC_USER'], app.config['CURRENCY_B_RPC_PASSWORD'], app.config['CURRENCY_B_RPC_PORT']))
    balance = access.getbalance("tradebot")
    return balance
コード例 #13
0
ファイル: trade-api.py プロジェクト: bhok/alexandria-tradebot
def get_btc_address():
    access = AuthServiceProxy("http://%s:%[email protected]:%s" % (app.config['RPC_USER'], app.config['RPC_PASSWORD'], app.config['RPC_PORT']))
    print(access.getinfo())
    address = access.getnewaddress()
    return address
コード例 #14
0
ファイル: otc_mp.py プロジェクト: kimSooHyun950921/Heuristics
def get_rpc():
    return AuthServiceProxy(f'http://{rpc_user}:{rpc_password}@{rpc_ip}:{rpc_port}', timeout=timeout)
コード例 #15
0
def withdrawSVC():
    # return json.dumps({
    # 	'status': 'error',
    # 	'message': 'Coming Soon'
    # })
    if session.get(u'logged_in') is None:
        return json.dumps({'status': 'error', 'message': 'Please Login'})
    else:

        if request.method == 'POST':

            user_id = session.get('user_id')
            uid = session.get('uid')
            user = db.users.find_one({'_id': ObjectId(user_id)})

            sva_address = request.form['sva_address']
            rpc_connection = AuthServiceProxy(
                "http://*****:*****@127.0.0.1:23321"
            )
            response_dict = rpc_connection.validateaddress(sva_address)
            print response_dict

            # url_api = 'http://192.254.72.34:38058/apisva/validateaddress/%s' %(sva_address)
            # r = requests.get(url_api)
            # response_dict = r.json()
            if response_dict['isvalid'] != True:
                return json.dumps({
                    'status': 'error',
                    'message': 'Please enter a valid address!'
                })
            # valid = rpc_connection.validateaddress(sva_address)
            # if valid['isvalid'] == False:
            # 	return json.dumps({
            # 		'status': 'error',
            # 		'message': 'Please enter valid SVA address'
            # 	})

            checkIsNumber = is_number(request.form['sva_amount'])
            if request.form[
                    'sva_amount'] == '' or checkIsNumber == False or float(
                        request.form['sva_amount']) < 50:
                return json.dumps({
                    'status':
                    'error',
                    'message':
                    'Please enter valid quantity (quantity > 50)'
                })

            password = request.form['password']
            if check_password(user['password'], password) == False:
                return json.dumps({
                    'status': 'error',
                    'message': 'Wrong password'
                })
            sva_amount = float(request.form['sva_amount'])
            sva_amount = round(sva_amount, 8)
            sva_balance = user['sva_balance']
            if float(sva_balance) < float(sva_amount):
                return json.dumps({
                    'status':
                    'error',
                    'message':
                    'Please enter valid quantity (Maximum %s XVG)' %
                    (sva_balance)
                })

            onetime = request.form['one_time_password']
            checkVerifY = verify_totp(onetime, user['secret_2fa'])
            if checkVerifY == False:
                msg = 'The two-factor authentication code you specified is incorrect. Please check the clock on your authenticator device to verify that it is in sync'
                return json.dumps({'status': 'error', 'message': msg})

            new_sva_balance = float(sva_balance) - float(sva_amount)
            new_sva_balance = round(new_sva_balance, 2)
            db.users.update({"_id": ObjectId(user_id)},
                            {'$set': {
                                "sva_balance": new_sva_balance
                            }})
            localtime = time.localtime(time.time())
            customer_id = '%s%s%s%s%s%s' % (
                localtime.tm_mon, localtime.tm_year, localtime.tm_mday,
                localtime.tm_hour, localtime.tm_min, localtime.tm_sec)
            code_active = customer_id + id_generator()
            data_history = {
                'uid': uid,
                'user_id': user_id,
                'username': user['username'],
                'amount': float(sva_amount),
                'type': 'send',
                'wallet': 'XVG',
                'date_added': datetime.utcnow(),
                'detail': 'Send %s XVG from XVG Wallet' % (sva_amount),
                'rate': '',
                'txtid': '',
                'amount_sub': 0,
                'amount_add': 0,
                'amount_rest': 0
            }
            id_history = db.historys.insert(data_history)
            data_withdraw = {
                'uid': uid,
                'user_id': user_id,
                'username': user['username'],
                'amount': float(sva_amount) - 0.5,
                'tx': '',
                'status': 0,
                'date_added': datetime.utcnow(),
                'wallet': sva_address,
                'type': 'XVG',
                'code_active': code_active,
                'active_email': 0
            }
            id_withdraw = db.withdrawas.insert(data_withdraw)
            code_active = '%s_%s' % (id_withdraw, code_active)
            print code_active
            link_active = 'http://worldtrader.info/account/activewithdraw/%s' % (
                code_active)
            send_mail_withdraw_sva(user['email'], sva_amount, ' XVG Coin',
                                   sva_address, link_active)
            # send_mail_withdraw(user['email'], user['username'], link_active)
            return json.dumps({
                'status': 'success',
                'new_sva_balance': new_sva_balance,
                'message': 'Withdraw success'
            })
コード例 #16
0
def main():
    parser = argparse.ArgumentParser()
    requiredNamed = parser.add_argument_group('required arguments')
    requiredNamed.add_argument("-d",
                               "--destinationaddr",
                               dest="dest_addr",
                               type=str,
                               required=True,
                               help="ZEN address to send to")
    parser.add_argument(
        "-f",
        "--fromaddr",
        dest="from_addr",
        nargs="+",
        default=[],
        required=False,
        help=
        "ZEN addresses to send from, space separated e.g. \"-f addr1 addr2\"")
    parser.add_argument(
        "--min-conf",
        dest="min_conf",
        nargs="?",
        type=int,
        default=1,
        const=1,
        required=False,
        help=
        "minumum number of confirmations to pass to listunspent (default 1)")
    requiredNamed.add_argument("-u",
                               "--rpc-user",
                               dest="rpc_user",
                               type=str,
                               required=True,
                               help="zend RPC username")
    requiredNamed.add_argument("-p",
                               "--rpc-password",
                               dest="rpc_pass",
                               type=str,
                               required=True,
                               help="zend RPC password")
    requiredNamed.add_argument(
        "-r",
        "--rpc-url",
        dest="rpc_url",
        type=str,
        required=True,
        help="zend RPC interface to connect to, e.g. \"http://127.0.0.1:8231\""
    )
    parser.add_argument(
        "-t",
        "--rpc-timeout",
        dest="rpc_timeout",
        nargs="?",
        type=int,
        default=300,
        const=300,
        required=False,
        help="timeout for RPC requests in seconds (default 300)")
    parser.add_argument(
        "-l",
        "--limit-vin",
        dest="limit_vin",
        nargs="?",
        type=int,
        default=300,
        const=300,
        required=False,
        help="utxo inputs per transaction (default 300, max 600)")
    parser.add_argument("--debug",
                        dest="debug",
                        action="store_true",
                        required=False,
                        help="print debug messages")

    args = parser.parse_args()
    DEST_ADDR = args.dest_addr
    FROM_ADDR = args.from_addr
    MIN_CONF = args.min_conf
    RPC_URL = args.rpc_url
    creds = ""
    if args.rpc_user:
        creds = args.rpc_user
        if args.rpc_pass:
            creds += ":" + args.rpc_pass
        creds += "@"
    if creds:
        RPC_URL = RPC_URL.split("/", 2)[0] + "//" + creds + RPC_URL.split(
            "/", 2)[2]
    RPC_TIMEOUT = args.rpc_timeout
    LIMIT_VIN = min(args.limit_vin, 600)
    DEBUG = args.debug

    if DEBUG:
        logging.basicConfig()
        logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)
        print(
            "DEST_ADDR: %s, FROM_ADDR: %s, MIN_CONF: %d, RPC_URL: %s, RPC_TIMEOUT: %d, LIMIT_VIN: %d"
            %
            (DEST_ADDR, FROM_ADDR, MIN_CONF, RPC_URL, RPC_TIMEOUT, LIMIT_VIN))

    rpc_connection = AuthServiceProxy(RPC_URL, timeout=RPC_TIMEOUT)
    all_unspent = rpc_connection.listunspent(MIN_CONF, MAX_CONF, FROM_ADDR)
    spendable_utxo = filter_unspendable(all_unspent)
    # sort by amount, low to high
    spendable_utxo_sorted = sorted(spendable_utxo, key=lambda i: i["amount"])
    utxo_by_address = group_by_address(spendable_utxo_sorted)

    commands = OrderedDict()
    for address, utxos in utxo_by_address.items():
        n = LIMIT_VIN
        # split into chunks of LIMIT_VIN size
        chunks = [
            utxos[i * n:(i + 1) * n] for i in range((len(utxos) + n - 1) // n)
        ]
        for chunk in chunks:
            amount = Decimal("0")
            for utxo in chunk:
                amount += utxo["amount"]
            warning = ""
            if amount - FEE < DUST_THRESHOLD or amount - FEE < FEE:
                warning = "#Error: Transaction output below dust threshold or smaller than fee"
            command = (
                warning + "OPID=$(zen-cli z_sendmany \"" + address +
                "\" '[{\"address\": \"" + DEST_ADDR + "\", \"amount\": " +
                str(amount - FEE) + "}]' " + str(MIN_CONF) + " " + str(FEE) +
                "); sleep 5 && zen-cli z_getoperationstatus '[\"'" +
                "$OPID'\"]'; echo -e \"\\n\\nPlease verify that the output contains \\\"status\\\": \\\"success\\\".\\n\\nIf this is not the case,"
                +
                " please run the python script again and retry with the same address or a different address.\\n\" && read -p "
                + "\"Press enter to continue.\"")
            if address in commands.keys():
                commands[address].append(command)
            else:
                commands.update({address: [command]})

    for address, cmds in commands.items():
        print("#")
        print("#Commands for address: " + address)
        for i in range(len(cmds)):
            print("#Transaction " + str(i + 1) + ":")
            print(cmds[i])
コード例 #17
0
ファイル: mogwaid.py プロジェクト: mogwaicoin/mogwai-sentinel
 def rpc_connection(self):
     return AuthServiceProxy("http://{0}:{1}@{2}:{3}".format(*self.creds))
コード例 #18
0
def channelpage():
    try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        chain_type = rpc_connect.getblockchaininfo()['chain']
        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"
        os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
        with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
            macaroon_bytes = f.read()
            macaroon = codecs.encode(macaroon_bytes, 'hex')

        cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
        creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel('localhost:10009', creds)
        stub = lnrpc.LightningStub(channel)

        response = stub.ListChannels(ln.ListChannelsRequest(), metadata=[('macaroon', macaroon)])
        walbal = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)])
        availablefunds = walbal.confirmed_balance
        channellist = response.channels
        closedchannelidentifiers = []
        channelidentifiers = []
        pendingchannelidentifiers = []

        pendingresponse = stub.PendingChannels(ln.PendingChannelsRequest(), metadata=[('macaroon', macaroon)])
        pend = pendingresponse.pending_open_channels
        for i in pend:
          k = ((str(i.channel.remote_node_pub)), str(i.channel.channel_point), int(i.channel.capacity), int(i.channel.local_balance))
          pendingchannelidentifiers.append(k)
        length_of_pending = len(pendingchannelidentifiers)

        closedresponse = stub.ClosedChannels(ln.ClosedChannelsRequest(), metadata=[('macaroon', macaroon)])
        for i in closedresponse.channels:
         p = (str(i.remote_pubkey), str(i.channel_point), int(i.capacity), int(i.close_height), int(i.settled_balance))
         closedchannelidentifiers.append(p)
        length_of_closed = len(closedchannelidentifiers)

        for i in channellist:
         if i.active == True:
          k = (str(i.remote_pubkey), int(i.capacity), int(i.local_balance), int(i.remote_balance), int(i.commit_fee), str(i.channel_point))
          channelidentifiers.append(k)
        conn = True
        length_of = len(channelidentifiers)
        try:
         outcap = sum(zip(*channelidentifiers)[2])
         incap = sum(zip(*channelidentifiers)[3])
        except:
         outcap = incap = 0
         length_of = 0


    except:
        conn = False

    if conn == True:
      if request.method == "POST":
        if request.form['action'] == "openchan":
              try:
                pkstring = str(request.form['channelpubkey'])
                locfundamt = int(request.form['channelamt'])
                response = stub.OpenChannelSync(ln.OpenChannelRequest(node_pubkey_string=pkstring, local_funding_amount=locfundamt, push_sat=0), metadata=[('macaroon', macaroon)])
                if response.funding_txid_bytes:
                  return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                   outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)   
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                   outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
        elif request.form['action'] == "closechan":
              try:
                return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey']))
                stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint), metadata=[('macaroon', macaroon)])
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
        elif request.form['action'] == "fclosechan":
              try:
                return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey']))
                stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint, force=True), metadata=[('macaroon', macaroon)])
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
      else:
        return render_template('channels.html', conn=conn, length_of=length_of, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, incap=incap,
     outcap=outcap, availablefunds=availablefunds, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)

    return render_template('channels.html', conn=conn, length_of=0, channelidentifiers=0, closedchannelidentifiers=0, incap=0,
     outcap=0, availablefunds=0, length_of_closed=0, pendingchannelidentifiers=0, length_of_pending=0)
コード例 #19
0
def get_rpc_connection():
    from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
    connection = "http://%s:%[email protected]:%s" % (rpc_user, rpc_pass, rpc_port)
    rpc_conn = AuthServiceProxy(connection)
    return (rpc_conn)
コード例 #20
0
def makepayment():
     try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        current_block_height = rpc_connect.getblockcount()
        onchain_peers = rpc_connect.getconnectioncount()
        chain_type = rpc_connect.getblockchaininfo()['chain']
        onchain_balance = rpc_connect.getbalance()
        fasttx = rpc_connect.estimatesmartfee(2)
        medtx = rpc_connect.estimatesmartfee(6)
        slowtx = rpc_connect.estimatesmartfee(12)

        newaddress = rpc_connect.getnewaddress()
        packqraddr = pyqrcode.create(newaddress)
        packqraddr.svg("app/static/img/newaddress.svg", scale=8)

        if chain_type == "main":
            fasttxrate = u"~₿ " + str(fasttx['feerate'])
            medtxrate = u"~₿ " + str(medtx['feerate'])
            slowtxrate = u"~₿ " + str(slowtx['feerate'])
        else:
            fasttxrate = u"~t₿ " + str(fasttx['feerate'])
            medtxrate = u"~t₿ " + str(medtx['feerate'])
            slowtxrate = u"~t₿ " + str(slowtx['feerate'])

        if onchain_balance > 0 and chain_type == "main":
            onchain_balance = u"₿ " + str(onchain_balance)
        elif onchain_balance == 0:
            onchain_balance = u"₿ " + str(0)
        elif onchain_balance > 0 and chain_type == "test":
            onchain_balance = u"t₿ " + str(onchain_balance)        
        else:
            onchain_balance = u"t₿ " + str(0)
        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"

        conn = True
     except:
        onchain_balance = "Offline!"
        fasttxrate, medtxrate, slowtxrate = "", "", ""
        conn = False

     try:
      os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
      with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
        macaroon_bytes = f.read()
        macaroon = codecs.encode(macaroon_bytes, 'hex')
      cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
      creds = grpc.ssl_channel_credentials(cert)
      channel = grpc.secure_channel('localhost:10009', creds)
      stub = lnrpc.LightningStub(channel)

      satbalance = stub.ChannelBalance(ln.ChannelBalanceRequest(), metadata=[('macaroon', macaroon)])
      offchain_balance = u"ş " + str(format(satbalance.balance,','))

      lninvoice = (stub.AddInvoice(ln.Invoice(), metadata=[('macaroon', macaroon)])).payment_request
      packlnaddr = pyqrcode.create(lninvoice)
      packqraddr.svg("app/static/img/lninvoice.svg", scale=8)

     except:
      offchain_balance = "Offline!"

     if conn == True:
      if request.method == 'POST':
        if request.form['action'] == "sendbutton":
          if request.form['fee'] == "medfee":
            try:
              txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, medtx['blocks'])

              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
            except:

              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)

          elif request.form['fee'] == "highfee":
            try:
              txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, fasttx['blocks'])

              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
            except:

              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) 
          elif request.form['fee'] == "lowfee":
            try:
              txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, slowtx['blocks'])

              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
            except:
              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)

        if request.form['action'] == "decodereq":
            try:
              os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
              with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
                macaroon_bytes = f.read()
                macaroon = codecs.encode(macaroon_bytes, 'hex')
              cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
              creds = grpc.ssl_channel_credentials(cert)
              channel = grpc.secure_channel('localhost:10009', creds)
              stub = lnrpc.LightningStub(channel)
              if len(request.form['reqtext']) > 20:
                req_whole = request.form['reqtext']
                decoded_req = stub.DecodePayReq(ln.PayReqString(pay_req=req_whole), metadata=[('macaroon', macaroon)])
                req_desc = decoded_req.description
                req_amt = u"ş " + str(format(decoded_req.num_satoshis,','))
                req_to = decoded_req.destination
                with open("invoice.txt",'wb') as invoicefile:
                 invoicefile.write(req_whole)
                 invoicefile.close()
                return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", req_desc=req_desc, req_amt=req_amt, req_to=req_to, switch=True, offchain_balance=offchain_balance, req_whole=req_whole, newaddress=newaddress, lninvoice=lninvoice)
              else:
                return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", switch=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
            except:
              return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", switch=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
        if request.form['action'] == "confirmbutton":
            try:
              os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
              with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
                macaroon_bytes = f.read()
                macaroon = codecs.encode(macaroon_bytes, 'hex')
              cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
              creds = grpc.ssl_channel_credentials(cert)
              channel = grpc.secure_channel('localhost:10009', creds)
              stub = lnrpc.LightningStub(channel)
              with open("invoice.txt",'r') as invoicefile:
                invoice_confirmed = invoicefile.read()    

              try:
               result = stub.SendPaymentSync(ln.SendRequest(payment_request=str(invoice_confirmed)), metadata=[('macaroon', macaroon)])
               if result.payment_error:
                 return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, successln=False, error=result.payment_error, newaddress=newaddress, lninvoice=lninvoice)
               else:
                return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, successln=True, preimage=hexlify(result.payment_preimage), newaddress=newaddress, lninvoice=lninvoice)
              except:
                return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
            except:
                return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
        
      else:
        return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice)
     return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance)
コード例 #21
0
    def do(self):
        rpc = AuthServiceProxy('http://' + settings.BITCOIN_RPC_USERNAME +
                               ':' + settings.BITCOIN_RPC_PASSWORD + '@' +
                               settings.BITCOIN_RPC_IP + ':' +
                               str(settings.BITCOIN_RPC_PORT))

        # Send all outgoing transactions that are ready to go
        otxs_to_send = OutgoingTransaction.objects.filter(
            inputs_selected_at__isnull=False, sent_at=None)
        for otx in otxs_to_send:
            # Gather inputs argument
            inputs = []
            for inpt in otx.inputs.all():
                inputs.append({
                    'txid': inpt.bitcoin_txid,
                    'vout': inpt.bitcoin_vout,
                })
            # Gather outputs argument
            outputs = {}
            for output in otx.outputs.all():
                outputs.setdefault(output.bitcoin_address, Decimal(0))
                outputs[output.bitcoin_address] += output.amount
            # Use arguments to create, sign and send raw transaction
            raw_tx = rpc.createrawtransaction(inputs, outputs)
            signing_result = rpc.signrawtransaction(raw_tx)
            raw_tx_signed = signing_result['hex']
            if signing_result['complete']:
                # Calculate how much fee each wallet needs to pay. Each
                # sender pays average fee from every outgoing transaction
                # it has, however rounding is done in a way that the
                # total sum is exatcly the same as the total fee.
                fees_for_wallets = []
                fees_to_pay_left = otx.calculateFee()
                fee_payers_left = otx.txs.count()
                if fees_to_pay_left:
                    txs_count = len(otx.txs.all())
                    for tx in otx.txs.all():
                        # Calculate fee for this payer
                        assert fee_payers_left > 0
                        fee = (fees_to_pay_left / fee_payers_left).quantize(
                            Decimal('0.00000001'), rounding=ROUND_HALF_UP)
                        fee_payers_left -= 1
                        fees_to_pay_left -= fee
                        if fee > 0:
                            # Mark fee paying to correct wallet
                            wallet_found = False
                            for fee_for_wallet in fees_for_wallets:
                                if fee_for_wallet['wallet'] == tx.wallet:
                                    fee_for_wallet['amount'] += fee
                                    wallet_found = True
                            if not wallet_found:
                                fees_for_wallets.append({
                                    'wallet': tx.wallet,
                                    'amount': fee,
                                })
                    assert fee_payers_left == 0
                assert fees_to_pay_left == Decimal(0)

                rpc.sendrawtransaction(raw_tx_signed)

                # Atomically mark outgoing transaction as sent and
                # add fee paying transactions to sending wallets.
                with transaction.atomic():
                    otx.sent_at = now()
                    otx.save(update_fields=['sent_at'])

                    for fee_for_wallet in fees_for_wallets:
                        wallet = fee_for_wallet['wallet']
                        amount = fee_for_wallet['amount']

                        # Create fee paying transaction
                        Transaction.objects.create(
                            wallet=wallet,
                            amount=str(-amount),
                            description='Fee from sent Bitcoins',
                            outgoing_tx=otx,
                        )

            elif signing_result.get('errors'):
                raise Exception('Unable to sign outgoing transaction!')

        # Get all outgoing transactions that do not have any inputs selected
        otxs_without_inputs = OutgoingTransaction.objects.filter(
            inputs_selected_at=None)

        # If all outgoing transactions are fine, then do nothing more
        if otxs_without_inputs.count() == 0:
            return

        # TODO: Some lock here might be a good idea, just to be sure!

        # List all unspent outputs that aren't already assigned to some outgoing transaction
        unspent_outputs_raw = rpc.listunspent(settings.CONFIRMED_THRESHOLD)
        unspent_outputs = []
        for unspent_output in unspent_outputs_raw:
            txid = unspent_output['txid']
            vout = unspent_output['vout']

            if unspent_output['spendable']:

                # If there is no existing input, then this output isn't assigned yet
                if OutgoingTransactionInput.objects.filter(
                        bitcoin_txid=txid, bitcoin_vout=vout).count() == 0:
                    unspent_outputs.append(unspent_output)

        # Assign inputs to those transactions that do not have them set
        for otx in otxs_without_inputs:
            # Calculate how much is being sent
            outputs_total = otx.outputs.aggregate(
                Sum('amount'))['amount__sum'] or Decimal(0)

            # Calculate fee
            tx_size = 148 * otx.inputs.count() + 34 * (otx.outputs.count() +
                                                       1) + 10
            fee = Decimal(get_fee_in_satoshis_per_byte()) * Decimal(
                tx_size) * Decimal('0.00000001')
            fee = fee.quantize(Decimal('0.00000001'))

            # Now assign inputs until there is enough for outputs
            inputs_total = otx.inputs.aggregate(
                Sum('amount'))['amount__sum'] or Decimal(0)
            while inputs_total < outputs_total + fee and len(
                    unspent_outputs) > 0:
                # Find unspent output that has most confirmations
                best_unspent_output = None
                best_unspent_output_i = None
                best_unspent_output_confirmations = 0
                for unspent_outputs_i in range(len(unspent_outputs)):
                    unspent_output = unspent_outputs[unspent_outputs_i]
                    if unspent_output[
                            'confirmations'] > best_unspent_output_confirmations:
                        best_unspent_output = unspent_output
                        best_unspent_output_i = unspent_outputs_i
                        best_unspent_output_confirmations = unspent_output[
                            'confirmations']

                # Assign this unspent output as input
                OutgoingTransactionInput.objects.create(
                    tx=otx,
                    amount=best_unspent_output['amount'],
                    bitcoin_txid=best_unspent_output['txid'],
                    bitcoin_vout=best_unspent_output['vout'],
                )
                inputs_total += best_unspent_output['amount']

                # Recalculate fee
                tx_size += 148
                fee = Decimal(get_fee_in_satoshis_per_byte()) * Decimal(
                    tx_size) * Decimal('0.00000001')
                fee = fee.quantize(Decimal('0.00000001'))

                # Remove the best output from unspent outputs
                del unspent_outputs[best_unspent_output_i]

            # If there was no suitable unspent outputs, then it means hot wallet does not
            # have enough funds for this transaction. We have to give up. Already assigned
            # inputs are, however, not cleared. Because of this, we have to give up
            # totally, because this transaction wasted rest of the available outputs.
            if inputs_total < outputs_total + fee:
                break

            # Calculate how much extra there is, and send it back to some of the change
            # addresses. If the system fails right after this operation, it doesn't matter,
            # because the inputs and outputs have perfect match, and next runs will do
            # nothing but set the "inputs_selected_at" timestamp.
            extra_amount = inputs_total - (outputs_total + fee)
            if extra_amount > Decimal(0):
                change_wallet = get_or_create_internal_wallet(
                    INTERNAL_WALLET_CHANGE)
                change_address = change_wallet.getUnusedAddress()
                OutgoingTransactionOutput.objects.create(
                    tx=otx,
                    amount=extra_amount,
                    bitcoin_address=change_address.address)

            # Enough inputs was assigned, so marking this transaction fully assigned
            otx.inputs_selected_at = now()
            otx.save(update_fields=['inputs_selected_at'])
コード例 #22
0
def peerpage():
    try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        chain_type = rpc_connect.getblockchaininfo()['chain']
        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"
        os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
        with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
            macaroon_bytes = f.read()
            macaroon = codecs.encode(macaroon_bytes, 'hex')

        cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
        creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel('localhost:10009', creds)
        stub = lnrpc.LightningStub(channel)

        pbks = stub.ListChannels(ln.ListChannelsRequest(), metadata=[('macaroon', macaroon)])
        pubkey_list = [str(i.remote_pubkey) for i in pbks.channels]

        response = stub.ListPeers(ln.ListPeersRequest(), metadata=[('macaroon', macaroon)])
        show_current_peers = response.peers
        show_current_peers_list = []
        for peer in show_current_peers:
            if peer.pub_key in pubkey_list:
              show_current_peers_list.append((str(peer.pub_key), True))
            else:
              show_current_peers_list.append((str(peer.pub_key), False))
        conn = True
        length_of = len(show_current_peers_list)

    except:
        show_current_peers_list = ["Offline!"]
        length_of = 0
        conn = False
        pubkey_list = ["Offline!"]

    if conn == True:
      if request.method == 'POST':
        if request.form['action'] == "connectbutton":
          if len(request.form['text']) > 10:
            response_uri = str(request.form['text'])
            result = response_uri.strip()

            def connect(host, port, node_id):
               addr = ln.LightningAddress(pubkey=node_id, host="{}:{}".format(host, port))
               req = ln.ConnectPeerRequest(addr=addr, perm=True)
               stub.ConnectPeer(ln.ConnectPeerRequest(addr=addr,perm=False), metadata=[('macaroon',macaroon)])
            try:
               nodeid, lnhost, lnport = result[:66], result[67:-5], result[-4:]
               connect(lnhost,lnport,nodeid)
               show_current_peers_list.append((nodeid, False))
               length_of = len(show_current_peers_list)
               result = "Successfully connected!"
               return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="SuccessCon", conn=conn)
            except:
               return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseCon", conn=conn)
          else:
            return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseCon", conn=conn)
        else:
          if len(request.form['text']) > 10:
            response_uri = str(request.form['text'])
            result = response_uri.strip()
            def disconnect(pubkey):
                req = ln.DisconnectPeerRequest(pub_key=pubkey)
                stub.DisconnectPeer(ln.DisconnectPeerRequest(pub_key=pubkey), metadata=[('macaroon',macaroon)])
            try:
                disconnect(result)
                del show_current_peers_list[-1]
                length_of = len(show_current_peers_list)
                return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="SuccessDis", conn=conn)
            except:
                return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseDis", conn=conn)
          else:
            return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseDis", conn=conn)
    return render_template('peerpage.html', len=len(show_current_peers_list), length_of=length_of, show_current_peers=show_current_peers_list, conn=conn)               
コード例 #23
0
from bitcoinrpc.authproxy import AuthServiceProxy
import util
import log

rpc_user = "******"
rpc_password = "******"
url = "http://{}:{}@127.0.0.1:6888".format(rpc_user, rpc_password)
# rpc_user and rpc_password are set in the bitcoin.conf file
rpc = AuthServiceProxy(url, timeout=3)


def get_address_by_account_name(_account_name):
    address_list = rpc.getaddressesbyaccount(_account_name)
    if len(address_list) == 0:
        return None
    else:
        return address_list[0]


def create_new_address(_account_name):
    address = rpc.getaccountaddress(_account_name)
    return address


def get_or_create_address(_account_name):
    address = get_address_by_account_name(_account_name)
    if address is None:
        address = create_new_address(_account_name)
    return address

コード例 #24
0
    async def tip(self, ctx, mention=None, amount=None):
        client = AuthServiceProxy(rpc_connection)
        user_id = str(ctx.author.id)

        if not user_db.check_user(user_id):
            embed = discord.Embed(title="**For first-use-user**",
                                  color=0x0043ff)
            embed.set_author(name=ctx.author.display_name,
                             icon_url=ctx.author.avatar_url_as(format='png',
                                                               size=256))
            embed.add_field(name="First of all, please type `//help`",
                            value="Welcome to world of CPUchain tipbot !")
            embed.set_thumbnail(
                url=self.bot.user.avatar_url_as(format='png', size=1024))
            embed.set_footer(text="CPUchain tipbot {0} [Owner: {1}]".format(
                config.VERSION, self.bot.get_user(config.OWNER_ID)),
                             icon_url=self.bot.user.avatar_url_as(format='png',
                                                                  size=256))

            await ctx.channel.send(embed=embed)
        else:
            pass

            if mention is None or amount is None:
                embed = discord.Embed(color=0xffd800)
                embed.set_author(name=ctx.author.display_name,
                                 icon_url=ctx.author.avatar_url_as(
                                     format='png', size=256))
                embed.add_field(name="Please check `//help` ", value=" :mag: ")
                embed.set_footer(
                    text="CPUchain tipbot {0} [Owner: {1}]".format(
                        config.VERSION, self.bot.get_user(config.OWNER_ID)),
                    icon_url=self.bot.user.avatar_url_as(format='png',
                                                         size=256))
                await ctx.channel.send(embed=embed)
            elif not str_isfloat(amount):
                embed = discord.Embed(color=0xff0000)
                embed.set_author(name=ctx.author.display_name,
                                 icon_url=ctx.author.avatar_url_as(
                                     format='png', size=256))
                embed.add_field(name="invalid amount.",
                                value="`{0}`".format(amount))
                embed.set_footer(
                    text="CPUchain tipbot {0} [Owner: {1}]".format(
                        config.VERSION, self.bot.get_user(config.OWNER_ID)),
                    icon_url=self.bot.user.avatar_url_as(format='png',
                                                         size=256))

                await ctx.channel.send(embed=embed)
            else:
                pass

                tipfrom = str(ctx.author.id)
                tipto = str(mention.replace('<@',
                                            '').replace('>',
                                                        '')).replace('!', '')
                amount = Decimal(
                    str(float(amount))
                )  # Dealing with cases like "001.100", ".123" : "float(amount)"

                if amount < Decimal('0.00000001'):
                    embed = discord.Embed(color=0xff0000)
                    embed.set_author(name=ctx.author.display_name,
                                     icon_url=ctx.author.avatar_url_as(
                                         format='png', size=256))
                    embed.add_field(
                        name="amount must be at least 0.00000001 CPU",
                        value="`{0}`".format(amount))
                    embed.set_footer(
                        text="CPUchain tipbot {0} [Owner: {1}]".format(
                            config.VERSION,
                            self.bot.get_user(config.OWNER_ID)),
                        icon_url=self.bot.user.avatar_url_as(format='png',
                                                             size=256))

                    await ctx.channel.send(embed=embed)
                else:
                    if len(tipto) != 18 and len(
                            tipto
                    ) != 17:  # length of discord user id is 18 or 17
                        embed = discord.Embed(color=0xff0000)
                        embed.set_author(name=ctx.author.display_name,
                                         icon_url=ctx.author.avatar_url_as(
                                             format='png', size=256))
                        embed.add_field(name="invalid user.",
                                        value="`{0}`".format(str(mention)))
                        embed.set_footer(
                            text="CPUchain tipbot {0} [Owner: {1}]".format(
                                config.VERSION,
                                self.bot.get_user(config.OWNER_ID)),
                            icon_url=self.bot.user.avatar_url_as(format='png',
                                                                 size=256))

                        await ctx.channel.send(embed=embed)
                    elif tipfrom == tipto:
                        embed = discord.Embed(color=0xff0000)
                        embed.set_author(name=ctx.author.display_name,
                                         icon_url=ctx.author.avatar_url_as(
                                             format='png', size=256))
                        embed.add_field(name="You cannot tip to yourself.",
                                        value=" :thinking: ")
                        embed.set_footer(
                            text="CPUchain tipbot {0} [Owner: {1}]".format(
                                config.VERSION,
                                self.bot.get_user(config.OWNER_ID)),
                            icon_url=self.bot.user.avatar_url_as(format='png',
                                                                 size=256))

                        await ctx.channel.send(embed=embed)
                    elif amount > client.getbalance(tipfrom, config.CONFIRM):
                        embed = discord.Embed(color=0xff0000)
                        embed.set_author(name=ctx.author.display_name,
                                         icon_url=ctx.author.avatar_url_as(
                                             format='png', size=256))
                        embed.add_field(
                            name="You don't have enough balances.",
                            value="Your balances ```{0} CPU```".format(
                                client.getbalance(tipfrom, config.CONFIRM)))
                        embed.set_footer(
                            text="CPUchain tipbot {0} [Owner: {1}]".format(
                                config.VERSION,
                                self.bot.get_user(config.OWNER_ID)),
                            icon_url=self.bot.user.avatar_url_as(format='png',
                                                                 size=256))

                        await ctx.channel.send(embed=embed)
                    else:
                        if tipto == str(self.bot.user.id):
                            try:
                                move_istrue = client.move(
                                    tipfrom, 'tipcpu_wallet', float(amount))
                            except:
                                embed = discord.Embed(color=0xff0000)
                                embed.set_author(
                                    name=ctx.author.display_name,
                                    icon_url=ctx.author.avatar_url_as(
                                        format='png', size=256))
                                embed.add_field(
                                    name=
                                    "invalid amount.\n(You can not specify the einth decimal place or smaller than that.)",
                                    value="`{0}`".format(amount))
                                embed.set_footer(
                                    text="CPUchain tipbot {0} [Owner: {1}]".
                                    format(config.VERSION,
                                           self.bot.get_user(config.OWNER_ID)),
                                    icon_url=self.bot.user.avatar_url_as(
                                        format='png', size=256))

                                await ctx.channel.send(embed=embed)
                            if move_istrue:
                                embed = discord.Embed(color=0x0043ff)
                                embed.set_author(
                                    name=ctx.author.display_name,
                                    icon_url=ctx.author.avatar_url_as(
                                        format='png', size=256))
                                embed.add_field(
                                    name="Thank you for donating!",
                                    value="```{0} CPU```".format(amount))
                                embed.set_footer(
                                    text="CPUchain tipbot {0} [Owner: {1}]".
                                    format(config.VERSION,
                                           self.bot.get_user(config.OWNER_ID)),
                                    icon_url=self.bot.user.avatar_url_as(
                                        format='png', size=256))

                                await ctx.channel.send(embed=embed)
                        else:
                            try:
                                move_istrue = client.move(
                                    tipfrom, tipto, float(amount))
                            except:
                                embed = discord.Embed(color=0xff0000)
                                embed.set_author(
                                    name=ctx.author.display_name,
                                    icon_url=ctx.author.avatar_url_as(
                                        format='png', size=256))
                                embed.add_field(
                                    name=
                                    "invalid amount.\n(You can not specify the einth decimal place or smaller than that.)",
                                    value="`{0}`".format(amount))
                                embed.set_footer(
                                    text="CPUchain tipbot {0} [Owner: {1}]".
                                    format(config.VERSION,
                                           self.bot.get_user(config.OWNER_ID)),
                                    icon_url=self.bot.user.avatar_url_as(
                                        format='png', size=256))

                                await ctx.channel.send(embed=embed)
                            if move_istrue:
                                embed = discord.Embed(color=0x0043ff)
                                embed.set_author(
                                    name=ctx.author.display_name,
                                    icon_url=ctx.author.avatar_url_as(
                                        format='png', size=256))
                                embed.add_field(
                                    name="{0} tipped to {1} `{2} CPU`".format(
                                        ctx.author.display_name,
                                        self.bot.get_user(
                                            int(tipto)).display_name, amount),
                                    value="yay!")
                                embed.set_footer(
                                    text="CPUchain tipbot {0} [Owner: {1}]".
                                    format(config.VERSION,
                                           self.bot.get_user(config.OWNER_ID)),
                                    icon_url=self.bot.user.avatar_url_as(
                                        format='png', size=256))

                                await ctx.channel.send(embed=embed)
コード例 #25
0
from __future__ import division
import time
import hashlib
from bitstring import BitArray
from bitcoinrpc.authproxy import AuthServiceProxy
import psycopg2
from psycopg2.extras import Json
import os
from operator import itemgetter
from urllib2 import Request, urlopen
import simplejson as json

#print "sleeping"
#time.sleep(5)
#print "done sleeping"
access = AuthServiceProxy("http://<user>:<pass>@127.0.0.1:2240")
print "Current block count: ", access.getblockcount()
# AUTHOR: JOHNY GEORGES
# DATE: 29/04/2014
# HEXHASHREVERSER IS USED FOR PREV.BLOCK[v] HASH, MERKLE ROOT, BITS, RAW BLOCK[v] HASH ETC.
# GETDIFFICULT WILL SPIT OUT THE DIFFICULTY OF THE BLOCK
postgres = psycopg2.connect(database="bcexchange",
                            user="******",
                            port=5432,
                            password="******")
cursor = postgres.cursor()
d_cursor = postgres.cursor(cursor_factory=psycopg2.extras.RealDictCursor
                           )  #used for dictionary-like fetches.


def set2list(aSet):
コード例 #26
0
from bitcoinrpc.authproxy import AuthServiceProxy

access = AuthServiceProxy("http://*****:*****@172.17.0.3:18332")
#Genere 2000 blocks
access.generate(2000)


コード例 #27
0
ファイル: __init__.py プロジェクト: xeddmc/bitrisk
KVSessionExtension(store, app)
# add flask csrf middleware
csrf = SeaSurf(app)
# add rate limiting middleware
limiter = Limiter(app)
auth_limit = limiter.shared_limit("5/minute;1/second", scope="auth")

# connect to bitcoind
bitcoind_config = read_default_config(config.main.bitcoin_conf_filename)
testnet = ''
if bitcoind_config.has_key('testnet'):
    testnet = bitcoind_config['testnet']
rpc_user = bitcoind_config['rpcuser']
rpc_password = bitcoind_config['rpcpassword']
host = os.getenv('HOST', '127.0.0.1')
bitcoind_rpc_connection = AuthServiceProxy("http://%s:%s@%s:%s8332"%(rpc_user, rpc_password, host, testnet))

# random number generator
cryptogen = random.SystemRandom()

# image directory
image_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static/images')

# app contants
BETS = 'bets'
HOUSE_EDGE = 0.01
BET_MAX_FACTOR = 0.05

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String, unique=True)
コード例 #28
0
 def rpc_conn(cls, rpc_user, rpc_password, rpc_host, rpc_port):
     rpc_conn_obj = AuthServiceProxy(
         "http://%s:%s@%s:%s" %
         (rpc_user, rpc_password, rpc_host, rpc_port))
     return rpc_conn_obj
コード例 #29
0
def initialize_chain(test_dir):
    """
    Create (or copy from cache) a 200-block-long chain and
    4 wallets.
    othilad and othila-cli must be in search path.
    """

    if not os.path.isdir(os.path.join("cache", "node0")):
        devnull = open("/dev/null", "w+")
        # Create cache directories, run othilad:
        for i in range(4):
            datadir = initialize_datadir("cache", i)
            args = [
                os.getenv("BITCOIND", "othilad"), "-keypool=1",
                "-datadir=" + datadir, "-discover=0"
            ]
            if i > 0:
                args.append("-connect=127.0.0.1:" + str(p2p_port(0)))
            bitcoind_processes[i] = subprocess.Popen(args)
            subprocess.check_call([
                os.getenv("BITCOINCLI", "othila-cli"), "-datadir=" + datadir,
                "-rpcwait", "getblockcount"
            ],
                                  stdout=devnull)
        devnull.close()
        rpcs = []
        for i in range(4):
            try:
                url = "http://*****:*****@127.0.0.1:%d" % (rpc_port(i), )
                rpcs.append(AuthServiceProxy(url))
            except:
                sys.stderr.write("Error connecting to " + url + "\n")
                sys.exit(1)

        # Create a 200-block-long chain; each of the 4 nodes
        # gets 25 mature blocks and 25 immature.
        # blocks are created with timestamps 10 minutes apart, starting
        # at 1 Jan 2014
        block_time = 1388534400
        for i in range(2):
            for peer in range(4):
                for j in range(25):
                    set_node_times(rpcs, block_time)
                    rpcs[peer].setgenerate(True, 1)
                    block_time += 10 * 60
                # Must sync before next peer starts generating blocks
                sync_blocks(rpcs)

        # Shut them down, and clean up cache directories:
        stop_nodes(rpcs)
        wait_bitcoinds()
        for i in range(4):
            os.remove(log_filename("cache", i, "debug.log"))
            os.remove(log_filename("cache", i, "db.log"))
            os.remove(log_filename("cache", i, "peers.dat"))
            os.remove(log_filename("cache", i, "fee_estimates.dat"))

    for i in range(4):
        from_dir = os.path.join("cache", "node" + str(i))
        to_dir = os.path.join(test_dir, "node" + str(i))
        shutil.copytree(from_dir, to_dir)
        initialize_datadir(test_dir,
                           i)  # Overwrite port/rpcport in othila.conf
コード例 #30
0
 def rpc(self, method):
     return AuthServiceProxy(self.lbrycrdd_conn_str, service_name=method)