Exemplo n.º 1
0
    def __init__(self, AKeys, BKeys):
        bitcoin = BitcoinConnection(user=user, password=password, port=port)

        # get C's address, pubkey, privkey
        try:
            addressC = bitcoin.getnewaddress()
        except Exception, e:
            print "Caught: ", e
            sys.exit(1)
Exemplo n.º 2
0
    def __init__(self, AKeys, BKeys, CKeys, multisigAddress, state):
        bitcoin = BitcoinConnection(user=user, password=password, port=port)

        # create txs for return funds
        if state['success'] is True:
        # refer A's output to B

            # count the output value deduct the fee.
            outputValue = state['txA']['value'] / float(1 + feeRate) #

            rawTxToB_Txin = [
                        {   "txid"          : state['txA']['txid'],
                            "vout"          : 0,
                            "scriptPubKey"  : state['txA']['scriptPubKey'],
                            "redeemScript"  : multisigAddress['redeemScript']
                        }
                       ]
            rawTxToB_Txout = {
                            BKeys['address'] : outputValue
                            }
            # get rawTx's hex
            rawTxToB_Hex = bitcoin.createrawtransaction(rawTxToB_Txin, rawTxToB_Txout, state['txA']['color']).encode('utf-8')
            # sign by C
            rawTxToB_SignedByC = bitcoin.signrawtransaction(rawTxToB_Hex, rawTxToB_Txin, [CKeys['privkey']])['hex'].encode('utf-8')

        # refer B's output to A

            # count the output value deduct the fee.
            outputValue = state['txB']['value'] / float(1 + feeRate) #

            rawTxToA_Txin = [
                        {   "txid"          : state['txB']['txid'],
                            "vout"          : 0,
                            "scriptPubKey"  : state['txB']['scriptPubKey'],
                            "redeemScript"  : multisigAddress['redeemScript']
                        }
                       ]
            rawTxToA_Txout = {
                            AKeys['address'] : outputValue
                        }
            # get rawTx's hex
            rawTxToA_Hex = bitcoin.createrawtransaction(rawTxToA_Txin, rawTxToA_Txout, state['txB']['color']).encode('utf-8')
            # sign by C
            rawTxToA_SignedByC = bitcoin.signrawtransaction(rawTxToA_Hex, rawTxToA_Txin, [CKeys['privkey']])['hex'].encode('utf-8')
            self.ret = {
                    "HexTxToA" : rawTxToA_SignedByC,
                    "HexTxToB" : rawTxToB_SignedByC
                        }
Exemplo n.º 3
0
def connect_to_remote(user, password, host='localhost', port=8332):
    """
    Connect to remote or alternative local bitcoin client instance.

    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.
    """
    from bitcoinrpc.connection import BitcoinConnection

    return BitcoinConnection(user, password, host, port)
Exemplo n.º 4
0
def connect_to_remote(user,
                      password,
                      host='localhost',
                      port=8332,
                      use_https=False):
    """
    Connect to remote or alternative local bitcoin client instance.

    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.
    """
    return BitcoinConnection(user, password, host, port, use_https)
Exemplo n.º 5
0
    def __init__(self, uname=RPC_UNAME, pwd=RPC_PWD):
        self.connection = BitcoinConnection(uname,
                                            pwd,
                                            host='127.0.0.1',
                                            port=18332)
        self.daemon = Popen([
            'bitcoind', '-regtest', '-datadir=.', '-rpcuser={0}'.format(uname),
            '-rpcpassword={0}'.format(pwd)
        ])
        while True:
            try:
                self.get_balance()
                break
            except (sock_err, BitcoinException):
                sleep(0.1)
                continue

        @atexit.register
        def onexit():
            if self.daemon:
                self.daemon.terminate()
                self.daemon = None
Exemplo n.º 6
0
    def __init__(self, multisigAddress, AKeys, BKeys):
        bitcoin = BitcoinConnection(user=user, password=password, port=port)
        '''
        - need to verify
            1. address
            2. value
            3. comfirmations
        - need to record
            1. scriptPubKey
            2. value
        '''
        print bitcoin.listunspent().__dict__
        txidA = "2c4bbd08ce27702cd04ff69819ab44c4dd24d8f424fc91cbe9aa4acbe0997795"
        scriptPubKeyA = "a9148e373ae21e902662561dab6de709d20121dcd19487"
        valueA = float(100)
        colorA = int(0)

        txidB = "2c4bbd08ce27702cd04ff69819ab44c4dd24d8f424fc91cbe9aa4acbe0997795"
        scriptPubKeyB = "a9148e373ae21e902662561dab6de709d20121dcd19487"
        valueB = float(100)
        colorB = int(0)

        self.state = {
                "success"   : True,
                "txA"       :
                                {
                                    "txid"          : txidA,
                                    "scriptPubKey"  : scriptPubKeyA,
                                    "value"         : valueA,
                                    "color"         : colorA
                                },
                "txB"       :
                                {
                                    "txid"          : txidB,
                                    "scriptPubKey"  : scriptPubKeyB,
                                    "value"         : valueB,
                                    "color"         : colorB
                                }
                }
