예제 #1
0
    def test_transaction_deserialization_and_serialization(self):
        # Transaction from Decred unit test.
        raw_tx = x('01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0200f2052a01000000abab434104d64bdfd09eb1c5fe295abdeb1dca4281be988e2da0b6c1c6a59dc226c28624e18175e851c96b973d81b01cc31f047834bc06d6d6edf620d184241a6aed8b63a6ac00e1f50500000000bcbc434104d64bdfd09eb1c5fe295abdeb1dca4281be988e2da0b6c1c6a59dc226c28624e18175e851c96b973d81b01cc31f047834bc06d6d6edf620d184241a6aed8b63a6ac00000000000000000112121212121212121515151534343434070431dc001b0162')
        tx = Transaction.deserialize(raw_tx)

        self.assertEqual(1, tx.version)
        self.assertEqual(0, tx.locktime)
        self.assertEqual(0, tx.expiry)

        # Test input.
        self.assertEqual(1, len(tx.txins))
        txin = tx.txins[0]
        self.assertEqual(1302123111085380114, txin.value)
        self.assertEqual(353703189, txin.block_height)
        self.assertEqual(875836468, txin.block_index)
        self.assertEqual(x('0431dc001b0162'), txin.sig_script)
        self.assertEqual(4294967295, txin.sequence)

        self.assertEqual(2, len(tx.txouts))
        # Test output 0.
        txout = tx.txouts[0]
        self.assertEqual(5000000000, txout.value)
        self.assertEqual(43947, txout.version)
        self.assertEqual(x('4104d64bdfd09eb1c5fe295abdeb1dca4281be988e2da0b6c1c6a59dc226c28624e18175e851c96b973d81b01cc31f047834bc06d6d6edf620d184241a6aed8b63a6ac'), txout.pk_script)
        # Test output 1.
        txout = tx.txouts[1]
        self.assertEqual(100000000, txout.value)
        self.assertEqual(48316, txout.version)
        self.assertEqual(x('4104d64bdfd09eb1c5fe295abdeb1dca4281be988e2da0b6c1c6a59dc226c28624e18175e851c96b973d81b01cc31f047834bc06d6d6edf620d184241a6aed8b63a6ac'), txout.pk_script)

        self.assertEqual(b2x(raw_tx), b2x(tx.serialize()))
예제 #2
0
def insight_parse_raw_tx(res):
    version = int(res.get('version'))
    locktime = int(res.get('locktime'))
    vin = []
    vout = []
    for i in res.get('vin'):
        prev_txid = i['txid']
        prev_n = int(i['n'])

        seq = int(i['sequence'])
        script_asm = i['scriptSig']['asm']
        script = Script.from_human(script_asm)

        tx_outpoint = COutPoint(lx(prev_txid), prev_n)
        tx_input = CTxIn(tx_outpoint, x(script.get_hex()), seq)
        vin.append(tx_input)

    for o in res.get('vout'):
        value = float(o['value'])
        value = int(value * pow(10, 8))

        script_asm = o['scriptPubKey']['asm']
        script = Script.from_human(script_asm)

        tx_output = CTxOut(value, x(script.get_hex()))
        vout.append(tx_output)

    tx = Transaction(vin, vout, locktime, version)
    return b2x(tx.serialize())
예제 #3
0
 def T(serialized1, serialized2, are_equal):
     script1 = CScript(x(serialized1))
     script2 = CScript(x(serialized2))
     if are_equal:
         self.assertEqual(script1, script2)
     else:
         self.assertNotEqual(script1, script2)
예제 #4
0
def abe_parse_raw_tx(res):
    version = int(res.get('ver'))
    locktime = int(res.get('lock_time'))
    vin = []
    vout = []
    for i in res.get('in'):
        prev_txid = i['prev_out']['hash']
        prev_n = int(i['prev_out']['n'])
        tx_outpoint = COutPoint(lx(prev_txid), prev_n)

        scriptSig = Script(x( i['raw_scriptSig'] ))
        sequence = int(i['sequence'])
        
        tx_input = CTxIn(tx_outpoint, x(scriptSig.get_hex()), sequence)
        vin.append(tx_input)

    for o in res.get('out'):
        value = float(o['value'])
        value = int(value * pow(10, 8))

        script = Script(x( o['raw_scriptPubKey'] ))
        tx_output = CTxOut(value, x(script.get_hex()))
        vout.append(tx_output)

    tx = Transaction(vin, vout, locktime, version)
    return b2x(tx.serialize())
예제 #5
0
    def test_create_from_string(self):
        """Create CBitcoinAddress's from strings"""

        def T(str_addr, expected_bytes, expected_version, expected_class):
            addr = CBitcoinAddress(str_addr)
            self.assertEqual(addr.to_bytes(), expected_bytes)
            self.assertEqual(addr.__class__, expected_class)
            if isinstance(addr, CBase58BitcoinAddress):
                self.assertEqual(addr.nVersion, expected_version)
            elif isinstance(addr, CBech32BitcoinAddress):
                self.assertEqual(addr.witver, expected_version)

        T('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
          x('62e907b15cbf27d5425399ebf6f0fb50ebb88f18'), 0,
          P2PKHBitcoinAddress)

        T('37k7toV1Nv4DfmQbmZ8KuZDQCYK9x5KpzP',
          x('4266fc6f2c2861d7fe229b279a79803afca7ba34'), 5,
          P2SHBitcoinAddress)

        T('BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4',
          x('751e76e8199196d454941c45d1b3a323f1433bd6'), 0,
          P2WPKHBitcoinAddress)

        T('bc1qc7slrfxkknqcq2jevvvkdgvrt8080852dfjewde450xdlk4ugp7szw5tk9',
          x('c7a1f1a4d6b4c1802a59631966a18359de779e8a6a65973735a3ccdfdabc407d'), 0,
          P2WSHBitcoinAddress)
예제 #6
0
 def unsigned_script_sig(self):
     if self.contract:
         if self.refund:
             return [script.OP_FALSE, x(self.contract)]
         elif self.secret:
             return [x(self.secret), script.OP_TRUE, x(self.contract)]
     return []
