
'''miscellaneous utilities.'''

import pypeerassets.constants

def testnet_or_mainnet(node):
    '''check if local node is configured to testnet or mainnet'''

    if node.getinfo()["testnet"] is True:
        return "testnet"
    else:
        return "mainnet"

def load_p2th_privkeys_into_node(node):
    '''load production p2th privkey into local node'''

    if testnet_or_mainnet(node) is "testnet":
        try:
            node.importprivkey(testnet_PAPROD, "PAPROD")
            assert testnet_PAPROD_addr in node.getaddressesbyaccount("PAPROD")
        except Exception:
            return {"error": "Loading P2TH privkey failed."}
    else:
        try:
            node.importprivkey(mainnet_PAPROD, "PAPROD")
            assert mainnet_PAPROD_addr in node.getaddressesbyaccount("PAPROD")
        except Exception:
            return {"error": "Loading P2TH privkey failed."}

def load_test_p2th_privkeys_into_node(node):
    '''load test p2th privkeys into local node'''

    if testnet_or_mainnet(node) is "testnet":
        try:
            node.importprivkey(testnet_PATEST, "PATEST")
            assert mainnet_PATEST_addr in node.getaddressesbyaccount("PATEST")
        except Exception:
            return {"error": "Loading P2TH privkey failed."}

    else:
        try:
            node.importprivkey(mainnet_PATEST, "PATEST")
            assert mainnet_PAPROD_addr in node.getaddressesbyaccount("PATEST")
        except Exception:
            return {"error": "Loading P2TH privkey failed."}

def find_deck_spawns(node, prod_or_test):
    '''find deck spawn transactions via local node, it requiers that Deck spawn P2TH were imported in local node.'''

    if prod_or_test == "prod":
        decks = [i["txid"] for i in node.listtransactions("PAPROD")]
    else:
        decks = [i["txid"] for i in node.listtransaction("PATEST")]

    return decks

@@ -26,16 +26,32 @@
 es.'''%0A%0A
+import binascii%0A
 import p
@@ -1880,8 +1880,683 @@
 n decks%0A
+%0Adef read_tx_opreturn(node, txid):%0A    '''Decode OP_RETURN message from %3Ctxid%3E'''%0A%0A    vouts = node.getrawtransaction(txid, 1)%5B'vout'%5D%0A%0A    for vout in vouts:%0A        asm = vout%5B'scriptPubKey'%5D%5B'asm'%5D%0A        n = asm.find('OP_RETURN')%0A        if n == -1:%0A            continue%0A        else:%0A            # add 10 because 'OP_RETURN ' is 10 characters%0A            n += 10%0A            data = asm%5Bn:%5D%0A            n = data.find(' ')%0A            #make sure that we don't include trailing opcodes%0A            if n == -1:%0A                return binascii.unhexlify(data)%0A            else:%0A                return binascii.unhexlify(data%5B:n%5D)%0A    return %7B'error': 'OP_RETURN not found'%7D%0A

add method to read op_return from txid