Exemplo n.º 7
0
def connect_to_local():
    """
    Connect to default bitcoin instance owned by this user, on this machine.
    
    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.
    """
    from bitcoinrpc.connection import BitcoinConnection
    from bitcoinrpc.config import read_default_config

    cfg = read_default_config()
    port = int(cfg.get('rpcport', '8332'))
    rcpuser = cfg.get('rpcuser', '')

    return BitcoinConnection(rcpuser, cfg['rpcpassword'], 'localhost', port)
Exemplo n.º 8
0
    def __init__(self, uname=RPC_UNAME, pwd=RPC_PWD):
        self.connection = BitcoinConnection(uname, pwd, host='127.0.0.1', port=18332)
        self.daemon = Popen(['bitcoind', '-regtest', '-datadir=.', '-rpcuser={0}'.format(uname), '-rpcpassword={0}'.format(pwd)])
        while True:
            try:
                self.get_balance()
                break
            except (sock_err, BitcoinException):
                sleep(0.1)
                continue

        @atexit.register
        def onexit():
            if self.daemon:
                self.daemon.terminate()
                self.daemon = None
Exemplo n.º 9
0
def connect_to_local(filename=None):
    """
    Connect to default bitcoin instance owned by this user, on this machine.

    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.

    Arguments:

        - `filename`: Path to a configuration file in a non-standard location (optional)
    """
    from bitcoinrpc.connection import BitcoinConnection
    from bitcoinrpc.config import read_default_config

    cfg = read_default_config(filename)
    port = int(cfg.get('rpcport', '18332' if cfg.get('testnet') else '8332'))
    rcpuser = cfg.get('rpcuser', '')

    return BitcoinConnection(rcpuser, cfg['rpcpassword'], 'localhost', port)
Exemplo n.º 10
0
class BTCMgr(object):
    def __init__(self, uname=RPC_UNAME, pwd=RPC_PWD):
        self.connection = BitcoinConnection(uname,
                                            pwd,
                                            host='127.0.0.1',
                                            port=18332)
        self.daemon = Popen([
            'bitcoind', '-regtest', '-datadir=.', '-rpcuser={0}'.format(uname),
            '-rpcpassword={0}'.format(pwd)
        ])
        while True:
            try:
                self.get_balance()
                break
            except (sock_err, BitcoinException):
                sleep(0.1)
                continue

        @atexit.register
        def onexit():
            if self.daemon:
                self.daemon.terminate()
                self.daemon = None

    def _test_get_pubkeys(self, amount):
        """
        generates a number of public keys which can be used to test things
        :param amount: number of keys to make
        :return: list of full public keys
        """
        addrs = [self.connection.getnewaddress() for i in xrange(amount)]
        return [
            addr_info['pubkey'] for addr_info in
            [self.connection.proxy.validateaddress(addr) for addr in addrs]
        ]

    def make_address(self, account):
        return self.connection.getnewaddress(account)

    def get_balance(self):
        return self.connection.listaccounts(as_dict=True)

    def send_to(self, tx_list):
        for tx in tx_list:
            account, target, amount = tx
            self.connection.sendfrom(account, target, amount)

    def make_multisig(self, min_signs, total_signs, pub_keys, account=''):
        addrs = [
            self.connection.getnewaddress()
            for i in xrange(total_signs - len(pub_keys))
        ]
        return self.connection.proxy.addmultisigaddress(
            min_signs, addrs + pub_keys, account)

    def withdraw_multisig(self, address, fee=Decimal(5e-5)):
        address_info = self.connection.proxy.validateaddress(address)
        account = address_info['account']
        signed_by = address_info['addresses']
        my_signatures = [
            addr for addr in signed_by
            if self.connection.proxy.validateaddress(addr)['ismine']
        ]
        withdraw_addr = self.connection.getnewaddress(account)
        UTXOs = self.connection.proxy.listunspent(1, 999999999, [address])

        for UTXO_from_msig in UTXOs:
            txid = UTXO_from_msig['txid']

            rawtx = self.connection.proxy.getrawtransaction(txid, 1)
            for UTXO_vout, vout in enumerate(rawtx['vout']):
                if address in vout['scriptPubKey']['addresses']:
                    break
            UTXO_outscr = vout['scriptPubKey']['hex']
            UTXO_sum = vout['value']
            redeem_script = UTXO_from_msig['redeemScript']
            newtx = self.connection.proxy.createrawtransaction(
                [{
                    'txid': txid,
                    'vout': UTXO_vout
                }], {withdraw_addr: float(UTXO_sum - fee)})

            privkeys = (self.connection.proxy.dumpprivkey(addr)
                        for addr in my_signatures)
            sign_complete = False
            while not sign_complete:
                privkey = privkeys.next()
                signed = self.connection.proxy.signrawtransaction(
                    newtx, [{
                        'txid': txid,
                        'vout': UTXO_vout,
                        'scriptPubKey': UTXO_outscr,
                        'redeemScript': redeem_script
                    }], [privkey])
                sign_complete = signed['complete']
                newtx = signed['hex']
            self.connection.proxy.sendrawtransaction(newtx)

    def get_transactions(self):
        return self.connection.proxy.listtransactions()

    def __del__(self):
        if self.daemon:
            self.daemon.terminate()
            self.daemon = None