예제 #7
0
    def test_from_nonstd_scriptPubKey(self):
        """CBitcoinAddress.from_scriptPubKey() with non-standard scriptPubKeys"""

        # Bad P2SH scriptPubKeys

        # non-canonical pushdata
        scriptPubKey = CScript(
            x('a94c14000000000000000000000000000000000000000087'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # Bad P2PKH scriptPubKeys

        # Missing a byte
        scriptPubKey = CScript(
            x('76a914000000000000000000000000000000000000000088'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # One extra byte
        scriptPubKey = CScript(
            x('76a914000000000000000000000000000000000000000088acac'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # One byte changed
        scriptPubKey = CScript(
            x('76a914000000000000000000000000000000000000000088ad'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)
예제 #8
0
def spend_p2sh_mediator(redeemScript, txins_str, amounts, daddrs, sig, rein):
    txin_redeemScript = CScript(x(redeemScript))
    txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey()
    txins_obj = []
    for txin_str in txins_str.split():
        txin_list = txin_str.split("-")
        txins_obj.append(
            CMutableTxIn(COutPoint(lx(txin_list[0]), int(txin_list[1]))))
    txouts = []
    len_amounts = len(amounts)
    for i in range(0, len_amounts):
        txouts.append(
            CMutableTxOut(
                round(amounts[i], 8) * COIN,
                CBitcoinAddress(daddrs[i]).to_scriptPubKey()))
    tx = CMutableTransaction(txins_obj, txouts)
    seckey = CBitcoinSecret(rein.user.dkey)
    ntxins = len(txins_obj)
    sig_list = []
    for s in sig.split():
        sig_list.append(x(s))
    sig2_str = ""
    for i in range(0, ntxins):
        sighash = SignatureHash(txin_redeemScript, tx, i, SIGHASH_ALL)
        sig2 = seckey.sign(sighash) + x("01")
        sig2_str += " " + b2x(sig2)
        txins_obj[i].scriptSig = CScript(
            [OP_0, sig2, sig_list[i], txin_redeemScript])
        VerifyScript(txins_obj[i].scriptSig, txin_scriptPubKey, tx, i,
                     (SCRIPT_VERIFY_P2SH, ))
    tx_bytes = tx.serialize()
    hash = sha256(sha256(tx_bytes).digest()).digest()
    txid = b2x(hash[::-1])
    txid_causeway = broadcast_tx(b2x(tx_bytes), rein)
    return (txid, sig2_str[1:])
예제 #9
0
    def test_from_nonstd_scriptPubKey(self):
        """CBitcoinAddress.from_scriptPubKey() with non-standard scriptPubKeys"""

        # Bad P2SH scriptPubKeys

        # non-canonical pushdata
        scriptPubKey = CScript(x('a94c14000000000000000000000000000000000000000087'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # Bad P2PKH scriptPubKeys

        # Missing a byte
        scriptPubKey = CScript(x('76a914000000000000000000000000000000000000000088'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # One extra byte
        scriptPubKey = CScript(x('76a914000000000000000000000000000000000000000088acac'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # One byte changed
        scriptPubKey = CScript(x('76a914000000000000000000000000000000000000000088ad'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)
예제 #10
0
 def T(serialized1, serialized2, are_equal):
     script1 = CScript(x(serialized1))
     script2 = CScript(x(serialized2))
     if are_equal:
         self.assertEqual(script1, script2)
     else:
         self.assertNotEqual(script1, script2)
예제 #11
0
def partial_spend_p2sh_mediator(redeemScript,
                                rein,
                                mediator_address,
                                mediator_sig=False):
    txin_redeemScript = CScript(x(redeemScript))
    txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey()
    txin_p2sh_address = CBitcoinAddress.from_scriptPubKey(txin_scriptPubKey)
    (txins, total_value) = unspent_txins(txin_p2sh_address, rein.testnet)
    if len(txins) == 0:
        raise ValueError('No unspent txins found')
    txins_str = ""
    txins_obj = []
    for txid, vout in txins:
        txins_str += " " + txid + "-" + str(vout)
        txins_obj.append(CMutableTxIn(COutPoint(lx(txid), vout)))
    fee = 0.00025
    amount = round(total_value - fee, 8)
    if amount <= 0:
        raise ValueError('Not enough value in the inputs')
    if mediator_sig:
        txout = CMutableTxOut(
            amount * COIN,
            CBitcoinAddress(mediator_address).to_scriptPubKey())
        tx = CMutableTransaction(txins_obj, [txout])
        seckey = CBitcoinSecret(rein.user.dkey)
        ntxins = len(txins_obj)
        sig = ""
        for i in range(0, ntxins):
            sighash = SignatureHash(txin_redeemScript, tx, i, SIGHASH_ALL)
            sig += " " + b2x(seckey.sign(sighash) + x("01"))
        return (txins_str[1:], "{:.8f}".format(amount), str(mediator_address),
                sig[1:])
    return (txins_str[1:], "{:.8f}".format(amount), str(mediator_address))
예제 #12
0
    def test_from_invalid_pubkeys(self):
        """Create P2PKHBitcoinAddress's from invalid pubkeys"""

        # first test with accept_invalid=True
        def T(invalid_pubkey, expected_str_addr):
            addr = P2PKHBitcoinAddress.from_pubkey(invalid_pubkey,
                                                   accept_invalid=True)
            self.assertEqual(str(addr), expected_str_addr)

        T(x(''), '1HT7xU2Ngenf7D4yocz2SAcnNLW7rK8d4E')
        T(
            x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c72'
              ), '1L9V4NXbNtZsLjrD3nkU7gtEYLWRBWXLiZ')

        # With accept_invalid=False we should get CBitcoinAddressError's
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_pubkey(x(''))
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_pubkey(
                x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c72'
                  ))
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_pubkey(
                CPubKey(
                    x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c72'
                      )))
    def test_tokenize_roundtrip(self):
        def T(serialized_script, expected_tokens, test_roundtrip=True):
            serialized_script = x(serialized_script)
            script_obj = CScript(serialized_script)
            actual_tokens = list(script_obj)
            self.assertEqual(actual_tokens, expected_tokens)

            if test_roundtrip:
                recreated_script = CScript(actual_tokens)
                self.assertEqual(recreated_script, serialized_script)

        T('', [])

        # standard pushdata
        T('00', [OP_0])
        T('0100', [b'\x00'])
        T('4b' + 'ff'*0x4b, [b'\xff'*0x4b])

        # non-optimal pushdata
        T('4c00', [b''], False)
        T('4c04deadbeef', [x('deadbeef')], False)
        T('4d0000', [b''], False)
        T('4d0400deadbeef', [x('deadbeef')], False)
        T('4e00000000', [b''], False)
        T('4e04000000deadbeef', [x('deadbeef')], False)

        # numbers
        T('00', [0x0])
        T('4f', [OP_1NEGATE])
        T('51', [0x1])
        T('52', [0x2])
        T('53', [0x3])
        T('54', [0x4])
        T('55', [0x5])
        T('56', [0x6])
        T('57', [0x7])
        T('58', [0x8])
        T('59', [0x9])
        T('5a', [0xa])
        T('5b', [0xb])
        T('5c', [0xc])
        T('5d', [0xd])
        T('5e', [0xe])
        T('5f', [0xf])

        # some opcodes
        T('9b', [OP_BOOLOR])
        T('9a9b', [OP_BOOLAND, OP_BOOLOR])
        T('ff', [OP_INVALIDOPCODE])
        T('fafbfcfd', [CScriptOp(0xfa), CScriptOp(0xfb), CScriptOp(0xfc), CScriptOp(0xfd)])

        # all three types
        T('512103e2a0e6a91fa985ce4dda7f048fca5ec8264292aed9290594321aa53d37fdea32410478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc345552ae',
          [1,
           x('03e2a0e6a91fa985ce4dda7f048fca5ec8264292aed9290594321aa53d37fdea32'),
           x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455'),
           2,
           OP_CHECKMULTISIG])
예제 #14
0
    def test(self):
        sig = BlockHeaderSig('bitcoin-mainnet',
                             x('010000000000000000000000000000000000000000000000000000000000000000000000'),
                             x('29ab5f49ffff001d1dac2b7c'))

        block_index = set([lx('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f')])
        nTime = sig.verify(x('3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a'), block_index)

        self.assertEqual(nTime, 1231006505)
예제 #15
0
def build_mandatory_multisig(mandatory_pubkey, other_pubkeys):
    txin_redeemScript = CScript([
        x(mandatory_pubkey), OP_CHECKSIGVERIFY, 1,
        x(other_pubkeys[0]),
        x(other_pubkeys[1]), 2, OP_CHECKMULTISIG
    ])
    txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey()
    txin_p2sh_address = CBitcoinAddress.from_scriptPubKey(txin_scriptPubKey)
    return (b2x(txin_redeemScript), str(txin_p2sh_address))
예제 #16
0
def build_2_of_3(pubkeys):
    txin_redeemScript = CScript(
        [2,
         x(pubkeys[0]),
         x(pubkeys[1]),
         x(pubkeys[2]), 3, OP_CHECKMULTISIG])
    txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey()
    txin_p2sh_address = CBitcoinAddress.from_scriptPubKey(txin_scriptPubKey)
    return (b2x(txin_redeemScript), str(txin_p2sh_address))
예제 #17
0
    def test_bloom_create_insert_key(self):
        filter = CBloomFilter(2, 0.001, 0, CBloomFilter.UPDATE_ALL)

        pubkey = x('045B81F0017E2091E2EDCD5EECF10D5BDD120A5514CB3EE65B8447EC18BFC4575C6D5BF415E54E03B1067934A0F0BA76B01C6B9AB227142EE1D543764B69D901E0')
        pubkeyhash = bitcoin.core.Hash160(pubkey)

        filter.insert(pubkey)
        filter.insert(pubkeyhash)

        self.assertEqual(filter.serialize(), x('038fc16b080000000000000001'))
예제 #18
0
def rebroadcast_unconfirmed(db, libbitcoin_client, testnet=False):
    # pylint: disable=cell-var-from-loop
    for raw in db.transactions.get_transactions():
        def cb_chain(ec, result):
            if ec == "not_found":
                tx.broadcast(libbitcoin_client)
            else:
                db.transactions.delete_transaction(raw[0])
        tx = BitcoinTransaction.from_serialized(x(raw[0]), testnet)
        libbitcoin_client.fetch_transaction(x(tx.get_hash()), cb_chain)
예제 #19
0
def get_radd_from_pub(pub):
    try:
        taker_addr = str(P2PKHBitcoinAddress.from_pubkey(x("02"+pub)))
    except:
        try:
            taker_addr = str(P2PKHBitcoinAddress.from_pubkey(x("03"+pub)))
        except:
            pass
        taker_addr = pub
        pass
    return str(taker_addr)
예제 #20
0
    def redeem_contract(self, contract, secret):
        print("Parsing script for redeem_contract...")
        scriptarray = self.parse_script(contract.redeemScript)
        redeemblocknum = scriptarray[8]
        redeemPubKey = P2PKHBitcoinAddress.from_bytes(x(scriptarray[6]))
        refundPubKey = P2PKHBitcoinAddress.from_bytes(x(scriptarray[13]))
        p2sh = contract.p2sh
        #checking there are funds in the address
        amount = self.check_funds(p2sh)
        if(amount == 0):
            print("address ", p2sh, " not funded")
            quit()
        fundtx = self.find_transaction_to_address(p2sh)
        amount = fundtx['amount'] / COIN
        # print("Found fund_tx: ", fundtx)
        p2sh = P2SHBitcoinAddress(p2sh)
        if fundtx['address'] == p2sh:
            print("Found {0} in p2sh {1}, redeeming...".format(amount, p2sh))

            blockcount = self.bitcoind.getblockcount()
            print("\nCurrent blocknum at time of redeem on Zcash:", blockcount)
            if blockcount < int(redeemblocknum):
                print('redeemPubKey', redeemPubKey)
                zec_redeemScript = CScript(x(contract.redeemScript))
                txin = CMutableTxIn(fundtx['outpoint'])
                txout = CMutableTxOut(fundtx['amount'] - FEE, redeemPubKey.to_scriptPubKey())
                # Create the unsigned raw transaction.
                tx = CMutableTransaction([txin], [txout])
                sighash = SignatureHash(zec_redeemScript, tx, 0, SIGHASH_ALL)
                # TODO: protect privkey better, separate signing from rawtx creation
                privkey = self.bitcoind.dumpprivkey(redeemPubKey)
                sig = privkey.sign(sighash) + bytes([SIGHASH_ALL])
                preimage = secret.encode('utf-8')
                txin.scriptSig = CScript([sig, privkey.pub, preimage, OP_TRUE, zec_redeemScript])

                # print("txin.scriptSig", b2x(txin.scriptSig))
                txin_scriptPubKey = zec_redeemScript.to_p2sh_scriptPubKey()
                print('Raw redeem transaction hex: ', b2x(tx.serialize()))
                VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH,))
                print("Script verified, sending raw transaction...")
                txid = self.bitcoind.sendrawtransaction(tx)
                fund_tx = str(fundtx['outpoint'])
                redeem_tx =  b2x(lx(b2x(txid)))
                return  {"redeem_tx": redeem_tx, "fund_tx": fund_tx}
            else:
                print("nLocktime exceeded, refunding")
                print('refundPubKey', refundPubKey)
                txid = self.bitcoind.sendtoaddress(refundPubKey, fundtx['amount'] - FEE)
                fund_tx = str(fundtx['outpoint'])
                refund_tx =  b2x(lx(b2x(txid)))
                return  {"refund_tx": refund_tx, "fund_tx": fund_tx}
        else:
            print("No contract for this p2sh found in database", p2sh)
예제 #21
0
 def create_signature(self, privkey, reedem_script):
     """
     Exports a raw signature suitable for use in a multisig transaction
     """
     seckey = CBitcoinSecret.from_secret_bytes(x(bitcointools.encode_privkey(privkey, "hex")))
     signatures = []
     for i in range(len(self.tx.vin)):
         sighash = SignatureHash(CScript(x(reedem_script)), self.tx, i, SIGHASH_ALL)
         signatures.append({
             "index": i,
             "signature": (seckey.sign(sighash) + struct.pack('<B', SIGHASH_ALL)).encode("hex")
         })
     return signatures
예제 #22
0
def get_radd_from_pub(pub):
    try:
        addr = str(P2PKHBitcoinAddress.from_pubkey(x(pub)))
    except Exception as e:
        try:
            addr = str(P2PKHBitcoinAddress.from_pubkey(x(pub)))
        except Exception as e:
            print(colorize(str(e) + ": " + pub, 'red'))
            print(e)
            addr = pub
            pass
        pass
    return str(addr)
예제 #23
0
def get_radd_from_pub(pub):
    try:
        taker_addr = str(P2PKHBitcoinAddress.from_pubkey(x("02"+pub)))
    except Exception as e:
        print(e)
        try:
            taker_addr = str(P2PKHBitcoinAddress.from_pubkey(x("03"+pub)))
        except Exception as e:
            print(e)
            taker_addr = pub
            pass
        pass
    return str(taker_addr)
예제 #24
0
 def test_init_with_field_keyword_args(self):
     ins = (
         CTxIn(COutPoint(lx('537ecb89e5ed7e872f988447432e6791c0a58b069c4ec8647e1683a383e867a3'), 0),
               x('473044022043b9aee9187effd7e6c7bc444b09162570f17e36b4a9c02cf722126cc0efa3d502200b3ba14c809fa9a6f7f835cbdbbb70f2f43f6b30beaf91eec6b8b5981c80cea50121025edf500f18f9f2b3f175f823fa996fbb2ec52982a9aeb1dc2e388a651054fb0f'))
     )
     outs = (
         CTxOut(114263, x('76a91495efca2c6a6f0e0f0ce9530219b48607a962e77788ac')),
         CTxOut(2125893, x('76a914f28abfb465126d6772dcb4403b9e1ad2ea28a03488ac'))
     )
     fields_data = {'Timestamp': 1432478808}
     tx = Transaction(ins, outs, 0, 2, peercoin_fields, fields_data)
     self.assertEqual(tx.fields, peercoin_fields)
     self.assertEqual(tx.Timestamp, 1432478808)
예제 #25
0
 def test_init_with_field_keyword_args(self):
     ins = (
         CTxIn(COutPoint(lx('537ecb89e5ed7e872f988447432e6791c0a58b069c4ec8647e1683a383e867a3'), 0),
               x('473044022043b9aee9187effd7e6c7bc444b09162570f17e36b4a9c02cf722126cc0efa3d502200b3ba14c809fa9a6f7f835cbdbbb70f2f43f6b30beaf91eec6b8b5981c80cea50121025edf500f18f9f2b3f175f823fa996fbb2ec52982a9aeb1dc2e388a651054fb0f'))
     )
     outs = (
         CTxOut(114263, x('76a91495efca2c6a6f0e0f0ce9530219b48607a962e77788ac')),
         CTxOut(2125893, x('76a914f28abfb465126d6772dcb4403b9e1ad2ea28a03488ac'))
     )
     fields_data = {'Timestamp': 1432478808}
     tx = Transaction(ins, outs, 0, 2, peercoin_fields, fields_data)
     self.assertEqual(tx.fields, peercoin_fields)
     self.assertEqual(tx.Timestamp, 1432478808)
예제 #26
0
 def create_signature(self, privkey, reedem_script):
     """
     Exports a raw signature suitable for use in a multisig transaction
     """
     seckey = CBitcoinSecret.from_secret_bytes(x(bitcointools.encode_privkey(privkey, "hex")))
     signatures = []
     for i in range(len(self.tx.vin)):
         sighash = SignatureHash(CScript(x(reedem_script)), self.tx, i, SIGHASH_ALL)
         signatures.append({
             "index": i,
             "signature": (seckey.sign(sighash) + struct.pack('<B', SIGHASH_ALL)).encode("hex")
         })
     return signatures
예제 #27
0
def mock_listunspent_mainnet(self, addrs):
    output1 = {
        'outpoint':
        COutPoint(
            lx('34eb81bc0d1a822369f75174fd4916b1ec490d8fbcba33168e820cc78a52f608'
               ), 0),
        'confirmations':
        123,
        'address':
        P2PKHBitcoinAddress('13yNf3azc8sUrjf6UFjUCRZx4B6JnQ4XeJ'),
        'spendable':
        False,
        'amount':
        6342,
        'solvable':
        False,
        'scriptPubKey':
        CScript([
            OP_DUP, OP_HASH160,
            x('cc0a909c4c83068be8b45d69b60a6f09c2be0fda'), OP_EQUALVERIFY,
            OP_CHECKSIG
        ]),
        'account':
        ''
    }
    output2 = {
        'address':
        P2PKHBitcoinAddress('13yNf3azc8sUrjf6UFjUCRZx4B6JnQ4XeJ'),
        'amount':
        2750,
        'account':
        '',
        'spendable':
        False,
        'solvable':
        False,
        'confirmations':
        456,
        'outpoint':
        COutPoint(
            lx('6773785b4dc5d2cced67d26fc0820329307a8e10dfaef50d506924984387bf0b'
               ), 1),
        'scriptPubKey':
        CScript([
            OP_DUP, OP_HASH160,
            x('cc0a909c4c83068be8b45d69b60a6f09c2be0fda'), OP_EQUALVERIFY,
            OP_CHECKSIG
        ])
    }
    unspent_outputs = [output1, output2]
    return unspent_outputs
예제 #28
0
    def test_from_invalid_scriptPubKey(self):
        """CBitcoinAddress.from_scriptPubKey() with invalid scriptPubKeys"""

        # We should raise a CBitcoinAddressError, not any other type of error

        # Truncated P2SH
        scriptPubKey = CScript(x('a91400000000000000000000000000000000000000'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # Truncated P2PKH
        scriptPubKey = CScript(x('76a91400000000000000000000000000000000000000'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)
예제 #29
0
    def test_from_invalid_scriptPubKey(self):
        """CBitcoinAddress.from_scriptPubKey() with invalid scriptPubKeys"""

        # We should raise a CBitcoinAddressError, not any other type of error

        # Truncated P2SH
        scriptPubKey = CScript(x('a91400000000000000000000000000000000000000'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)

        # Truncated P2PKH
        scriptPubKey = CScript(x('76a91400000000000000000000000000000000000000'))
        with self.assertRaises(CBitcoinAddressError):
            CBitcoinAddress.from_scriptPubKey(scriptPubKey)
예제 #30
0
    def test_create_from_string(self):
        """Create CBitcoinAddress's from strings"""
        def T(str_addr, expected_bytes, expected_nVersion, expected_class):
            addr = CBitcoinAddress(str_addr)
            self.assertEqual(addr.to_bytes(), expected_bytes)
            self.assertEqual(addr.nVersion, expected_nVersion)
            self.assertEqual(addr.__class__, expected_class)

        T('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
          x('62e907b15cbf27d5425399ebf6f0fb50ebb88f18'), 0,
          P2PKHBitcoinAddress)

        T('37k7toV1Nv4DfmQbmZ8KuZDQCYK9x5KpzP',
          x('4266fc6f2c2861d7fe229b279a79803afca7ba34'), 5, P2SHBitcoinAddress)
예제 #31
0
    def multisign(self, sigs, redeem_script):
        """
        Signs a multisig transaction.

        Args:
            sigs: a `list` of `dict` with format: {"index": 0, "signatures": [sig1, sig2]}
            redeem_script: the redeem script in hex

        """
        for sig in sigs:
            i = sig["index"]
            s = sig["signatures"]
            self.tx.vin[i].scriptSig = CScript([OP_0, x(s[0]), x(s[1]), CScript(x(redeem_script))])
            VerifyScript(self.tx.vin[i].scriptSig, CScript(x(redeem_script)).to_p2sh_scriptPubKey(),
                         self.tx, i, (SCRIPT_VERIFY_P2SH,))
예제 #32
0
    def test_from_bare_checksig_scriptPubKey(self):
        def T(hex_scriptpubkey, expected_str_address):
            scriptPubKey = CScript(x(hex_scriptpubkey))
            addr = P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey)
            self.assertEqual(str(addr), expected_str_address)

            # now test that CBitcoinAddressError is raised with accept_non_canonical_pushdata=False
            with self.assertRaises(CBitcoinAddressError):
                P2PKHBitcoinAddress.from_scriptPubKey(
                    scriptPubKey, accept_bare_checksig=False)

        # compressed
        T(
            '21000000000000000000000000000000000000000000000000000000000000000000ac',
            '14p5cGy5DZmtNMQwTQiytBvxMVuTmFMSyU')

        # uncompressed
        T(
            '410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ac',
            '1QLFaVVt99p1y18zWSZnespzhkFxjwBbdP')

        # non-canonical encoding
        T(
            '4c21000000000000000000000000000000000000000000000000000000000000000000ac',
            '14p5cGy5DZmtNMQwTQiytBvxMVuTmFMSyU')

        # odd-lengths are *not* accepted
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_scriptPubKey(
                x('2200000000000000000000000000000000000000000000000000000000000000000000ac'
                  ))
예제 #33
0
    def get_public_key(self, f="hex", public_key=None):
        if public_key == None:
            public_key = self.public_key

        #O4 = uncompressed.
        public_key_hex = "04" + binascii.hexlify(public_key).decode("utf-8")
        if self.use_compression:
            public_key = binascii.unhexlify(public_key_hex)
            public_key = self.compress_public_key(public_key)
            public_key_hex = binascii.hexlify(public_key).decode("utf-8")
        else:
            public_key = binascii.unhexlify(public_key_hex)

        cpub = CPubKey(x(public_key_hex))

        if f == "bin":
            return public_key

        elif f == "hex":
            return public_key_hex.decode("utf-8")

        elif f == "cpub":
            return cpub

        elif f == "hash":
            return Hash160(cpub)

        else:
            return base64.b64encode(public_key).decode("utf-8")
예제 #34
0
    def test_from_valid_pubkey(self):
        """Create P2PKHBitcoinAddress's from valid pubkeys"""

        def T(pubkey, expected_str_addr):
            addr = P2PKHBitcoinAddress.from_pubkey(pubkey)
            self.assertEqual(str(addr), expected_str_addr)

        T(x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71'),
          '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
        T(x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455'),
          '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T')

        T(CPubKey(x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71')),
          '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
        T(CPubKey(x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455')),
          '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T')
예제 #35
0
def analyze_key_pair(key_pair):
    """
    Converts a key pair to different formats which is useful
    for working with Bitcoin Script.
    """
    if "priv" not in key_pair:
        key_pair["priv"] = None
    pub = CPubKey(x(key_pair["pub"]))

    addr = None
    if "addr" in key_pair:
        addr = key_pair["addr"]
    """
    The Hash160 function in Python-bitcoin lib actually
    wraps around sha256 hash so every call to Hash160
    also sha256 hashes the input before ripemd160 hashing,
    meaning it the output is valid for address hashes.
    """
    return {
        "addr": {
            "base58": addr
        },
        "pub": {
            "hash": Hash160(pub),
            "hex": key_pair["pub"],
            "bin": pub
        },
        "priv": {
            "wif": key_pair["priv"],
            "hex": None,
            "bin": None
        }
    }
예제 #36
0
    def test_from_valid_pubkey(self):
        """Create P2PKHBitcoinAddress's from valid pubkeys"""

        def T(pubkey, expected_str_addr):
            addr = P2PKHBitcoinAddress.from_pubkey(pubkey)
            self.assertEqual(str(addr), expected_str_addr)

        T(x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71'),
          '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
        T(x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455'),
          '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T')

        T(CPubKey(x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71')),
          '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
        T(CPubKey(x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455')),
          '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T')
예제 #37
0
  def test_build_send_script(self):
    """ Run simple sanity checks on script generation """
    sender_public_key = x('02160dcd36ac266ea8dea3e483410ace007f5a648bac2df9b11b4f93641b421411')
    recipient_public_key = x('02f0383460e3d2609b3c69f4630bcc66abaf5f7419c06a6cc9a433eacf2258ff5b')
    secret_hash = x('f303d286d0047d2f3bad0e07a6a2350a783a30281229790925e3ef580c51de5e')
    script_elements = []
    for sig_element in build_send_out_script(sender_public_key, recipient_public_key, secret_hash):
      script_elements.append(sig_element)

    # Check the length of the script is as expected
    self.assertEqual(16, len(script_elements))

    # Verify each input is present
    self.assertEqual(Hash160(recipient_public_key), script_elements[2])
    self.assertEqual(Hash160(sender_public_key), script_elements[8])
    self.assertEqual(secret_hash, script_elements[13])
예제 #38
0
class CoreLtcMainParams(bitcoin.core.CoreChainParams):
    NAME = 'litecoin_main'
    GENESIS_BLOCK = CAltcoinBlock.deserialize(
        x('010000000000000000000000000000000000000000000000000000000000000000000000d9ced4ed1130f7b7faad9be25323ffafa33232a17c3edf6cfd97bee6bafbdd97b9aa8e4ef0ff0f1ecd513f7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4804ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536ffffffff0100f2052a010000004341040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9ac00000000'
          ))
    SUBSIDY_HALVING_INTERVAL = 840000
    PROOF_OF_WORK_LIMIT = 2**256 - 1 >> 20
예제 #39
0
class CoreDogeMainParams(bitcoin.core.CoreChainParams):
    NAME = 'dogecoin_main'
    GENESIS_BLOCK = CAltcoinBlock.deserialize(
        x('010000000000000000000000000000000000000000000000000000000000000000000000696ad20e2dd4365c7459b4a4a5af743d5e92c6da3229e6532cd605f6533f2a5b24a6a152f0ff0f1e678601000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff1004ffff001d0104084e696e746f6e646fffffffff010058850c020000004341040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9ac00000000'
          ))
    SUBSIDY_HALVING_INTERVAL = 100000
    PROOF_OF_WORK_LIMIT = 2**256 - 1 >> 20
예제 #40
0
    def test_create_from_string_specify_network(self):
        """Create CBitcoinAddress's from strings, and override the default network parameters"""

        def T(str_addr, expected_bytes, expected_nVersion, expected_class):
            addr = CBitcoinAddress(str_addr, network=bitcoin.TestNetParams())
            self.assertEqual(addr.to_bytes(), expected_bytes)
            self.assertEqual(addr.nVersion, expected_nVersion)
            self.assertEqual(addr.__class__, expected_class)

        T('mpXwg4jMtRhuSpVq4xS3HFHmCmWp9NyGKt',
          x('62e907b15cbf27d5425399ebf6f0fb50ebb88f18'), 111,
          P2PKHBitcoinAddress)

        T('2MyJKxYR2zNZZsZ39SgkCXWCfQtXKhnWSWq',
          x('4266fc6f2c2861d7fe229b279a79803afca7ba34'), 196,
          P2SHBitcoinAddress)
예제 #41
0
    def make_unsigned(cls, outpoints, output_address, tx_fee=TRANSACTION_FEE, testnet=False, out_value=None):
        """
        Build an unsigned transaction.

        Args:
            outpoints: A `list` of `dict` objects which contain a txid, vout, value, and scriptPubkey.
            output_address: The address to send the full value (minus the tx fee) of the inputs to.
            tx_fee: The Bitcoin network fee to be paid on this transaction.
            testnet: Should this transaction be built for testnet?
            out_value: used if you want to specify a specific output value otherwise the full value
                of the inputs (minus the tx fee) will be used.
        """
        # build the inputs from the outpoints object
        SelectParams("testnet" if testnet else "mainnet")
        txins = []
        in_value = 0
        for outpoint in outpoints:
            in_value += outpoint["value"]
            txin = CMutableTxIn(COutPoint(lx(outpoint["txid"]), outpoint["vout"]))
            txin.scriptSig = CScript(x(outpoint["scriptPubKey"]))
            txins.append(txin)

        # build the output
        value = out_value if out_value is not None else (in_value - tx_fee)
        txout = CMutableTxOut(value, CBitcoinAddress(output_address).to_scriptPubKey())

        # make the transaction
        tx = CMutableTransaction(txins, [txout])

        return BitcoinTransaction(tx)
예제 #42
0
    def getblockheader(self, block_hash, verbose=False):
        """Get block header <block_hash>

        verbose - If true a dict is returned with the values returned by
                  getblockheader that are not in the block header itself
                  (height, nextblockhash, etc.)

        Raises IndexError if block_hash is not valid.
        """
        try:
            block_hash = b2lx(block_hash)
        except TypeError:
            raise TypeError('%s.getblockheader(): block_hash must be bytes; got %r instance' %
                    (self.__class__.__name__, block_hash.__class__))
        try:
            r = self._call('getblockheader', block_hash, verbose)
        except InvalidAddressOrKeyError as ex:
            raise IndexError('%s.getblockheader(): %s (%d)' %
                    (self.__class__.__name__, ex.error['message'], ex.error['code']))

        if verbose:
            nextblockhash = None
            if 'nextblockhash' in r:
                nextblockhash = lx(r['nextblockhash'])
            return {'confirmations':r['confirmations'],
                    'height':r['height'],
                    'mediantime':r['mediantime'],
                    'nextblockhash':nextblockhash,
                    'chainwork':x(r['chainwork'])}
        else:
            return CBlockHeader.deserialize(unhexlify(r))
예제 #43
0
    def test_create_from_string(self):
        """Create CBitcoinAddress's from strings"""

        def T(str_addr, expected_bytes, expected_nVersion, expected_class):
            addr = CBitcoinAddress(str_addr)
            self.assertEqual(addr.to_bytes(), expected_bytes)
            self.assertEqual(addr.nVersion, expected_nVersion)
            self.assertEqual(addr.__class__, expected_class)

        T('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
          x('62e907b15cbf27d5425399ebf6f0fb50ebb88f18'), 0,
          P2PKHBitcoinAddress)

        T('37k7toV1Nv4DfmQbmZ8KuZDQCYK9x5KpzP',
          x('4266fc6f2c2861d7fe229b279a79803afca7ba34'), 5,
          P2SHBitcoinAddress)
예제 #44
0
    async def parse_solutions(self):
        sols, sol_size = [], GetSolutionSize()
        async for line in self.solver.stdout:
            line = stri(line)
            if line.startswith('Nonce'):
                break
            if line.startswith('Total'):
                raise SolverException('Solver stopped before valid solution found.')
            if len(line) != sol_size*2:
                raise SolverException("Solver returned unexpected solution of size != {:d}:\n{}"
                        .format(sol_size, line))
            sols.append(x(line))
        _, nonce, solc, _ = line.split()
        nonce = x(nonce[:-1]) # TODO or lx?

        return (nonce, sols)
예제 #45
0
def adjust_transaction(tx_hex):
    # if you don't want change you wallet signature code
    # you can use this to adjust high S signature to a canonical signature
    tx = CTransaction.deserialize(x(tx_hex))
    for vin in tx.vin:
        script_lst = list(vin.scriptSig)
        sig = script_lst[0]
        # normal signature format <sig> <pubkey>
        if len(script_lst) == 2 and not IsLowDERSignature(sig):
            low_s_sig = signature_to_low_s(sig)#.encode('hex')
            #print sig.encode('hex'), low_s_sig.encode('hex')
            script_lst[0] = low_s_sig
            vin.scriptSig = CScript(script_lst)
        # 2/2 or 2/3 multisig format <0> <signature> <signature> <redeemscript>
        elif len(script_lst) == 4:
            script_lst_new = []
            for idx, sig in enumerate(script_lst[1:3]):
                if not IsLowDERSignature(sig):
                    low_s_sig = signature_to_low_s(sig)#.encode('hex')
                    #print sig.encode('hex'), low_s_sig.encode('hex')
                    script_lst_new.append(low_s_sig)
                else:
                    script_lst_new.append(sig)
            script_lst_new.append(script_lst[3])
            vin.scriptSig = "\x00" + CScript(script_lst_new)
    return b2x(tx.serialize())
예제 #46
0
    def fundrawtransaction(self, given_transaction, *args, **kwargs):
        """
        Make up some inputs for the given transaction.
        """
        # just use any txid here
        vintxid = lx("99264749804159db1e342a0c8aa3279f6ef4031872051a1e52fb302e51061bef")

        if isinstance(given_transaction, str):
            given_bytes = x(given_transaction)
        elif isinstance(given_transaction, CMutableTransaction):
            given_bytes = given_transaction.serialize()
        else:
            raise FakeBitcoinProxyException("Wrong type passed to fundrawtransaction.")

        # this is also a clever way to not cause a side-effect in this function
        transaction = CMutableTransaction.deserialize(given_bytes)

        for vout_counter in range(0, self._num_fundrawtransaction_inputs):
            txin = CMutableTxIn(COutPoint(vintxid, vout_counter))
            transaction.vin.append(txin)

        # also allocate a single output (for change)
        txout = make_txout()
        transaction.vout.append(txout)

        transaction_hex = b2x(transaction.serialize())

        return {"hex": transaction_hex, "fee": 5000000}
    def test_repr(self):
        def T(script, expected_repr):
            actual_repr = repr(script)
            self.assertEqual(actual_repr, expected_repr)

        T( CScript([]),
          'CScript([])')

        T( CScript([1]),
          'CScript([1])')

        T( CScript([1, 2, 3]),
          'CScript([1, 2, 3])')

        T( CScript([1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP]),
          "CScript([1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP])")

        T(CScript(unhexlify(b'0001ff515261ff')),
          "CScript([x(''), x('ff'), 1, 2, OP_NOP, OP_INVALIDOPCODE])")

        # truncated scripts
        T(CScript(unhexlify(b'6101')),
          "CScript([OP_NOP, x('')...<ERROR: PUSHDATA(1): truncated data>])")

        T(CScript(unhexlify(b'614bff')),
          "CScript([OP_NOP, x('ff')...<ERROR: PUSHDATA(75): truncated data>])")

        T(CScript(unhexlify(b'614c')),
          "CScript([OP_NOP, <ERROR: PUSHDATA1: missing data length>])")

        T(CScript(unhexlify(b'614c0200')),
          "CScript([OP_NOP, x('00')...<ERROR: PUSHDATA1: truncated data>])")
예제 #48
0
    def getblockheader(self, block_hash, verbose=False):
        """Get block header <block_hash>

        verbose - If true a dict is returned with the values returned by
                  getblockheader that are not in the block header itself
                  (height, nextblockhash, etc.)

        Raises IndexError if block_hash is not valid.
        """
        try:
            block_hash = b2lx(block_hash)
        except TypeError:
            raise TypeError(
                '%s.getblockheader(): block_hash must be bytes; got %r instance'
                % (self.__class__.__name__, block_hash.__class__))
        try:
            r = self._call('getblockheader', block_hash, verbose)
        except InvalidAddressOrKeyError as ex:
            raise IndexError('%s.getblockheader(): %s (%d)' %
                             (self.__class__.__name__, ex.error['message'],
                              ex.error['code']))

        if verbose:
            nextblockhash = None
            if 'nextblockhash' in r:
                nextblockhash = lx(r['nextblockhash'])
            return {
                'confirmations': r['confirmations'],
                'height': r['height'],
                'mediantime': r['mediantime'],
                'nextblockhash': nextblockhash,
                'chainwork': x(r['chainwork'])
            }
        else:
            return CBlockHeader.deserialize(unhexlify(r))
예제 #49
0
    def test_repr(self):
        def T(script, expected_repr):
            actual_repr = repr(script)
            self.assertEqual(actual_repr, expected_repr)

        T(CScript([]), 'CScript([])')

        T(CScript([1]), 'CScript([1])')

        T(CScript([1, 2, 3]), 'CScript([1, 2, 3])')

        T(
            CScript(
                [1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP]),
            "CScript([1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP])"
        )

        T(CScript(unhexlify(b'0001ff515261ff')),
          "CScript([x(''), x('ff'), 1, 2, OP_NOP, OP_INVALIDOPCODE])")

        # truncated scripts
        T(CScript(unhexlify(b'6101')),
          "CScript([OP_NOP, x('')...<ERROR: PUSHDATA(1): truncated data>])")

        T(
            CScript(unhexlify(b'614bff')),
            "CScript([OP_NOP, x('ff')...<ERROR: PUSHDATA(75): truncated data>])"
        )

        T(CScript(unhexlify(b'614c')),
          "CScript([OP_NOP, <ERROR: PUSHDATA1: missing data length>])")

        T(CScript(unhexlify(b'614c0200')),
          "CScript([OP_NOP, x('00')...<ERROR: PUSHDATA1: truncated data>])")
예제 #50
0
        def T(hex_scriptpubkey, expected_str_address):
            scriptPubKey = CScript(x(hex_scriptpubkey))
            addr = P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey)
            self.assertEqual(str(addr), expected_str_address)

            # now test that CBitcoinAddressError is raised with accept_non_canonical_pushdata=False
            with self.assertRaises(CBitcoinAddressError):
                P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey, accept_bare_checksig=False)
예제 #51
0
 def check_raw_tx(self):
     txt = str(self.raw_tx_edit.toPlainText())
     try:
         tx = Transaction.deserialize(x(txt))
     except Exception:
         tx = None
     self.tx = tx
     self.model.set_tx(tx)
    def test_path_from_msg_to_txid(self):
        def T(msg, tx):
            path = path_from_msg_to_txid(msg, tx)
            self.assertEqual(path(msg), tx.GetHash())

        tx = CTransaction.deserialize(x('0100000001e853c9e0c133547fd9e162b1d3860dd0f27d5b9b8a7430d28896c00fbb3f1bc7000000008c49304602210095bcd54ebd0caa7cee75f0f89de472a765e6ef4b98c5fd4b32c7f9d4905db9ae022100ebd3f668e3a1a36d56e30184c27531dbb9fc136c84b1282be562064d86997d1e014104727eb4fdcc90658cd26abe7dcb0ae7297810b15b9e27c32bcf8e3edd934901968806dc18b1276d7273cc4c223feee0070361ed947888a3cef422bebfede96e08ffffffff020065cd1d000000001976a91468c6c2b3c0bc4a8eeb10d16a300d627a31a3b58588ac0008af2f000000001976a9141d87f0a54a1d704ffc70eae83b025698bc0fdcfc88ac00000000'))

        # txid in vin
        T(lx('c71b3fbb0fc09688d230748a9b5b7df2d00d86d3b162e1d97f5433c1e0c953e8'), tx)

        # part of a script
        T(x('1d87f0a54a1d704ffc70eae83b025698bc0fdcfc'), tx)

        # beginning of the tx
        T(x('0100000001e853c9e0c133547fd9'), tx)

        # end of the tx
        T(x('98bc0fdcfc88ac00000000'), tx)
예제 #53
0
def get_unspent_txouts(source, return_confirmed=False):
    """returns a list of unspent outputs for a specific address
    @return: A list of dicts, with each entry in the dict having the following keys:
    """
    # Get all coins.
    outputs = {}
    if util.is_multisig(source):
        pubkeyhashes = util.pubkeyhash_array(source)
        raw_transactions = blockchain.searchrawtransactions(pubkeyhashes[1])
    else:
        pubkeyhashes = [source]
        raw_transactions = blockchain.searchrawtransactions(source)

    canonical_address = util.canonical_address(source)

    for tx in raw_transactions:
        for vout in tx['vout']:
            scriptpubkey = vout['scriptPubKey']
            if script.scriptpubkey_to_address(CScript(x(scriptpubkey['hex']))) == canonical_address:
                txid = tx['txid']
                confirmations = tx['confirmations'] if 'confirmations' in tx else 0
                outkey = '{}{}'.format(txid, vout['n'])
                if outkey not in outputs or outputs[outkey]['confirmations'] < confirmations:
                    coin = {'amount': float(vout['value']),
                            'confirmations': confirmations,
                            'scriptPubKey': scriptpubkey['hex'],
                            'txid': txid,
                            'vout': vout['n']
                           }
                    outputs[outkey] = coin
    outputs = outputs.values()

    # Prune away spent coins.
    unspent = []
    confirmed_unspent = []
    for output in outputs:
        spent = False
        confirmed_spent = False
        for tx in raw_transactions:
            for vin in tx['vin']:
                if 'coinbase' in vin: continue
                if (vin['txid'], vin['vout']) == (output['txid'], output['vout']):
                    spent = True
                    if 'confirmations' in tx and tx['confirmations'] > 0:
                        confirmed_spent = True
        if not spent:
            unspent.append(output)
        if not confirmed_spent and output['confirmations'] > 0:
            confirmed_unspent.append(output)

    unspent = sorted(unspent, key=lambda x: x['txid'])
    confirmed_unspent = sorted(confirmed_unspent, key=lambda x: x['txid'])

    if return_confirmed:
        return unspent, confirmed_unspent
    else:
        return unspent
예제 #54
0
        def T(serialized_script, expected_tokens, test_roundtrip=True):
            serialized_script = x(serialized_script)
            script_obj = CScript(serialized_script)
            actual_tokens = list(script_obj)
            self.assertEqual(actual_tokens, expected_tokens)

            if test_roundtrip:
                recreated_script = CScript(actual_tokens)
                self.assertEqual(recreated_script, serialized_script)
예제 #55
0
    def test_check_pub_key_encoding(self):
        tests = (
            (
                    "uncompressed ok",
                    x("0411db93e1dcdb8a016b49840f8c53bc1eb68" +
                            "a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf" +
                            "9744464f82e160bfa9b8b64f9d4c03f999b8643f656b" +
                            "412a3"),
                    True,
            ),
            (
                    "compressed ok",
                    x("02ce0b14fb842b1ba549fdd675c98075f12e9" +
                            "c510f8ef52bd021a9a1f4809d3b4d"),
                    True,
            ),
            (
                    "compressed ok",
                    x("032689c7c2dab13309fb143e0e8fe39634252" +
                            "1887e976690b6b47f5b2a4b7d448e"),
                    True,
            ),
            (
                    "hybrid",
                    x("0679be667ef9dcbbac55a06295ce870b07029" +
                            "bfcdb2dce28d959f2815b16f81798483ada7726a3c46" +
                            "55da4fbfc0e1108a8fd17b448a68554199c47d08ffb1" +
                            "0d4b8"),
                    False,
            ),
            (
                    "empty",
                    b'',
                    False,
            ),
        )

        flags = ScriptVerifyStrictEncoding
        for name, key, is_valid in tests:
            vm = Engine(_bchr(OP_NOP), Transaction(txins=(TxIn(),)), 0, flags, 0)
            if not is_valid:
                self.assertRaises(Exception, vm.check_pubkey_encoding, key)
            else:
                vm.check_pubkey_encoding(key)
예제 #56
0
파일: tx.py 프로젝트: mazaclub/hashmal
 def setData(self, index, value, role = Qt.EditRole):
     if not index.isValid() or not self.vout: return False
     tx_out = self.vout[index.row()]
     col = index.column()
     if col == 0:
         tx_out.nValue, _ = value.toULongLong()
     elif col == 1:
         tx_out.scriptPubKey = x(Script.from_human(str(value.toString())).get_hex())
     self.dataChanged.emit(self.index(index.row(), col), self.index(index.row(), col))
     return True