Example #1
0
def start_bitcoind(bitcoind_path):
    datadir = tempfile.mkdtemp()
    bitcoind_proc = subprocess.Popen([
        bitcoind_path, '-regtest', '-datadir=' + datadir, '-noprinttoconsole'
    ])

    def cleanup_bitcoind():
        bitcoind_proc.kill()
        shutil.rmtree(datadir)

    atexit.register(cleanup_bitcoind)
    # Wait for cookie file to be created
    while not os.path.exists(datadir + '/regtest/.cookie'):
        time.sleep(0.5)
    # Read .cookie file to get user and pass
    with open(datadir + '/regtest/.cookie') as f:
        userpass = f.readline().lstrip().rstrip()
    rpc = AuthServiceProxy('http://{}@127.0.0.1:18443'.format(userpass))

    # Wait for bitcoind to be ready
    ready = False
    while not ready:
        try:
            rpc.getblockchaininfo()
            ready = True
        except JSONRPCException as e:
            time.sleep(0.5)
            pass

    # Make sure there are blocks and coins available
    rpc.generatetoaddress(101, rpc.getnewaddress())
    return (rpc, userpass)
Example #2
0
class BitcoinService:
    def __init__(self):
        self.access = AuthServiceProxy("http://*****:*****@[email protected]:8332")

    def getInfo(self):
        return self.access.getinfo()
        
    def getlistreceivedbyaddress(self, num):
        return self.access.listreceivedbyaddress(num)

    def getBalance(self):
        return self.access.getbalance()

    def isValidAddress(self, addr):
        return self.access.validateaddress(addr)

    def generateAddress(self):
        return self.access.getnewaddress()

    def getAccount(self, addr):
        return self.access.getaccount(addr)

    def getAccountAddr(self, account):
        return self.access.getaccountaddress(account)
    
    def getreceivedbyaddress(self, addr):
        return self.access.getreceivedbyaddress(addr)

    def sendtoaddress(self, addr, amount, comment=""):
        return self.acccess.sendtoaddress(addr, amount, comment)
Example #3
0
def pay(request, order_id, product_id):
    cart = Cart(request)
    btc_course = (requests.get("https://api.coindesk.com/v1/bpi/currentprice/USD.json").json())["bpi"]['USD']["rate_float"]
    total_price = cart.get_total_price(product_id)
    btc_price = round((float(cart.get_total_price(product_id))/float(btc_course)), 8)
    if total_price > 0:
        rpc_user = "******"
        rpc_password = "******"
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" % (rpc_user, rpc_password))
        print("=============================")
        address = rpc_connection.getnewaddress()
        print(address)
        pay = Pay.objects.create(timestamp=timezone.now(), btc_course=btc_course, amount_expected=btc_price,
                                 amount_received=0, author=request.user.username, status=0, address=address)
        pay.save()
        Order.objects.filter(id=order_id).update(payment=pay, paid="1")
        cart.clear_item(product_id)
        return render(request, 'orders/order/pay.html',
                      {'order_id': order_id,
                       'address': address,
                       'btc_course': btc_course,
                       'total_price': total_price,
                       'btc_price': btc_price})

    else:
        content = "Cart Items are Zero. Please cart products."
        return render(request, "orders/order/waiting.html", {'content': content})
Example #4
0
    def after_signup(self, form):
        # Read and parse the referal cookie off the request if there is one
        # tracking_cookie = self.request.COOKIES.get('ref', '{}')
        # tracking_cookie = unquote_plus(tracking_cookie)
        # ref_info = json.loads(tracking_cookie)

        # and set that on the user profile
        user = self.created_user
        # up.set_referral_info(ref_code=ref_info.get('ref_code', None))
        user.set_referral_info(
            ref_code=self.request.session.get('ref_code') or '',
            ref_source=self.request.session.get('ref_src') or '',
            ref_campaign=self.request.session.get('ref_cmp') or '',
        )

        try:
            w = AuthServiceProxy(wallet.CRYPTO_WALLET_CONNSTRING)
            crypto_address = w.getnewaddress(account=user.email)
            user.set_crypto_address(crypto_address)
        except socket.error:
            # TODO Proper error handling here
            user.profile.crypto_address = '<pending>'

        user.profile.signup_ip = utils.get_client_ip(self.request) or ''
        user.profile.nickname = user.email.split('@')[0][:20]

        user.profile.save()

        super(SignupView, self).after_signup(form)
Example #5
0
class btcd(invoice):
    def __init__(self, dollar_value, currency, label, test=False):
        super().__init__(dollar_value, currency, label, test)
        print(self.__dict__)
        # self.__dict__ = invoice.__dict__.copy()

        from bitcoinrpc.authproxy import AuthServiceProxy

        connection_str = "http://{}:{}@{}:{}".format(config.username,
                                                     config.password,
                                                     config.host,
                                                     config.rpcport)
        print("Attempting to connect to {}.".format(connection_str))

        for i in range(config.connection_attempts):
            try:
                self.rpc = AuthServiceProxy(connection_str)

                if test:
                    info = self.rpc.getblockchaininfo()
                    print(info)

                print("Successfully contacted bitcoind.")
                break

            except Exception as e:
                print(e)
                time.sleep(config.pollrate)
                print("Attempting again... {}/{}...".format(
                    i + 1, config.connection_attempts))
        else:
            raise Exception("Could not connect to bitcoind. \
                Check your RPC / port tunneling settings and try again.")

    def check_payment(self):
        transactions = self.rpc.listtransactions()
        relevant_txs = [
            tx for tx in transactions if tx["address"] == self.address
        ]

        conf_paid = 0
        unconf_paid = 0
        for tx in relevant_txs:
            self.txid = tx["txid"]
            if tx["confirmations"] >= config.required_confirmations:
                conf_paid += tx["amount"]
            else:
                unconf_paid += tx["amount"]

        return conf_paid, unconf_paid

    def get_address(self):
        for i in range(config.connection_attempts):
            try:
                self.address = self.rpc.getnewaddress(self.label)
            except Exception as e:
                print(e)
                print("Attempting again... {}/{}...".format(
                    i + 1, config.connection_attempts))
        return
Example #6
0
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
Example #7
0
 def save(self, *args, **kwargs):
     if self.pk is None:
         if not self.currency in settings.CONNECTION_STRING:
             raise Exception("Connection string for %s is not defined" % self.currency)
         try:
             access = AuthServiceProxy(settings.CONNECTION_STRING[self.currency])
             self.addr = access.getnewaddress(settings.GENERATED_ADDRESSES_ACCOUNT)
         except Exception, e:
             raise Exception("Could not connect to crypto coin daemon")
Example #8
0
def btc_generate():
   print("trying RPC")
   try:
    rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,nodeip,rpc_port))
    newaddress = rpc_connect.getnewaddress()
    packqraddr = pyqrcode.create(newaddress)
    packqraddr.png("newaddress.png", scale=8)
    return newaddress
   except:
    return "Something went wrong. Check your node is properly connected."
Example #9
0
def refill_addresses_queue():
    for currency in Currency.objects.all():
        coin = AuthServiceProxy(currency.api_url)
        count = Address.objects.filter(currency=currency, active=True, wallet=None).count()

        if count < settings.CC_ADDRESS_QUEUE:
            for i in range(count, settings.CC_ADDRESS_QUEUE):
                try:
                    Address.objects.create(address=coin.getnewaddress(settings.CC_ACCOUNT), currency=currency)
                except (socket_error, CannotSendRequest) :
                    pass
Example #10
0
def refill_addresses_queue():
    for currency in Currency.objects.all():
        coin = AuthServiceProxy(currency.api_url)
        count = Address.objects.filter(currency=currency, active=True, wallet=None).count()

        if count < settings.CC_ADDRESS_QUEUE:
            for i in xrange(count, settings.CC_ADDRESS_QUEUE):
                try:
                    Address.objects.create(address=coin.getnewaddress(settings.CC_ACCOUNT), currency=currency)
                except (socket_error, CannotSendRequest) :
                    pass
Example #11
0
def create_raw_op_return_transaction(metadata):
    """
    Method used to create a transaction with embedded data through OP_RETURN

    Args:
            metadata (str)

    Returns:
            Raw transaction (hex)
            Author address (str)
    """
    rpc = AuthServiceProxy(
        ("http://%s:%[email protected]:%s/") %
        (config['RPC_USER'], config['RPC_PASS'], config['RPC_PORT']))

    if sys.getsizeof(metadata) > MAX_OP_RETURN_BYTES:
        raise Exception("Metadata size is over MAX_OP_RETURN_BYTES")

    if len(metadata) < 4:
        raise Exception(
            "This tool set does not currently support reading op_return data with less than 4 chars"
        )

    input_tx = get_input()

    init_raw_tx = rpc.createrawtransaction(
        [{
            "txid": input_tx["txid"],
            "vout": input_tx["vout"]
        }], {
            input_tx["address"]:
            TX_BURN_AMOUNT,
            rpc.getnewaddress():
            round(float(input_tx["amount"]) - 1.1 * TX_BURN_AMOUNT, 8)
        })

    oldScriptPubKey = init_raw_tx[len(init_raw_tx) - 60:len(init_raw_tx) - 8]
    newScriptPubKey = b"6a" + hexlify(
        bytes(chr(len(metadata)), encoding='utf-8')) + hexlify(
            bytes(metadata, encoding='utf-8'))
    newScriptPubKey = hexlify(
        bytes(chr(len(unhexlify(newScriptPubKey))),
              encoding='utf-8')) + newScriptPubKey

    if oldScriptPubKey not in init_raw_tx:
        raise Exception("Something broke!")

    op_return_tx = init_raw_tx.replace(oldScriptPubKey,
                                       newScriptPubKey.decode('ascii'))

    print(rpc.decoderawtransaction(op_return_tx)['vout'])

    return op_return_tx, input_tx["address"]
