Пример #1
0
 def reconnect(self):
   if self.server:
     del self.server
   if self.host is None:
     self.server = btc.Proxy()
   else:
     self.server = btc.Proxy("http://"+str(self.host)+"/",service_port=self.port)
     self.server.setConnParams(self.host, self.port, self.user, self.password)
Пример #2
0
 def send_bitcoin_cmd(self, *args):
     try:
         return self.bitcoin_api.call(*args)
     except ConnectionResetError:
         self.bitcoin_api = rpc.Proxy(btc_conf_file=self.btc_config)
         return self.send_bitcoin_cmd(*args)
     except BrokenPipeError:
         self.bitcoin_api = rpc.Proxy(btc_conf_file=self.btc_config)
         return self.send_bitcoin_cmd(*args)
Пример #3
0
 def __init__(cls):
     self.bitcoind = rpc.Proxy()
     self.pusher_client = pusher.Pusher(app_id,
                                        key,
                                        secret,
                                        cluster=u'cluster')
     return cls
Пример #4
0
def main(allchains=False, activeDepth=10):
    global bu
    bu = btc.Proxy()  # service_port=18332)

    chainTooOld = 10000
    # print bu.getbalance()

    chains = bu._call("getchaintips")
    # print chains
    highest = chains[0]["height"]

    for chain in chains:
        if highest - chainTooOld > chain["height"]:  # Don't show old forks
            continue
        if allchains or chain["status"] == "active":
            blkid = chain["hash"]
            blk = None
            try:
                blk = bu._call("getblock", blkid)
            except btc.JSONRPCError, e:  # We don't have info about this block
                #print "  " + str(e)
                #continue  # Skip showing old chains
                pass
            printChainHeader(chain, blk)

            if chain["status"] == "active":
                depth = activeDepth
            else:
                depth = min(10, chain["branchlen"])
            for i in range(0, depth):
                print "Block -%d" % i
                try:
                    # print blkid
                    #blk = bu.getblock(blkid)
                    blk = bu._call("getblock", blkid)
                except btc.JSONRPCError, e:  # We don't have info about this block
                    print("No info on block %d " % i) + str(e)
                    continue
                if blk["size"] > 1000000: pfx = "**  "
                else: pfx = "    "
                coinbaseHash = blk["tx"][0]
                try:
                    rawcoinbase = bu._call("getrawtransaction", coinbaseHash)
                    coinbase = bu._call("decoderawtransaction", rawcoinbase)
                    data = binascii.unhexlify(
                        coinbase["vin"][0]["coinbase"][8:])
                except Exception, e:
                    data = str(e)
                print "--- %sDate: %s Height: %6d Size: %8d  NumTx: %6d  Ver: %8x  Hash: %s " % (
                    pfx, datetime.datetime.fromtimestamp(
                        blk["time"]).strftime('%Y-%m-%d %H:%M:%S'),
                    blk['height'], blk["size"], len(
                        blk["tx"]), blk["version"], blkid)
                print "MSG:", data
                try:
                    blkid = blk["previousblockhash"]
                except KeyError, e:  # first block
                    print "first block"
                    break
 def wait_for_bitcoind_start(self, process, btc_conf_file):
     while True:
         if process.poll() is not None:
             raise Exception('bitcoind exited with status %i during initialization' % process.returncode)
         try:
             self.bitcoin_api = rpc.Proxy(btc_conf_file=btc_conf_file)
             blocks = self.bitcoin_api.getblockcount()
             break # break out of loop on success
         except Exception:
             time.sleep(0.25)
             continue
Пример #6
0
def get_cached_batch_raw_transactions(tx_hashes):
    tx_hashes = json.loads(tx_hashes)  # for lru_cache
    call_id = 0
    call_list = []
    for tx_hash in tx_hashes:
        call_list.append({
            "method": 'getrawtransaction',
            "params": [tx_hash, 1],
            "jsonrpc": "2.0",
            "id": call_id
        })
        call_id += 1

    if config.TESTNET:
        bitcoinlib.SelectParams('testnet')
    proxy = bitcoin_rpc.Proxy(service_url=config.BACKEND_URL)
    return proxy._batch(call_list)