Exemplo n.º 11
0
#exit()
#for order in Order.select():
#    print order.sender_address
    





#time.sleep(1000)

config = read_default_config()
print config
host="localhost"
print config["rpcuser"]
conn = BitcoinConnection(config["rpcuser"],config["rpcpassword"],config["rpcconnect"],config["rpcport"],0)

#try:
#    conn.move("testaccount", "testaccount2", 1.0)
#except InsufficientFunds,e:
#    print "Account does not have enough funds available!"


#balance = conn.getbalance()

#print "Balance: %f" % balance

#newadr = conn.getnewaddress();
#print "Newaddress: %s" % newadr

Exemplo n.º 12
0
class BTCMgr(object):
    def __init__(self, uname=RPC_UNAME, pwd=RPC_PWD):
        self.connection = BitcoinConnection(uname, pwd, host='127.0.0.1', port=18332)
        self.daemon = Popen(['bitcoind', '-regtest', '-datadir=.', '-rpcuser={0}'.format(uname), '-rpcpassword={0}'.format(pwd)])
        while True:
            try:
                self.get_balance()
                break
            except (sock_err, BitcoinException):
                sleep(0.1)
                continue

        @atexit.register
        def onexit():
            if self.daemon:
                self.daemon.terminate()
                self.daemon = None

    def _test_get_pubkeys(self, amount):
        """
        generates a number of public keys which can be used to test things
        :param amount: number of keys to make
        :return: list of full public keys
        """
        addrs = [self.connection.getnewaddress() for i in xrange(amount)]
        return [addr_info['pubkey'] for addr_info in [self.connection.proxy.validateaddress(addr) for addr in addrs]]

    def make_address(self, account):
        return self.connection.getnewaddress(account)

    def get_balance(self):
        return self.connection.listaccounts(as_dict=True)

    def send_to(self, tx_list):
        for tx in tx_list:
            account, target, amount = tx
            self.connection.sendfrom(account, target, amount)

    def make_multisig(self, min_signs, total_signs, pub_keys, account=''):
        addrs = [self.connection.getnewaddress() for i in xrange(total_signs - len(pub_keys))]
        return self.connection.proxy.addmultisigaddress(min_signs, addrs + pub_keys, account)

    def withdraw_multisig(self, address, fee=Decimal(5e-5)):
        address_info = self.connection.proxy.validateaddress(address)
        account = address_info['account']
        signed_by = address_info['addresses']
        my_signatures = [addr for addr in signed_by if self.connection.proxy.validateaddress(addr)['ismine']]
        withdraw_addr = self.connection.getnewaddress(account)
        UTXOs = self.connection.proxy.listunspent(1, 999999999, [address])

        for UTXO_from_msig in UTXOs:
            txid = UTXO_from_msig['txid']

            rawtx = self.connection.proxy.getrawtransaction(txid, 1)
            for UTXO_vout, vout in enumerate(rawtx['vout']):
                if address in vout['scriptPubKey']['addresses']:
                    break
            UTXO_outscr = vout['scriptPubKey']['hex']
            UTXO_sum = vout['value']
            redeem_script = UTXO_from_msig['redeemScript']
            newtx = self.connection.proxy.createrawtransaction([{'txid': txid, 'vout': UTXO_vout}],
                                                               {withdraw_addr: float(UTXO_sum - fee)})

            privkeys = (self.connection.proxy.dumpprivkey(addr) for addr in
                        my_signatures)
            sign_complete = False
            while not sign_complete:
                privkey = privkeys.next()
                signed = self.connection.proxy.signrawtransaction(newtx, [{'txid': txid, 'vout': UTXO_vout,
                                                                    'scriptPubKey': UTXO_outscr,
                                                                    'redeemScript': redeem_script}],
                                                                    [privkey])
                sign_complete = signed['complete']
                newtx = signed['hex']
            self.connection.proxy.sendrawtransaction(newtx)

    def get_transactions(self):
        return self.connection.proxy.listtransactions()

    def __del__(self):
        if self.daemon:
            self.daemon.terminate()
            self.daemon = None