Example #12
0
 def save(self, *args, **kwargs):
     if self.pk is None:
         if not self.currency in settings.CONNECTION_STRING:
             raise Exception("Connection string for %s is not defined" %
                             self.currency)
         try:
             access = AuthServiceProxy(
                 settings.CONNECTION_STRING[self.currency])
             self.addr = access.getnewaddress(
                 settings.GENERATED_ADDRESSES_ACCOUNT)
         except Exception, e:
             raise Exception("Could not connect to crypto coin daemon")
Example #13
0
def homewallet():
    if session.get(u'logged_in') is None:
        return redirect('/user/login')
    else:
        uid = session.get('uid')
        user_id = session.get('user_id')
        user = db.User.find_one({'customer_id': uid})
        sva_address = user['sva_address']
        # if sva_address == '':

        # 	rpc_connection = AuthServiceProxy("http://*****:*****@127.0.0.1:23321")
        # 	sva_address = rpc_connection.getnewaddress()
        # 	print sva_address
        # 	db.users.update({ "_id" : ObjectId(user_id) }, { '$set': { "sva_address": sva_address } })
        # else:
        # 	sva_address = user['sva_address']

        btc_address = user['btc_address']
        if btc_address == '':
            # name = 'BICO_%s' %user['email']
            # url_api = 'http://192.254.72.34:38058/apibtc/getnewaddress/%s' %(name)
            # r = requests.get(url_api)
            # response_dict = r.json()
            # btc_address = response_dict['wallet']
            rpc_connection = AuthServiceProxy(
                "http://*****:*****@127.0.0.1:23321"
            )
            btc_address = rpc_connection.getnewaddress()
            print btc_address
            db.users.update({"_id": ObjectId(user_id)},
                            {'$set': {
                                "btc_address": btc_address
                            }})
        else:
            btc_address = user['btc_address']

        dataTxUser = db.txdeposits.find({'uid': uid, 'status': 1})
        dataWithdraw = db.withdrawas.find({'user_id': user_id})
        data_ticker = db.tickers.find_one({})
        data = {
            'user': user,
            'menu': 'wallet',
            'float': float,
            'tx': dataTxUser,
            'sva_address': sva_address,
            'btc_address': btc_address,
            'withdraw': dataWithdraw,
            'btc_usd': data_ticker['btc_usd'],
            'sva_btc': data_ticker['sva_btc'],
            'sva_usd': data_ticker['sva_usd']
        }
        return render_template('account/wallet.html', data=data)
class BTcoin:  

	def __init__(self, bt_account_id , username, password, hostname, port ):
		self.bt_account_id = bt_account_id  
		self.coin_client = AuthServiceProxy("http://%s:%s@%s:%s" % (username, password, hostname, port)) 
		if not self.check_client_connection():
			print "Error: Failed to connect or authenticate with the  client. Please check it's running and configured correctly."  
			
	#  Verify client		
	def check_client_connection(self):
		try:
			test = self.coin_client.getinfo()
			return True
		except socket.error:
			return False
		except ValueError:
			return False
			
	# bitcoin listaccounts
	def getAccount(self):
		return self.bt_account_id
	
	# bitcoin getaccountaddress <bt_account_id>
	def getAddress(self):
		return self.coin_client.getaccountaddress( self.bt_account_id )	 

	# bitcoin getbalance
	def getBalance(self):  
		return self.coin_client.getbalance()	
		
	# bitcoin getnewaddress
	def getNewAddress( self):
		return self.coin_client.getnewaddress( self.bt_account_id  )
		
	# bitcoin listtransactions ""
	def getListTransactions( self):
		return self.coin_client.listtransactions( self.bt_account_id  )

	# bitcoin sendtoaddress <targetaddress> <amount> [comment] [comment-to]
	def doPayment(self,toBTaddress,coins): 
		if not toBTaddress:
			return  '<div class="alert alert-danger" style="   margin: 15px;" role="alert">Error - no payment address set</div>' 
		else: 
			try:
				transaction 	= self.coin_client.sendtoaddress( toBTaddress , float(coins)  ) 
				transaction_url = "http://lbw.blockprobe.com/index.php/search?q=%s" % transaction	 
				html 			= '<div class="alert alert-info" style="    margin: 15px;" role="alert"><b>Your transaction is complete:</b> <a href="http://lbw.blockprobe.com/index.php/search?q=%s" target="_blank">%s</a></div>' % (transaction,transaction	)
				return html
			except JSONRPCException as e:
				return '<div class="alert alert-danger" style="   margin: 15px;" role="alert">Error - %s</div>' % e.error['message']
Example #15
0
def pay(request, order_id):
    cart = Cart(request)
    btc_course = (requests.get("https://api.coindesk.com/v1/bpi/currentprice/USD.json").json())["bpi"]['USD']["rate_float"]
    total_price = cart.get_total_price()
    btc_price = round((float(cart.get_total_price())/float(btc_course)),8)
    rpc_user = "******"
    rpc_password = "******"
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))
    addres = rpc_connection.getnewaddress()
    pay = Pay.objects.create(timestamp=timezone.now(), amount_expected = btc_price, amount_received = 0, author = request.user.username, status = 0, address = addres)
    pay.save()
    Order.objects.filter(id=order_id).update(payment=pay)
    cart.clear()
    return render(request, 'orders/order/pay.html', {'order_id':order_id,'addres':addres,'btc_course': btc_course, "total_price":total_price, "btc_price":btc_price})
Example #16
0
class Btc(object):
    def __init__(self,rpc_port,rpc_user,rpc_password):
    	self.rpc_ip = '127.0.0.1'
        self.rpc_user = rpc_user
        self.rpc_password = rpc_password
        self.rpc_port = rpc_port
        self.rpc_connection = AuthServiceProxy("http://%s:%s@%s:%s"%(self.rpc_user,self.rpc_password,self.rpc_ip,self.rpc_port))


    def getnewaddress(self):
        return self.rpc_connection.getnewaddress("")
    
    
    der getaccount(self,bitcoinaddress):
        return self.rpc_connection.getaccount(bitcoinaddress)
Example #17
0
def get_address(user):
	db = get_mongo()

	address = db.users.find_one({'userid': user['userid']}) \
				.get('address', None)

	if address is None:
		rpc = AuthServiceProxy("http://%s:%s@%s:%d" %
							   (config['rpc']['user'],
								config['rpc']['password'],
								config['rpc']['host'], config['rpc']['port']))
		address = rpc.getnewaddress()
		db.users.update({'userid': user['userid']},
						{'$set': {'address': address}})

	return address
Example #18
0
def get_address(user):
    db = get_mongo()

    address = db.users.find_one({"userid": user["userid"]}).get("address", None)

    if address is None:
        rpc = AuthServiceProxy(
            "http://%s:%s@%s:%d"
            % (
                config["rpc"]["user"],
                config["rpc"]["password"],
                config["rpc"]["host"],
                config["rpc"]["port"],
            )
        )
        address = rpc.getnewaddress()
        db.users.update({"userid": user["userid"]}, {"$set": {"address": address}})

    return address
Example #19
0
def hwi_initialize(plugin, bitcoin_wallet_name):
    # create Core watch-only wallet
    bitcoin_rpc.createwallet(bitcoin_wallet_name, True)
    # importmulti
    device, client = get_device_and_client()
    keypool = commands.getkeypool(client, None, 0, 100, keypool=True)

    # construct rpc for this wallet
    rpc_settings['wallet_name'] = bitcoin_wallet_name
    uri = template.format(**rpc_settings)
    wallet_rpc = AuthServiceProxy(uri)

    # import keys
    r = wallet_rpc.importmulti(keypool)
    plugin.log(str(r))
    
    address = wallet_rpc.getnewaddress()
    # return {'result': 'fund this address: ' + address}
    return 'fund this address: ' + address
Example #20
0
class CoinProxy(object):

  def __init__(self, server_ip, port, user_name, user_password):
    self.server_ip = server_ip
    # found in coin conf, rpcport
    self.port = port
    # found in coin conf, rpcuser
    self.user_name = user_name
    # found in coin conf, rpcpassword
    self.user_password = user_password

    # "http://<user>:<password>@<server_ip>:<port>"
    # we could use below curl request for debugging.
    # curl  -v --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"getblockcount","params":[]}' -H 'content-type:text/plain;'  http://cnyfundrpc:[email protected]:18189/
    self.conn = AuthServiceProxy("http://%s:%s@%s:%s"%(user_name, user_password, server_ip, port))

  @classmethod
  def fromMockConn(self, server_ip, port, user_name, user_password, conn):
    proxy = CoinProxy(server_ip, port, user_name, user_password)
    proxy.conn = conn

    return proxy

  def listtransactions(self, account, lookback_count):
    logger.info("wallet rpc: list transactions with account{0} and count {1} on server {2}".format(account, lookback_count, self.server_ip))
    return self.conn.listtransactions(account, lookback_count)

  def sendtoaddress(self, dest_addr, amount, comment):
    logger.info("wallet rpc: send {0} to address {1} with comment {2}".format(amount, dest_addr, comment))
    return self.conn.sendtoaddress(dest_addr, amount, '{0}'.format(comment))

  def unlockwallet(self, passphrase, timeout_in_sec):
    logger.info("wallet rpc: unlock wallet with {0} seconds".format(timeout_in_sec))
    return self.conn.walletpassphrase(passphrase, timeout_in_sec)

  def getnewaddress(self, account):
    logger.info("wallet rpc: get new address for account {0}".format(account))
    return self.conn.getnewaddress(account)

  def getbalance(self, account):
    logger.info("wallet rpc: get balance for account {0}".format(account))
    return self.conn.getbalance(account)