Пример #7
0
    def htlc_p2sh(self) -> str:
        # TODO: cache the generated address
        # We create connections on the fly because they'll time out quickly if
        # we don't
        bitcoind = rpc.Proxy()

        # We can decipher the hash of the preimage without explicitly asking
        # for it by taking it out of the payment request supplied
        decoded_pr = json.loads(
            to_json(lnd.decode_payment_request(self.bolt11_invoice)))
        hashed_preimage = decoded_pr['payment_hash']

        # Once these assignments are made, we want to lock them in so this
        # functions generates deterministically
        if not self.final_address_pubkey:
            final_address = bitcoind.getnewaddress()
            seckey = bitcoind.dumpprivkey(final_address)
            self.final_address_pubkey = seckey.pub.hex()

        if not self.redeemblock:
            curr_blockheight = bitcoind.getblockcount()
            self.redeemblock = curr_blockheight + self.lockduration

        # HTLC locking script
        txin_redeemScript = CScript([
            OP_IF, OP_SHA256,
            bytes(hashed_preimage, 'utf8'), OP_EQUALVERIFY, OP_DUP, OP_HASH160,
            bytes(Hash160(bytes(self.final_address_pubkey,
                                'utf8'))), OP_ELSE, self.redeemblock,
            OP_CHECKLOCKTIMEVERIFY, OP_DROP, OP_DUP, OP_HASH160,
            bytes(Hash160(bytes(self.refund_address, 'utf8'))), OP_ENDIF,
            OP_EQUALVERIFY, OP_CHECKSIG
        ])

        self.save()

        # Generate a P2SH address from the locking script
        txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey()
        txin_p2sh_address = CBitcoinAddress.from_scriptPubKey(
            txin_scriptPubKey)
        return str(txin_p2sh_address)
Пример #8
0
def get_new_address():
    proxy = rpc.Proxy()
    newaddress = str(proxy.getnewaddress())
    return newaddress
Пример #9
0
def get_balance():
    proxy = rpc.Proxy()
    balance = proxy.getbalance()
    print("balance: " + str(balance))
    return float(balance)
Пример #10
0
def send_bitcoins(address, amount):
    proxy = rpc.Proxy()
    transaction = proxy.sendtoaddress(address, amount)
    print(transaction)
    return transaction
Пример #11
0
def getreceivedbyaddress(address):
    proxy = rpc.Proxy()
    amount = proxy.getreceivedbyaddress(address)
    print(amount)
    return amount
Пример #12
0
 def send_bitcoin_cmd(self, *args):
     try:
         self.bitcoin_api.call(*args)
     except BrokenPipeError:
         self.bitcoin_api = rpc.Proxy(btc_conf_file=self.btc_config)
         self.send_bitcoin_cmd(*args)
Пример #13
0
 def htlc_p2sh_address_balance(self) -> str:
     """ Lazy loading of live address received balance """
     bitcoind = rpc.Proxy()
     return str(
         Decimal(bitcoind.getreceivedbyaddress(self.htlc_p2sh)) * 10**-8)
Пример #14
0
import os

from lndgrpc import LNDClient
from bitcoin import rpc
import bitcoin

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

NETWORK = "testnet"

bitcoin.SelectParams(NETWORK)
BITCOINRPC = rpc.Proxy()

LNDRPC = LNDClient("127.0.0.1:10009",
                   network=NETWORK,
                   macaroon_filepath='/home/harshagoli/Limbo/admin.macaroon',
                   cert_filepath='/home/harshagoli/Limbo/tls.cert')

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#p&o16c**q2t%x19o$_-cj@wvm6yei$x#=x@ld2&s51zaaxq7_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition
Пример #15
0
def get_proxy():
    if config.TESTNET:
        bitcoinlib.SelectParams('testnet')
    proxy = bitcoinlib_rpc.Proxy(service_url=config.BACKEND_RPC,
                                 timeout=config.HTTP_TIMEOUT)
    return proxy
Пример #16
0
lengthMsgHex = lengthMsgHex[2:]  # remove 0x from the beginning of the string
if len(lengthMsgHex) == 1:
    lengthMsgHex = "0" + lengthMsgHex

# OP_RETURN message should be 80 bytes max
if lengthMsg > 80:
    print(
        "Your message's size is greater than 80 bytes. Please start again and choose a smaller message. Size: ",
        lengthMsg, "bytes\n")
    quit()

#
# display the balance of the wallet
#

rpc = bitcoinlibrpc.Proxy()
print("\nWallet total balance: ", rpc.getbalance() / nbrSatIn1BTC, "BTC")
print("\n")

#
# display the list of UTXOs to the user and let him choose one.
#

listUTXOs = rpc.listunspent(1)

if len(listUTXOs) == 0:
    print(
        "There is no UTXO available. Please create an address and send funds to it.\n"
    )
    quit()