Example #21
0
def vendor_stats(request):
    if request.method == 'POST':
        btc_course = (requests.get(
            "https://api.coindesk.com/v1/bpi/currentprice/USD.json").json()
                      )["bpi"]['USD']["rate_float"]
        usd_price = 1
        btc_price = round((float(usd_price) / float(btc_course)), 8)
        rpc_user = "******"
        rpc_password = "******"
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                          (rpc_user, rpc_password))
        address = rpc_connection.getnewaddress()

        pay = Pay.objects.create(timestamp=timezone.now(),
                                 btc_course=btc_course,
                                 amount_expected=btc_price,
                                 amount_received=0,
                                 author=request.user.username,
                                 status=0,
                                 address=address)
        pay.save()

        order = Order.objects.create(address="upgrade_vendor__",
                                     user=request.user,
                                     payment=pay,
                                     paid="1")
        order.save()

        # content = "Will send you message after confirm your transaction. Please wait some times during confirm your transaction."
        # return render(request, "orders/order/waiting.html", {'content': content})
        return render(
            request, 'orders/order/pay.html', {
                'order_id': order.id,
                'address': address,
                'btc_course': btc_course,
                "total_price": usd_price,
                "btc_price": btc_price
            })

    elif request.method == 'GET':
        return render(request, 'profile/vendor_stats.html')
Example #22
0
def buy():
    body = request.json
    buyer_asset_name = body['buyer_asset_name']
    buyer_shares = float(body['buyer_shares'])
    buyer_recieve_address = body['buyer_recieve_address']

    try:
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%s/wallet/"%(rpc_user, rpc_password, rpc_port))

        receiver = rpc_connection.getnewaddress()

        for p in get_posts():
            if p[1] == buyer_asset_name:
                global amt
                amt = float(p[2]) * buyer_shares

    except JSONRPCException as json_exception:
        return "A JSON RPC Exception occured: " + str(json_exception)
    except Exception as general_exception:
        return "An Exception occured: " + str(general_exception)
    
    return json.dumps({'receiver': receiver, 'amount': amt})
Example #23
0
def newaddress():
    # {"apiKey": "0000", "params": {"account":""}}
    result_data = "{'code':'%(code)s','data':%(data)s,'msg':'%(msg)s'}"
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:18332" %
                                      (rpc_user, rpc_password))

    try:
        form_data = request.json
        param = getParams(form_data, 'post')
        if param == None:
            raise Exception('入参异常')
        account = param['account']
        address_type = 'legacy'
        address = rpc_connection.getnewaddress(account, address_type)
        a = rpc_connection.walletpassphrase('admin', 30)
        address_pkey = rpc_connection.dumpprivkey(address)
        result_data = result_data % {
            "code": "0000",
            "data": str({
                'address': address,
                'address_pkey': address_pkey
            }),
            "msg": '0'
        }
        result_data = demjson.decode(result_data)
    except BaseException as err:

        err = str(err).replace("'", "")
        result_data = result_data % ({
            "code": "0001",
            "data": "0",
            "msg": str(err)
        })

        # print(result_data)
        result_data = demjson.decode(result_data)
        # batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
    return jsonify(result_data)
Example #24
0
class BtcWallet():
    """btc钱包"""
    BTC_BLOCK_API = 'https://blockchain.info/'

    def __init__(self, app=None, consul_client=None):
        if app and consul_client:
            self.init_consul(app, consul_client)

    def init_consul(self, app, consul_client):
        try:
            rpc_user = app.config.get('CONFIG_BITCOIND_RPC_USER')
            rpc_pwd = app.config.get('CONFIG_BITCOIND_RPC_PASSWORD')
            wallet_passphrase = app.config.get('CONFIG_BITCOIND_WALLET_PASSWORD')
            self.ipport = consul_client.getRandomOneAvailableServiceIpPort(ConsulServiceName.BTC_CLI)
            # s = "http://%s:%s@" % (self.user, self.pwd) + self.ipport
            # print(s)

            self.bitcoin_cli = AuthServiceProxy(
                "http://%s:%s@" % (rpc_user, rpc_pwd) + self.ipport, timeout=10)
            print("Succeed to connect to the BTC node")

        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 是否连接BTC节点
    def is_connected(self):
        try:
            if self.bitcoin_cli.getwalletinfo().get('walletversion'):
                return True
            return False
        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 节点是否同步
    def is_sync(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        if ret.get('blocks') != ret.get("headers"):
            return False
        else:
            return True

    # btc地址是否有效
    def is_valid_address(self, coin_address):
        if coin_address is None or coin_address == '':
            return False
        else:
            ret = self.bitcoin_cli.validateaddress(coin_address).get('isvalid')
            print('账户检查结果:', ret)
            return ret

            # return self.bitcoin_cli.validateaddress(coin_address).get('isvalid')

    # 获取账户余额, 默认经过6个区块确认
    def get_balance(self, coin_address):

        transaction_lists = self.bitcoin_cli.listunspent(1, 99999999, [coin_address])
        print(transaction_lists)
        current_amount = 0
        for transaction_list in transaction_lists:
            amount = transaction_list.get('amount')
            amount = float(amount)
            current_amount += amount
        return current_amount

    def get_balance_by_account(self, account):
        try:
            ret = self.bitcoin_cli.getbalance(account)
            return ret
        except Exception as e:
            logging.error('get balance error:{}'.format(str(e)))
            return None


    def estimate_fee(self):
        try:
            fee = self.bitcoin_cli.estimatefee(6)
            return fee
        except Exception as e:
            logging.error('get fee error:{}'.format(str(e)))
            return None

    def create_account(self, stellar_account):
        # private = random_key()
        # address = pubtoaddr(privtopub(private))
        # print(address, private)
        # return address, private
        address = self.bitcoin_cli.getnewaddress(stellar_account)
        private_key = self.bitcoin_cli.dumpprivkey(address)
        return address, private_key

    def get_block_num(self):
        """获取最新区块数"""
        try:
            block_num = self.bitcoin_cli.getblockcount()
            return block_num
        except Exception as e:
            logging.error('Get btc node block number error:{}'.format(str(e)))
            return None


    def get_chain_info(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        return ret

    def get_block_info(self, block_num):
        """获取区块的详细信息"""
        param = "block-height/{}?format=json".format(block_num)
        api_url = self.BTC_BLOCK_API + param
        # print(api_url)

        blocks = requests.get(api_url, timeout=500).json()
        # print(type(blocks))
        return blocks

    # 链外转帐,普通交易
    def payment(self, btc_base_account, address_to, amount):
        try:
            txid = self.bitcoin_cli.sendfrom(btc_base_account, address_to, amount)
            return True, txid
        except Exception as e:
            logging.error('btc payment error:{}'.format(str(e)))
            return False, str(e)

    def hash_get_detail(self, tx_id):
        """
        Arguments:
        1. "txid" (string, required) The transaction id
        """
        # 根据txid获取确认链外交易信息
        ret = self.bitcoin_cli.gettransaction(tx_id)
        abandoned = ret.get("details")[0].get("abandoned")  # 获取abandon信息
        confirmation_num = ret.get('confirmations')  # 获取确认数

        # 如果确认数小于1,则未确认
        if confirmation_num < 1:
            msg = dict(confirm=str(ret))
            # msg = ret.get("details")[0]
            return False, False, msg, None
        # 如果确认数大于1,则确认
        else:
            msg = dict(confirm=str(ret))
            # msg = ret
            fee = abs(ret.get("fee"))
            if abandoned:
                return True, False, msg, None
            else:
                return True, True, msg, fee

    def raw_payment(self, address_from, address_to, collect_amount):
        inputs = []
        # 获取地址余额信息
        try:
            unspend_lists = self.bitcoin_cli.listunspent(1, 9999999, [address_from])
            for unspend_list in unspend_lists:
                # if unspend_list.get('amount') <= 0:
                #     continue
                # else:
                txid = unspend_list.get('txid')
                vout = unspend_list.get('vout')
                inputs.append({'txid': txid, 'vout': vout})

            outputs = {address_to: round(collect_amount, 8)}

            # 交易建立和签名时不用连接比特币网络,只有在执行交易时才需要将交易发送到网络
            # 创建裸交易
            transaction_hash = self.bitcoin_cli.createrawtransaction(inputs, outputs)

            # 使用私钥签名,获取16进制信息
            hex = self.bitcoin_cli.signrawtransaction(transaction_hash).get('hex')

            # 广播到p2p网络,返回交易哈希
            trading_hash = self.bitcoin_cli.sendrawtransaction(hex, False)

            return True, trading_hash, ''
        except Exception as e:
            print(e)
            return None, None, ''

    def btc_transaction_record(self, block_num):
        # 获取某一区块信息
        block_info = self.get_block_info(block_num)
        blocks = block_info.get('blocks')
        txs = blocks[0].get('tx')
        records = []
        for tx in txs:
            outs = tx.get('out')
            hash = tx.get('hash')
            inputs = tx.get('inputs')
            p_out = inputs[0].get('prev_out')
            if not p_out:
                continue
            else:
                addr_from = p_out.get('addr')
            for out in outs:
                re = []
                addr_to = out.get('addr')
                value = out.get('value') / (10 ** 8)
                # addr_to与User表中绑定的地址进行对比,如果有,则说明此address_to有冲币记录
                user = User.address_query_user('BTC', addr_to)
                if not user:
                    continue
                else:
                    re.append(addr_from)
                    re.append(addr_to)
                    re.append(value)
                    re.append(hash)
                    records.append(re)
        return records

    def get_accounts(self, addr):
        try:
            ad = self.bitcoin_cli.getaccount(addr)
            return ad
        except Exception as e:
            # logging.error('get btc_account error:{}'.format(str(e)))
            return None

    def get_address_byaccount(self, account):
        re = self.bitcoin_cli.getaddressesbyaccount(account)

        return re

    def test1(self):

        transaction_list = self.bitcoin_cli.listaccounts()
        # transaction_list = self.bitcoin_cli.getwalletinfo()
        print(transaction_list)
Example #25
0
class TestSignTx(DeviceTestCase):
    def setUp(self):
        self.rpc = AuthServiceProxy('http://{}@127.0.0.1:18443'.format(
            self.rpc_userpass))
        if '{}_test'.format(self.full_type) not in self.rpc.listwallets():
            self.rpc.createwallet('{}_test'.format(self.full_type), True)
        self.wrpc = AuthServiceProxy(
            'http://{}@127.0.0.1:18443/wallet/{}_test'.format(
                self.rpc_userpass, self.full_type))
        self.wpk_rpc = AuthServiceProxy(
            'http://{}@127.0.0.1:18443/wallet/'.format(self.rpc_userpass))
        if '--testnet' not in self.dev_args:
            self.dev_args.append('--testnet')
        self.emulator.start()

    def tearDown(self):
        self.emulator.stop()

    def _generate_and_finalize(self, unknown_inputs, psbt):
        if not unknown_inputs:
            # Just do the normal signing process to test "all inputs" case
            sign_res = self.do_command(self.dev_args +
                                       ['signtx', psbt['psbt']])
            finalize_res = self.wrpc.finalizepsbt(sign_res['psbt'])
        else:
            # Sign only input one on first pass
            # then rest on second pass to test ability to successfully
            # ignore inputs that are not its own. Then combine both
            # signing passes to ensure they are actually properly being
            # partially signed at each step.
            first_psbt = PSBT()
            first_psbt.deserialize(psbt['psbt'])
            second_psbt = PSBT()
            second_psbt.deserialize(psbt['psbt'])

            # Blank master fingerprint to make hww fail to sign
            # Single input PSBTs will be fully signed by first signer
            for psbt_input in first_psbt.inputs[1:]:
                for pubkey, path in psbt_input.hd_keypaths.items():
                    psbt_input.hd_keypaths[pubkey] = (0, ) + path[1:]
            for pubkey, path in second_psbt.inputs[0].hd_keypaths.items():
                second_psbt.inputs[0].hd_keypaths[pubkey] = (0, ) + path[1:]

            single_input = len(first_psbt.inputs) == 1

            # Process the psbts
            first_psbt = first_psbt.serialize()
            second_psbt = second_psbt.serialize()

            # First will always have something to sign
            first_sign_res = self.do_command(self.dev_args +
                                             ['signtx', first_psbt])
            self.assertTrue(single_input == self.wrpc.finalizepsbt(
                first_sign_res['psbt'])['complete'])
            # Second may have nothing to sign (1 input case)
            # and also may throw an error(e.g., ColdCard)
            second_sign_res = self.do_command(self.dev_args +
                                              ['signtx', second_psbt])
            if 'psbt' in second_sign_res:
                self.assertTrue(not self.wrpc.finalizepsbt(
                    second_sign_res['psbt'])['complete'])
                combined_psbt = self.wrpc.combinepsbt(
                    [first_sign_res['psbt'], second_sign_res['psbt']])

            else:
                self.assertTrue('error' in second_sign_res)
                combined_psbt = first_sign_res['psbt']

            finalize_res = self.wrpc.finalizepsbt(combined_psbt)
            self.assertTrue(finalize_res['complete'])
            self.assertTrue(
                self.wrpc.testmempoolaccept([finalize_res['hex']
                                             ])[0]["allowed"])
        return finalize_res['hex']

    def _test_signtx(self, input_type, multisig):
        # Import some keys to the watch only wallet and send coins to them
        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--sh_wpkh', '30', '40'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--sh_wpkh', '--internal', '30', '40'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        sh_wpkh_addr = self.wrpc.getnewaddress('', 'p2sh-segwit')
        wpkh_addr = self.wrpc.getnewaddress('', 'bech32')
        pkh_addr = self.wrpc.getnewaddress('', 'legacy')
        self.wrpc.importaddress(wpkh_addr)
        self.wrpc.importaddress(pkh_addr)

        # pubkeys to construct 2-of-3 multisig descriptors for import
        sh_wpkh_info = self.wrpc.getaddressinfo(sh_wpkh_addr)
        wpkh_info = self.wrpc.getaddressinfo(wpkh_addr)
        pkh_info = self.wrpc.getaddressinfo(pkh_addr)

        # Get origin info/key pair so wallet doesn't forget how to
        # sign with keys post-import
        pubkeys = [sh_wpkh_info['desc'][8:-11],\
                wpkh_info['desc'][5:-10],\
                pkh_info['desc'][4:-10]]

        # Get the descriptors with their checksums
        sh_multi_desc = self.wrpc.getdescriptorinfo('sh(multi(2,' +
                                                    pubkeys[0] + ',' +
                                                    pubkeys[1] + ',' +
                                                    pubkeys[2] +
                                                    '))')['descriptor']
        sh_wsh_multi_desc = self.wrpc.getdescriptorinfo('sh(wsh(multi(2,' +
                                                        pubkeys[0] + ',' +
                                                        pubkeys[1] + ',' +
                                                        pubkeys[2] +
                                                        ')))')['descriptor']
        wsh_multi_desc = self.wrpc.getdescriptorinfo('wsh(multi(2,' +
                                                     pubkeys[2] + ',' +
                                                     pubkeys[1] + ',' +
                                                     pubkeys[0] +
                                                     '))')['descriptor']

        sh_multi_import = {
            'desc': sh_multi_desc,
            "timestamp": "now",
            "label": "shmulti"
        }
        sh_wsh_multi_import = {
            'desc': sh_wsh_multi_desc,
            "timestamp": "now",
            "label": "shwshmulti"
        }
        # re-order pubkeys to allow import without "already have private keys" error
        wsh_multi_import = {
            'desc': wsh_multi_desc,
            "timestamp": "now",
            "label": "wshmulti"
        }
        multi_result = self.wrpc.importmulti(
            [sh_multi_import, sh_wsh_multi_import, wsh_multi_import])
        self.assertTrue(multi_result[0]['success'])
        self.assertTrue(multi_result[1]['success'])
        self.assertTrue(multi_result[2]['success'])

        sh_multi_addr = self.wrpc.getaddressesbylabel("shmulti").popitem()[0]
        sh_wsh_multi_addr = self.wrpc.getaddressesbylabel(
            "shwshmulti").popitem()[0]
        wsh_multi_addr = self.wrpc.getaddressesbylabel("wshmulti").popitem()[0]

        in_amt = 3
        out_amt = in_amt // 3
        number_inputs = 0
        # Single-sig
        if input_type == 'segwit' or input_type == 'all':
            self.wpk_rpc.sendtoaddress(sh_wpkh_addr, in_amt)
            self.wpk_rpc.sendtoaddress(wpkh_addr, in_amt)
            number_inputs += 2
        if input_type == 'legacy' or input_type == 'all':
            self.wpk_rpc.sendtoaddress(pkh_addr, in_amt)
            number_inputs += 1
        # Now do segwit/legacy multisig
        if multisig:
            if input_type == 'legacy' or input_type == 'all':
                self.wpk_rpc.sendtoaddress(sh_multi_addr, in_amt)
                number_inputs += 1
            if input_type == 'segwit' or input_type == 'all':
                self.wpk_rpc.sendtoaddress(wsh_multi_addr, in_amt)
                self.wpk_rpc.sendtoaddress(sh_wsh_multi_addr, in_amt)
                number_inputs += 2

        self.wpk_rpc.generatetoaddress(6, self.wpk_rpc.getnewaddress())

        # Spend different amounts, requiring 1 to 3 inputs
        for i in range(number_inputs):
            # Create a psbt spending the above
            if i == number_inputs - 1:
                self.assertTrue((i + 1) *
                                in_amt == self.wrpc.getbalance("*", 0, True))
            psbt = self.wrpc.walletcreatefundedpsbt(
                [], [{
                    self.wpk_rpc.getnewaddress('', 'legacy'): (i + 1) * out_amt
                }, {
                    self.wpk_rpc.getnewaddress('', 'p2sh-segwit'):
                    (i + 1) * out_amt
                }, {
                    self.wpk_rpc.getnewaddress('', 'bech32'): (i + 1) * out_amt
                }], 0, {
                    'includeWatching': True,
                    'subtractFeeFromOutputs': [0, 1, 2]
                }, True)

            # Sign with unknown inputs in two steps
            self._generate_and_finalize(True, psbt)
            # Sign all inputs all at once
            final_tx = self._generate_and_finalize(False, psbt)

        # Send off final tx to sweep the wallet
        self.wrpc.sendrawtransaction(final_tx)

    # Test wrapper to avoid mixed-inputs signing for Ledger
    def test_signtx(self):
        supports_mixed = {'coldcard', 'trezor_1', 'digitalbitbox', 'keepkey'}
        supports_multisig = {'ledger', 'trezor_1', 'digitalbitbox', 'keepkey'}
        if self.full_type not in supports_mixed:
            self._test_signtx("legacy", self.full_type in supports_multisig)
            self._test_signtx("segwit", self.full_type in supports_multisig)
        else:
            self._test_signtx("all", self.full_type in supports_multisig)

    # Make a huge transaction which might cause some problems with different interfaces
    def test_big_tx(self):
        # make a huge transaction that is unrelated to the hardware wallet
        outputs = []
        num_inputs = 60
        for i in range(0, num_inputs):
            outputs.append({self.wpk_rpc.getnewaddress('', 'legacy'): 0.001})
        psbt = self.wpk_rpc.walletcreatefundedpsbt([], outputs, 0, {},
                                                   True)['psbt']
        psbt = self.wpk_rpc.walletprocesspsbt(psbt)['psbt']
        tx = self.wpk_rpc.finalizepsbt(psbt)['hex']
        txid = self.wpk_rpc.sendrawtransaction(tx)
        inputs = []
        for i in range(0, num_inputs):
            inputs.append({'txid': txid, 'vout': i})
        psbt = self.wpk_rpc.walletcreatefundedpsbt(
            inputs,
            [{
                self.wpk_rpc.getnewaddress('', 'legacy'): 0.001 * num_inputs
            }], 0, {'subtractFeeFromOutputs': [0]}, True)['psbt']
        # For cli, this should throw an exception
        try:
            result = self.do_command(self.dev_args + ['signtx', psbt])
            if self.interface == 'cli':
                self.fail('Big tx did not cause CLI to error')
            if self.type == 'coldcard':
                self.assertEqual(result['code'], -7)
            else:
                self.assertNotIn('code', result)
                self.assertNotIn('error', result)
        except OSError as e:
            if self.interface == 'cli':
                pass
Example #26
0
class WalletBase:

    def __init__(self, pay_tx_fee, min_tx_fee,
                 prio_threshold, dust_soft_limit, free_tx_size):
        self.proxy = None
        self.pay_tx_fee = pay_tx_fee
        self.min_tx_fee = min_tx_fee
        self.prio_threshold = prio_threshold
        self.dust_soft_limit = dust_soft_limit
        self.free_tx_size = free_tx_size

    def set_size(self, base_size, input_size, output_size):
        self.base_size = base_size
        self.input_size = input_size
        self.output_size = output_size

    def load_config(self, config_path):
        # trick to load a config file without sections
        con = open(config_path, 'r').read()
        dummy_fp = io.StringIO(("[%s]\n" % TMP_SECTION) + con)
        config = configparser.ConfigParser()
        config.readfp(dummy_fp)

        ## utility function
        def get_conf(key, default=None):
            if config.has_option(TMP_SECTION, key):
                return config.get(TMP_SECTION, key)
            return default

        self.rpc_user = get_conf('rpcuser')
        self.rpc_pass = get_conf('rpcpassword')
        self.rpc_port = int(get_conf('rpcport'))
        self.rpc_host = get_conf('rpcconnect', '127.0.0.1')

        if config.has_option(TMP_SECTION, 'paytxfee'):
            self.pay_tx_fee = int(float(get_conf('paytxfee')) * 10**8)
        if config.has_option(TMP_SECTION, 'mintxfee'):
            self.min_tx_fee = int(float(get_conf('mintxfee')) * 10**8)

    def connect(self):
        self.proxy = AuthServiceProxy('http://%s:%s@%s:%d/' %
                                      (self.rpc_user, self.rpc_pass,
                                       self.rpc_host, self.rpc_port))

    def get_size(self, inputs, outputs):
        raw = self.proxy.createrawtransaction(inputs, outputs)
        return len(raw) / 2

    ## Deprecate after official supports for getrawchangeaddress in major coins
    def get_change_address(self):
        groups = self.proxy.listaddressgroupings()
        for group in groups:
            for entry in group:
                if len(entry) == 3:
                    ## maybe with account
                    continue
                elif len(entry) == 2:
                    res = self.proxy.validateaddress(entry[0])
                    if 'account' not in res:
                        return entry[0]
                else:
                    raise RuntimeError('never reach')
        return self.proxy.getnewaddress()

    ## ref: wallet.cpp CWallet::CreateTransaction
    def calculate(self, inputs, address, amount, chgaddress):
        tmp = {address: float(amount) / 10**8, chgaddress: 1 }
        size = self.get_size(inputs, tmp)

        total = 0
        prio = 0
        for inp in inputs:
            raw = self.proxy.getrawtransaction(inp['txid'])
            tx = self.proxy.decoderawtransaction(raw)
            value = tx['vout'][inp['vout']]['value']
            conf = self.proxy.gettransaction(inp['txid'])['confirmations']

            total += int(value * 10**8)
            prio += int(value * 10**8) * (conf + 1)
        prio = int(prio / size)

        payfee = self.pay_tx_fee * (1 + int(size / 1000))

        minfee = self.min_tx_fee * (1 + int(size / 1000))
        if prio >= self.prio_threshold and size < self.free_tx_size:
            minfee = 0
        if amount < self.dust_soft_limit:
            minfee += self.min_tx_fee
        if total-amount-minfee < self.dust_soft_limit:
            minfee += self.min_tx_fee
        fee = max(payfee, minfee)

        change = total - amount - fee

        if change <= 0:
            raise RuntimeError('Insufficient inputs: change = %f' %
                               (float(change) / 10**8))

        return { 'total': total, 'fee': fee, 'change': change,
                  'size': size, 'prio': prio }

    def send(self, inputs, address, amount):
        chgaddress = self.get_change_address()
        res = self.calculate(inputs, address, amount, chgaddress)
        outputs = { address: float(amount) / 10**8,
                    chgaddress: float(res['change']) / 10**8 }

        raw = self.proxy.createrawtransaction(inputs, outputs)
        signed = self.proxy.signrawtransaction(raw)
        if not signed['complete']:
            raise RuntimeError('signatures are missing')
        return self.proxy.sendrawtransaction(signed['hex'])

    def show_send_info(self, inputs, address, amount):
        chgaddress = self.get_change_address()
        res = self.calculate(inputs, address, amount, chgaddress)

        print('Total amount: %f' % (float(res['total']) / 10**8))
        print('Send: %f to %s' % (float(amount) / 10**8, address))
        print('Change: %f to %s' % (float(res['change']) / 10**8, chgaddress))
        print('Fee: %f' % (float(res['fee']) / 10**8))
        print('Size: %d bytes' % res['size'])
        print('Priority: %d' % res['prio'])

    def unspent_coins(self):
        coins = self.proxy.listunspent(6)
        for c in coins:
            c['amount'] = int(c['amount'] * 10**8)
            c['prio'] = c['amount'] * (c['confirmations'] + 1)
        return coins
Example #27
0
class TestGetKeypool(DeviceTestCase):
    def setUp(self):
        self.rpc = AuthServiceProxy('http://{}@127.0.0.1:18443'.format(
            self.rpc_userpass))
        if '{}_test'.format(self.full_type) not in self.rpc.listwallets():
            self.rpc.createwallet('{}_test'.format(self.full_type), True)
        self.wrpc = AuthServiceProxy(
            'http://{}@127.0.0.1:18443/wallet/{}_test'.format(
                self.rpc_userpass, self.full_type))
        self.wpk_rpc = AuthServiceProxy(
            'http://{}@127.0.0.1:18443/wallet/'.format(self.rpc_userpass))
        if '--testnet' not in self.dev_args:
            self.dev_args.append('--testnet')
        self.emulator.start()

    def tearDown(self):
        self.emulator.stop()

    def test_getkeypool_bad_args(self):
        result = self.do_command(
            self.dev_args + ['getkeypool', '--sh_wpkh', '--wpkh', '0', '20'])
        self.assertIn('error', result)
        self.assertIn('code', result)
        self.assertEqual(result['code'], -7)

    def test_getkeypool(self):
        non_keypool_desc = self.do_command(self.dev_args +
                                           ['getkeypool', '0', '20'])
        import_result = self.wpk_rpc.importmulti(non_keypool_desc)
        self.assertTrue(import_result[0]['success'])

        keypool_desc = self.do_command(self.dev_args +
                                       ['getkeypool', '--keypool', '0', '20'])
        import_result = self.wpk_rpc.importmulti(keypool_desc)
        self.assertFalse(import_result[0]['success'])

        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/44'/1'/0'/0/{}".format(i))
            addr_info = self.wrpc.getaddressinfo(
                self.wrpc.getrawchangeaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/44'/1'/0'/1/{}".format(i))

        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--sh_wpkh', '0', '20'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/49'/1'/0'/0/{}".format(i))
            addr_info = self.wrpc.getaddressinfo(
                self.wrpc.getrawchangeaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/49'/1'/0'/1/{}".format(i))

        keypool_desc = self.do_command(
            self.dev_args + ['getkeypool', '--keypool', '--wpkh', '0', '20'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/84'/1'/0'/0/{}".format(i))
            addr_info = self.wrpc.getaddressinfo(
                self.wrpc.getrawchangeaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/84'/1'/0'/1/{}".format(i))

        keypool_desc = self.do_command(self.dev_args + [
            'getkeypool', '--keypool', '--sh_wpkh', '--account', '3', '0', '20'
        ])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/49'/1'/3'/0/{}".format(i))
            addr_info = self.wrpc.getaddressinfo(
                self.wrpc.getrawchangeaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/49'/1'/3'/1/{}".format(i))
        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--wpkh', '--account', '3', '0', '20'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/84'/1'/3'/0/{}".format(i))
            addr_info = self.wrpc.getaddressinfo(
                self.wrpc.getrawchangeaddress())
            self.assertEqual(addr_info['hdkeypath'],
                             "m/84'/1'/3'/1/{}".format(i))

        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--path', 'm/0h/0h/4h/*', '0', '20'])
        import_result = self.wrpc.importmulti(keypool_desc)
        self.assertTrue(import_result[0]['success'])
        for i in range(0, 21):
            addr_info = self.wrpc.getaddressinfo(self.wrpc.getnewaddress())
            self.assertEqual(addr_info['hdkeypath'], "m/0'/0'/4'/{}".format(i))

        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--path', '/0h/0h/4h/*', '0', '20'])
        self.assertEqual(keypool_desc['error'], 'Path must start with m/')
        self.assertEqual(keypool_desc['code'], -7)
        keypool_desc = self.do_command(
            self.dev_args +
            ['getkeypool', '--keypool', '--path', 'm/0h/0h/4h/', '0', '20'])
        self.assertEqual(keypool_desc['error'], 'Path must end with /*')
        self.assertEqual(keypool_desc['code'], -7)
Example #28
0
from bitcoinrpc.authproxy import AuthServiceProxy
from datetime import datetime

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://*****:*****@47.105.119.12:18332")
best_block_hash = rpc_connection.getblockhash(202)
print(rpc_connection.getblock(best_block_hash))

print(rpc_connection.getblockcount())
print(rpc_connection.listreceivedbyaddress())
print(rpc_connection.listaddressgroupings())
print(rpc_connection.listaccounts())
print(rpc_connection.getnewaddress())

print('=' * 20)
# batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
commands = [["getblockhash", height] for height in range(100)]
block_hashes = rpc_connection.batch_(commands)
blocks = rpc_connection.batch_([["getblock", h] for h in block_hashes])
block_times = [
    datetime.utcfromtimestamp(block["time"]).strftime("%Y-%m-%d %H:%M:%S")
    for block in blocks
]
print(block_times)
print('=' * 20)
#rpc_connection.sendrawtransaction('test')

print('=' * 20)
import hashlib
import bitcoin
import bitcoin.rpc
Example #29
0
def submit_raw(rpc_user,
               rpc_password,
               rpc_host,
               send_addr=None,
               recv_addr=None,
               send_amount=None):

    rpc_connection = AuthServiceProxy("http://{}:{}@{}".format(
        rpc_user, rpc_password, rpc_host))
    # ...
    #rpc_connection.walletpassphrase("openos", 10)
    # validate address
    ret = rpc_connection.validateaddress(recv_addr) if recv_addr else {}

    # ...

    first_unspent = rpc_connection.listunspent()[0]
    print(first_unspent)

    address = first_unspent.get("address")
    scriptPubKey = first_unspent.get("scriptPubKey")
    redeemScript = first_unspent.get("redeemScript")
    txid = first_unspent.get("txid")
    vout = first_unspent.get("vout")

    #first_unspent_amount = Decimal(first_unspent.get("amount"))
    #username = rpc_connection.getaccountaddress(send_addr)
    #print(username)
    username = '******'
    first_unspent_amount = Decimal(rpc_connection.getbalance(username))

    raw_change_address = rpc_connection.getrawchangeaddress()
    new_bitcoin_address = recv_addr if recv_addr else rpc_connection.getnewaddress(
    )

    print("raw_change_address [{}]".format(raw_change_address))

    fee_obj = rpc_connection.estimatesmartfee(6)
    fee = fee_obj.get("feerate")

    # check
    if send_amount:
        print(first_unspent_amount, fee, send_amount)
        change_amount = first_unspent_amount - fee - send_amount
    else:
        send_amount = first_unspent_amount / 2
        change_amount = first_unspent_amount / 2 - fee

    if change_amount < 0.00001:
        print(change_amount)
        raise Exception("Insufficient funds")

    change_amount_string = "%.8f" % change_amount
    send_amount_string = "%0.8f" % send_amount

    data = "@landpack"
    if len(data) > 75:
        print("Data length is {}".format(len(data)))
        raise Exception("Too much data, use OP_PUSHDATA1 instead")

    hex_format_data = binascii.hexlify(data)

    hexstring = rpc_connection.createrawtransaction(
        [{
            "txid": txid,
            "vout": vout
        }], {
            "data": hex_format_data,
            new_bitcoin_address: send_amount_string,
            raw_change_address: change_amount_string
        })
    privkey = rpc_connection.dumpprivkey(address)

    sign_raw_transaction = rpc_connection.signrawtransaction(
        hexstring, [{
            "txid": txid,
            "vout": vout,
            "redeemScript": redeemScript,
            "scriptPubKey": scriptPubKey,
            "amount": first_unspent_amount
        }], [privkey])
    raw_hash = sign_raw_transaction.get("hex")
    ret = rpc_connection.sendrawtransaction(raw_hash)
    return ret
Example #30
0
        json.dump(dict(name=name), file)
        file.close()

    try:
        prox = AuthServiceProxy('http://*****:*****@127.0.0.1:8336')

        valid = False
        for add in prox.name_history(name):
            if add['address'] == address:
                valid = True
        if not valid:
            print 'Invalid name.'
            os.remove('keys.txt')
            exit()

        add = prox.getnewaddress()
        prox.name_update(name, '', add)
    except JSONRPCException, exc: 
        if exc.error['message'] == 'there are pending operations on that name':
            print 'Program is or was recently running. You need to wait for this copy to work.'
        else:                                                     
            print 'Invalid name.'
            os.remove('keys.txt')
        exit()

    thr = Thread(target=check, args=[add])
    thr.daemon = True
    thr.start()    

    while 1:
        print raw_input('input> ')
# Python 2.7.6 and relies on bitcoind & bitcoinrpc & wobine's github connection file
# We had to change the bitcoinrpc 'connection.py' file to add multisig support
# you'll need to download our 'connection.py' file from Github & stuff it in your bitcoinrpc folder

#import sys;
#sys.path.append("D:\github\python-bitcoinrpc\bitcoinrpc")

from bitcoinrpc.authproxy import AuthServiceProxy



bitcoin = AuthServiceProxy("http://*****:*****@127.0.0.1:8332")#creates an object called 'bitcoin' that allows for bitcoind calls

SetTxFee = int(0.00005461*100000000) # Lets proper good etiquette & put something aside for our friends the miners

ChangeAddress = bitcoin.getnewaddress();

unspent = bitcoin.listunspent() # Query wallet.dat file for unspent funds to see if we have multisigs to spend from

print "你的钱包里这些地址有 ",len(unspent)," 个地址可以花费"
for i in range(0, len(unspent)):
    print
    print "第 ",i+1," 个地址有 ",unspent[i]["amount"]," 个比特币,相当于 ",int(unspent[i]["amount"]*100000000),"聪"
    print "它的传输ID ",i+1,"是"
    print unspent[i]["txid"]
    print "ScriptPubKey: ", unspent[i]["scriptPubKey"]
    print "地址 =====>>",unspent[i]["address"]

print
totalcoin = int(bitcoin.getbalance()*100000000)
print "钱包总额是:", totalcoin, "聪"
Example #32
0
class Bitcoind_Real:
    """
	Connection to a Bitcoin daemon process.
	"""

    def __init__(self, settings):
        """
		Arguments:
		settings: a settings object; must contain the attribute bitcoinRPCURL.

		Connects to a Bitcoin daemon process, indicated by settings.bitcoinRPCURL.
		If settings.bitcoinRPCURL is empty, this object will not be connected.
		"""

        if settings.bitcoinRPCURL != "":
            log.log("Making connection to Bitcoin daemon...")
            self.access = AuthServiceProxy(settings.bitcoinRPCURL)
            log.log("...done")
        else:
            log.log("Bitcoin-RPC URL is not set: not connecting")
            self.access = None

    def isConnected(self):
        """
		Return value:
		bool

		Returns whether this object is connected.
		"""

        return self.access != None

    def getBalance(self):
        """
		Return value:
		int, in Satoshi

		Returns the balance.
		"""

        return self.DecimaltoAmount(self.access.getbalance())

    def getBlockCount(self):
        """
		Return value:
		int

		Returns the block count.
		"""

        return self.access.getblockcount()

    def getNewAddress(self):
        """
		Return value:
		str, Base58Check-encoded address

		Generates and returns a new address.
		"""
        return self.access.getnewaddress()

    def getPrivateKey(self, address):
        """
		Arguments:
		address: str, Base58Check-encoded address
		Return value:
		str, Base58Check-encoded private key

		Returns the private key corresponding to the given address.
		"""

        return self.access.dumpprivkey(address)

    def getBlockInfoByBlockHeight(self, height):
        """
		Arguments:
		height: int

		Return value:
		dict; containing:
			hash: str; the block hash (hexadecimal)
			merkleroot: str; the block Merkle root (hexadecimal, Bitcoin hash byte order)
			time: int; the block timestamp (UNIX time)

		Returns information about the block (in the main chain) at the
		given height.
		"""
        bhash = self.access.getblockhash(height)
        binfo = self.access.getblock(bhash)
        return {"hash": binfo["hash"], "merkleroot": binfo["merkleroot"], "time": binfo["time"]}

    def getTransactionHashesByBlockHeight(self, height):
        """
		Arguments:
		height: int
		Return value:
		list of str, hexadecimal, Bitcoin hash byte order

		Returns the transaction hashes in the block (in the main chain) at the
		given height.
		"""

        bhash = self.access.getblockhash(height)
        block = self.access.getblock(bhash)
        return block["tx"]

    def getTransaction(self, thash):
        """
		Arguments:
		thash: str, hexadecimal, Bitcoin hash byte order

		Return value:
		dict, containing:
			vin: list of dict, each element containing:
				coinbase [only for coinbase transactions]
				txid [only for non-coinbase transactions]:
					str, hexadecimal, Bitcoin hash byte order
					hash of input transaction
			hex: str, hexadecimal, serialization of the transaction
			confirmations: int, number of confirmations

		Returns information about the transaction indicated by the given hash.
		"""

        return self.access.getrawtransaction(thash, 1)

    def importprivkey(self, privateKey, description, rescan):
        return self.access.importprivkey(privateKey, description, rescan)

    def listUnspent(self):
        """
		Return value:
		list of dict, each element containing:
			address: 
				str, Base58Check-encoded address
			amount:
				int, in Satoshi
			scriptPubKey:
				str, binary
			txid:
				str, binary, OpenSSL byte order
			vout:
				int

		Returns information about the available unspent transaction outputs.
		"""

        ret = self.access.listunspent()
        for vout in ret:
            vout["txid"] = binascii.unhexlify(vout["txid"])[::-1]  # reversed; TODO: is this the right place?
            vout["scriptPubKey"] = binascii.unhexlify(vout["scriptPubKey"])
            vout["amount"] = self.DecimaltoAmount(vout["amount"])
        return ret

    def sendRawTransaction(self, txData):
        """
		Arguments:
		txData: str, binary

		Send the given serialized transaction over the Bitcoin network.
		"""
        try:
            self.access.sendrawtransaction(txData.encode("hex"))
        except JSONRPCException as e:
            if e.error["code"] == RPC_TRANSACTION_ALREADY_IN_CHAIN:
                # It's perfectly fine (but very unlikely) that the transaction is
                # already in the block chain.
                # After all, we WANT it to end up in the block chain!
                pass
            else:
                raise

    def DecimaltoAmount(self, value):
        return int(value * 100000000)

    def handleMessage(self, msg):
        return [
            messages.BitcoinReturnValue(value=msg.function(self), ID=msg.returnID, channelIndex=msg.returnChannelIndex)
        ]
Example #33
0
class BTCRPCCall(object):

    def __init__(self, wallet="receive", currency="btc"):
        yml_config_reader = ConfigFileReader()
        url = yml_config_reader.get_rpc_server(currency=currency, wallet=wallet)

        self.access = AuthServiceProxy(url)

    def do_getinfo(self):
        return self.access.getinfo()

    def do_get_new_address(self):
        return self.access.getnewaddress();

    def do_set_account(self, address, account):
        return self.access.setaccount(address, account)

    def do_get_transaction(self, txid):
        try:
            return self.access.gettransaction(txid)
        except RuntimeError:
            #return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

    def do_list_transactions(self, account, count=10, from_index=0):
        try:
            return self.access.listtransactions(account, count, from_index)
        except RuntimeError:
            print "calling failure"

    def amount_received_by_address(self, address="", confirms=0):
        return self.access.getreceivedbyaddress(address, confirms)

    def do_validate_address(self, address=""):
        return self.access.validateaddress(address)

    def list_transactions(self, account="", count=10, from_index=0):
        return self.access.listtransactions(account, count, from_index)

    def send_from(self, from_account="", to_address="", amount=0, minconf=1):
        return self.access.sendfrom(from_account, to_address, amount, minconf)

    def get_received_amount_by_account(self, account="", minconf=1):
        return self.access.getreceivedbyaccount(account, minconf)

    def get_balance(self, account="", minconf=1):
        return self.access.getbalance(account, minconf)

    def get_wallet_balance(self):
        return self.access.getbalance()

    def move(self, from_account="", to_account="", amount=0, minconf=1):
        return self.access.move(from_account, to_account, amount, minconf)

    def list_accounts(self, confirmations=1):
        return self.access.listaccounts(confirmations)

    def list_received_by_address(self, confirmations=1, include_empty=False):
        return self.access.listreceivedbyaddress(confirmations, include_empty)

    def get_addresses_by_account(self, account):
        return self.access.getaddressesbyaccount(account)
Example #34
0
from pacioli import app
from bitcoinrpc.authproxy import AuthServiceProxy
import csv

access = AuthServiceProxy("http://%s:%[email protected]:8332" % (app.config['RPCUSERNAME'], app.config['RPCPASSWORD']))

number = 50
csvfile = open('addresses.csv','a')
writer = csv.writer(csvfile)

while number != 0:
    try:
        newaddress = access.getnewaddress()
        writer.writerow([newaddress])
        print(number)
        number -= 1
    except:
        pass

csvfile.close()
Example #35
0
class BTCRPCCall(object):
  def __init__(self, wallet="receive", currency="btc"):
    yml_config_reader = ConfigFileReader()
    url = yml_config_reader.get_rpc_server(currency=currency, wallet=wallet)

    self.access = AuthServiceProxy(url)

  def do_getinfo(self):
    return self.access.getinfo()

  def do_get_new_address(self):
    return self.access.getnewaddress();

  def do_set_account(self, address, account):
    return self.access.setaccount(address, account)

  def do_get_transaction(self, txid):
    try:
      return self.access.gettransaction(txid)
    except RuntimeError:
      # return simplejson.dumps ({u'error' : u'txid is not valid'})
      return None

  def do_list_transactions(self, account, count=10, from_index=0):
    try:
      return self.access.listtransactions(account, count, from_index)
    except RuntimeError:
      print("calling failure")

    def do_get_transaction(self, tx_id):
        try:
            return self.access.gettransaction(tx_id)
        except RuntimeError:
            #return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

  def amount_received_by_address(self, address="", confirms=0):
    return self.access.getreceivedbyaddress(address, confirms)

  def do_validate_address(self, address=""):
    return self.access.validateaddress(address)

  def list_transactions(self, account="", count=10, from_index=0):
    return self.access.listtransactions(account, count, from_index)

  def send_from(self, from_account="", to_address="", amount=0, minconf=1):
    return self.access.sendfrom(from_account, to_address, amount, minconf)

  def get_received_amount_by_account(self, account="", minconf=1):
    return self.access.getreceivedbyaccount(account, minconf)

  def get_balance(self, account="", minconf=1):
    return self.access.getbalance(account, minconf)

  def get_wallet_balance(self):
    return self.access.getbalance()

  def move(self, from_account="", to_account="", amount=0, minconf=1):
    return self.access.move(from_account, to_account, amount, minconf)

  def list_accounts(self, confirmations=1):
    return self.access.listaccounts(confirmations)

  def list_received_by_address(self, confirmations=1, include_empty=False):
    return self.access.listreceivedbyaddress(confirmations, include_empty)

  def get_addresses_by_account(self, account):
    return self.access.getaddressesbyaccount(account)

  def set_tx_fee(self, amount):
    return self.access.settxfee(amount)

  def send_to_address(self, address, amount, subtractfeefromamount=True):
    return self.access.sendtoaddress(address, amount, "", "", subtractfeefromamount)

  # amount is type of dictionary
  def send_many(self, from_account="", minconf=1, **amounts):
    log.info("From account: %s", from_account)
    log.info("To accounts: %s", json.dumps(amounts))
    amounts_string = json.dumps(amounts['amounts'])
    amounts_object = json.loads(amounts_string)
    try:
      return True, self.access.sendmany(from_account, amounts_object, minconf)
    except JSONRPCException as ex:
      return False, ex
    except socket.error as e:
      return False, e
Example #36
0
# you'll need to download our 'connection.py' file from Github & stuff it in your bitcoinrpc folder

#import sys;
#sys.path.append("D:\github\python-bitcoinrpc\bitcoinrpc")

from bitcoinrpc.authproxy import AuthServiceProxy

bitcoin = AuthServiceProxy(
    "http://*****:*****@127.0.0.1:8332"
)  #creates an object called 'bitcoin' that allows for bitcoind calls

SetTxFee = int(
    0.00005461 * 100000000
)  # Lets proper good etiquette & put something aside for our friends the miners

ChangeAddress = bitcoin.getnewaddress()

unspent = bitcoin.listunspent(
)  # Query wallet.dat file for unspent funds to see if we have multisigs to spend from

print "你的钱包里这些地址有 ", len(unspent), " 个地址可以花费"
for i in range(0, len(unspent)):
    print
    print "第 ", i + 1, " 个地址有 ", unspent[i]["amount"], " 个比特币,相当于 ", int(
        unspent[i]["amount"] * 100000000), "聪"
    print "它的传输ID ", i + 1, "是"
    print unspent[i]["txid"]
    print "ScriptPubKey: ", unspent[i]["scriptPubKey"]
    print "地址 =====>>", unspent[i]["address"]

print
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
# rpc_user and rpc_password are set in the bitcoin.conf file
bitcoin = AuthServiceProxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))

add = dict()
privkey = dict()
pubkey = dict()
mid = "\",\"" #this thing inserts these 3 characters ","


for i in range(0, 3): #Generate three new addresses (Pub Key & Priv Key)
    print
    print "Brand New Address Pair: Number", i+1
    
    add[i] = bitcoin.getnewaddress()
    print "Compressed Public Address -",len(add[i]),"chars -", add[i]
    
    privkey[i] = bitcoin.dumpprivkey(add[i])
    print "Private Key -", len(privkey[i]),"chars -",privkey[i]

    validDate = bitcoin.validateaddress(add[i]) # we need a less compressed Public Key so we have to call validateaddress to find it
    pubkey[i] = validDate["pubkey"]
    print "Less compressed Public Key/Address -",len(pubkey[i]),"chars -",pubkey[i]

print
print "For fun you can paste this into bitcoind to verify multisig address"
print "%s%s%s%s%s%s%s" % ('bitcoind createmultisig 2 \'["',pubkey[0],mid,pubkey[1],mid,pubkey[2],'"]\'')

print
threeaddy = [pubkey[0],pubkey[1],pubkey[2]]
Example #38
0
class client():
    def __init__(self, rpcuser, rpcpassword, rpcbindip, rpcport):
        serverURL = 'http://' + rpcuser + ':' + rpcpassword + '@' + rpcbindip + ':' + str(
            rpcport)
        self.access = AuthServiceProxy(serverURL)

    def checksynced(self):
        try:
            r = self.access.mnsync('status')
            return (r['IsSynced'])

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_governance(self):
        try:
            r = self.access.getgovernanceinfo()
            ginfo = {
                "proposalfee": r.get('proposalfee'),
                "superblockcycle": r.get('superblockcycle'),
                "nextsuperblock": r.get('nextsuperblock')
            }
            return ginfo

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_getblockcount(self):
        try:
            r = self.access.getblockcount()
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_prepare(self, preparetime, proposalhex):
        try:
            r = self.access.gobject('prepare', str(0), str(1),
                                    str(preparetime), proposalhex)
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_submit(self, preparetime, proposalhex, feetxid):
        try:
            r = self.access.gobject('submit', str(0), str(1), str(preparetime),
                                    proposalhex, feetxid)
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_submit_sb(self, preparetime, triggerhex):
        try:
            r = self.access.gobject('submit', str(0), str(1), str(preparetime),
                                    triggerhex)
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_vote(self, proposalhash):
        try:
            r = self.access.gobject('vote-many', proposalhash, 'funding',
                                    'yes')
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_rawtxid(self, txid):
        try:
            r = self.access.getrawtransaction(txid, 1)
            confirmations = r.get('confirmations')
            if confirmations:
                print('confirmations : ', confirmations)
                return confirmations
            else:
                print('confirmations : 0')
                return 0

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()

    def get_getnewaddress(self):
        try:
            r = self.access.getnewaddress()
            return r

        except JSONRPCException as e:
            print(e.args)
            sys.exit()

        except Exception as e:
            print(e.args)
            sys.exit()
Example #39
0
        print access.gethashespersec()
    except:
        print "\n---An error occurred---\n"

elif cmd == "getinfo":
    print access.getinfo()
elif cmd == "getpeerinfo":
    print access.getpeerinfo()
elif cmd == "addnode":
    cmd = raw_input("node addr:port to add?: ")
    print access.addnode(cmd, "add")
elif cmd == "getnewaddress":
    try:
        acct = raw_input("Enter an account name: ")
        try:
            print access.getnewaddress(acct)
        except:
            print access.getnewaddress()
    except:
        print "\n---An error occurred---\n"

elif cmd == "getreceivedbyaccount":
    try:
        acct = raw_input("Enter an account (optional): ")
        mc = raw_input("Minimum confirmations (optional): ")
        try:
            print access.getreceivedbyaccount(acct, mc)
        except:
            print access.getreceivedbyaccount()
    except:
        print "\n---An error occurred---\n"
Example #40
0
total_in = 0;

unspent.sort (key=lambda coin: abs(to_satoshi (coin['amount']) - target_in));

for coin in unspent:
  total_in += to_satoshi (coin['amount']);
  donation += donation_per_input;
  inputs.append (dict (txid = coin['txid'], vout = coin['vout']));
  if total_in > target_in:
    break;

if donation < donation_minimum:
  donation = donation_minimum;

# FIND OUTPUTS
outputs = dict ();
outputs[donation_address] = from_satoshi (donation);
total_in -= donation;
while total_in > target_out:
  outputs[service.getnewaddress()] = from_satoshi (target_out);
  total_in -= target_out;
outputs[service.getnewaddress()] = from_satoshi (total_in);

# Make the transaction
print service.createrawtransaction (inputs, outputs);





class Wallet(object):
    """ Wallet with one account
    """

    def __init__(self, uri, account_name, fee):
        self._connection = AuthServiceProxy(uri)
        self._account_name = account_name

        self._connection.settxfee(fee)

    @property
    def account_name(self):
        return self._account_name

    def get_address(self):
        return self._connection.getnewaddress(self._account_name)

    def get_accounts(self):
        return self._connection.listaccounts(MINIMUM_CONFIRMATIONS)

    @property
    def balance(self):
        return self._connection.getbalance(self._account_name, MINIMUM_CONFIRMATIONS)

    def move_to_account(self, source_account, destination_account, amount, comment=None):
        if amount > Decimal('0.0'):
            self._connection.move(source_account, destination_account, amount, MINIMUM_CONFIRMATIONS, comment)
        elif amount < Decimal('0.0'):
            self._connection.move(destination_account, source_account, -amount, MINIMUM_CONFIRMATIONS, comment)
        # just fall through if amount == 0.0 as there is nothing to do

    def transfer_to(self, destination, amount):
        """ Create an address for each wallet and transfer the funds between them
        """
        to_address = destination.get_address()

        validation = self._connection.validateaddress(to_address)
        if validation['isvalid']:
            try:
                transaction_id = self._connection.sendfrom(self._account_name, to_address, amount, MINIMUM_CONFIRMATIONS, 'out', 'in')
                if transaction_id is not None:
                    transaction_details = self._connection.gettransaction(transaction_id)
                    fee = transaction_details.get(u'fee')
                    # LOG.info('transaction_id %r, fee %r', transaction_id, fee)
                    return transaction_id, fee
                else:
                    return None, None
            except JSONRPCException as json_ex:
                LOG.exception('JSON Exception calling sendfrom(%s,_,%d) %r' % (self._account_name, amount, json_ex.error))
                raise
        else:
            return None, None

    def find_transaction(self, including_transaction, confirmations=MINIMUM_CONFIRMATIONS):
        for transaction in self._connection.listtransactions():
            if transaction.get(u'txid') == including_transaction:
                if transaction[u'confirmations'] >= confirmations:
                    return True
        return False

    def wait_for_transaction(
        self, including_transaction, confirmations=MINIMUM_CONFIRMATIONS, max_wait=60, secs_between_checks=0.1
    ):
        current = time()
        timeout = current + max_wait
        while current < timeout and not self.find_transaction(including_transaction, confirmations):
            sleep(secs_between_checks)
            current = time()
        return current < timeout

    def __repr__(self):
        """ Provide a string representation
        """
        return "{}('{}')".format(self.__class__.__name__, self._account_name)
Example #42
0
            raw_change_address: change_amount_string
        })
    privkey = rpc_connection.dumpprivkey(address)

    sign_raw_transaction = rpc_connection.signrawtransaction(
        hexstring, [{
            "txid": txid,
            "vout": vout,
            "redeemScript": redeemScript,
            "scriptPubKey": scriptPubKey,
            "amount": first_unspent_amount
        }], [privkey])
    raw_hash = sign_raw_transaction.get("hex")
    ret = rpc_connection.sendrawtransaction(raw_hash)
    return ret


if __name__ == '__main__':
    # https://test-insight.bitpay.com/tx/8a73f907a1b44dc2ba00e4a9e0dacb57b745f5cdbd336541be71dca8971c9a93
    #ret = submit_raw(rpc_user, rpc_password, rpc_host)
    rpc_connection = AuthServiceProxy("http://{}:{}@{}".format(
        rpc_user, rpc_password, rpc_host))
    send_addr = rpc_connection.getnewaddress()
    recv_addr = rpc_connection.getnewaddress()
    ret = submit_raw(rpc_user,
                     rpc_password,
                     rpc_host,
                     send_addr=send_addr,
                     recv_addr=recv_addr)
    print(ret)
				self.in_value = Decimal(txo["value"])
			else:
				block = sidechain.getblock(sidechain.getblockhash(i))
				for tx in sidechain.batch_([["getrawtransaction", txhash, 1] for txhash in block["tx"]]):
					self.check_tx(tx)
					if self.in_value > self.target_value:
						break
			if self.in_value > self.target_value:
				break

		assert(self.in_value > self.target_value)

try:
	if args.command == "generate-one-of-one-multisig":
		if args.wallet == "sidechain-wallet":
			address = sidechain.getnewaddress()
			p2sh_res = sidechain.addmultisigaddress(1, [address])
		elif args.wallet == "mainchain-wallet":
			address = bitcoin.getnewaddress()
			p2sh_res = bitcoin.addmultisigaddress(1, [address])
		print("One-of-one address: %s" % address)
		print("P2SH address: %s" % p2sh_res)
	elif args.command == "send-to-sidechain":
		cht = os.popen("%s %s -g -r %s -d %s" % (contracthashtool_path, testnet_arg, redeem_script, args.p2shSideAddress))
		cht_read = cht.read()
		nonce = cht_read.split("\n")[0 + is_testnet][7:]
		full_contract = cht_read.split("\n")[1 + is_testnet][26:]
		send_address = cht_read.split("\n")[3 + is_testnet][40:]
		assert(cht.close() == None)
		if full_contract[0:8] != "50325348":
			print("You must use a P2SH address")
Example #44
0
class BTCRPCCall(object):
    def __init__(self, wallet="receive", currency="btc"):
        yml_config_reader = ConfigFileReader()
        url = yml_config_reader.get_rpc_server(currency=currency,
                                               wallet=wallet)

        self.access = AuthServiceProxy(url)

    def do_getinfo(self):
        return self.access.getinfo()

    def do_get_new_address(self):
        return self.access.getnewaddress()

    def do_set_account(self, address, account):
        return self.access.setaccount(address, account)

    def do_get_transaction(self, txid):
        try:
            return self.access.gettransaction(txid)
        except RuntimeError:
            # return simplejson.dumps ({u'error' : u'txid is not valid'})
            return None

    def do_list_transactions(self, account, count=10, from_index=0):
        try:
            return self.access.listtransactions(account, count, from_index)
        except RuntimeError:
            print "calling failure"

        def do_get_transaction(self, tx_id):
            try:
                return self.access.gettransaction(tx_id)
            except RuntimeError:
                #return simplejson.dumps ({u'error' : u'txid is not valid'})
                return None

    def amount_received_by_address(self, address="", confirms=0):
        return self.access.getreceivedbyaddress(address, confirms)

    def do_validate_address(self, address=""):
        return self.access.validateaddress(address)

    def list_transactions(self, account="", count=10, from_index=0):
        return self.access.listtransactions(account, count, from_index)

    def send_from(self, from_account="", to_address="", amount=0, minconf=1):
        return self.access.sendfrom(from_account, to_address, amount, minconf)

    def get_received_amount_by_account(self, account="", minconf=1):
        return self.access.getreceivedbyaccount(account, minconf)

    def get_balance(self, account="", minconf=1):
        return self.access.getbalance(account, minconf)

    def get_wallet_balance(self):
        return self.access.getbalance()

    def move(self, from_account="", to_account="", amount=0, minconf=1):
        return self.access.move(from_account, to_account, amount, minconf)

    def list_accounts(self, confirmations=1):
        return self.access.listaccounts(confirmations)

    def list_received_by_address(self, confirmations=1, include_empty=False):
        return self.access.listreceivedbyaddress(confirmations, include_empty)

    def get_addresses_by_account(self, account):
        return self.access.getaddressesbyaccount(account)

    def set_tx_fee(self, amount):
        return self.access.settxfee(amount)

    def send_to_address(self, address, amount, subtractfeefromamount=True):
        return self.access.sendtoaddress(address, amount, "", "",
                                         subtractfeefromamount)

    # amount is type of dictionary
    def send_many(self, from_account="", minconf=1, **amounts):
        log.info("From account: %s", from_account)
        log.info("To accounts: %s", json.dumps(amounts))
        amounts_string = json.dumps(amounts['amounts'])
        amounts_object = json.loads(amounts_string)
        try:
            return True, self.access.sendmany(from_account, amounts_object,
                                              minconf)
        except JSONRPCException as ex:
            return False, ex
        except socket.error as e:
            return False, e
Example #45
0
    logging.info("successfully connected to coinhouse api")
except:
    logging.exception("could not connect to coinhouse api")
    sys.exit()


# provide btc addresses to rails and try to clear transactions periodically
round = 0;
while True:
    try:
        round += 1

        # check, how many new addresses coinhouse needs
        address_gen_count = ch_api.how_many_addresses_are_needed()
        # generate and get new addresses from bitcoind
        new_addresses = list(btcd.getnewaddress(btc_account_incoming) for n in range(address_gen_count))
        # register addresses in rails for showing them to end users
        for address in new_addresses:
            ch_api.give_new_addresses(address)

        # check incoming addresses for balance (not yet verified). 
        # if there is enough btc on the account
        # we transfer it to verifying. otherwise it is forced to await more btcs
        incoming_addresses = btcd.getaddressesbyaccount(btc_account_incoming)
        for address in incoming_addresses:
            balance = btcd.getreceivedbyaddress(address, 0)
            if balance > 0:
                is_paid_enough = ch_api.register_payment(address, balance)
                if is_paid_enough:
                    btcd.setaccount(address, btc_account_verifying)