Example #1
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)
Example #2
0
 def test(self):
     data = x(
         '5586e3531b857c5a3d7af6d512ec84161f4531b66daf2ad72a6f647e4164c8ae')
     k = CKey(data)
     self.assertEqual(k, data)
     expected_pub = x(
         '0392aef1ad6db10a2da4aa9f9e874fa28d5423eaa29ee83aa9acec01cc812903df'
     )
     self.assertEqual(k.pub, expected_pub)
     expected_uncompressed_pub = x(
         '0492aef1ad6db10a2da4aa9f9e874fa28d5423eaa29ee83aa9acec01cc812903df4c9b555eb62f0bf6dc4406b271365768737733ec8af4024809348ea594eef1f3'
     )
     k = CKey(data, compressed=False)
     self.assertEqual(k.pub, expected_uncompressed_pub)
Example #3
0
 def test_add_sub(self) -> None:
     k1 = CKey(x('5586e3531b857c5a3d7af6d512ec84161f4531b66daf2ad72a6f647e4164c8ae'))
     k2 = CKey(x('9e77dd4f6693461578e32e60e9c095023e1fc98ae3eaf0c53f645d53a5ead91e'))
     k_sum = CKey.add(k1, k2)
     pub_sum = CPubKey.add(k1.pub, k2.pub)
     self.assertEqual(pub_sum, k_sum.pub)
     if secp256k1_has_pubkey_negate:
         k_diff = CKey.sub(k1, k2)
         pub_diff = CPubKey.sub(k1.pub, k2.pub)
         self.assertEqual(pub_diff, k_diff.pub)
         self.assertEqual(k1, CKey.sub(k_sum, k2))
         self.assertEqual(k2, CKey.sub(k_sum, k1))
         self.assertEqual(k1, CKey.add(k_diff, k2))
         self.assertEqual(k2.negated(), CKey.sub(k_diff, k1))
         self.assertEqual(CKey.add(k2, k2), CKey.sub(k_sum, k_diff))
         self.assertEqual(k1.pub, CPubKey.sub(pub_sum, k2.pub))
         self.assertEqual(k2.pub, CPubKey.sub(pub_sum, k1.pub))
         self.assertEqual(k1.pub, CPubKey.add(pub_diff, k2.pub))
         self.assertEqual(k2.pub.negated(), CPubKey.sub(pub_diff, k1.pub))
         self.assertEqual(CPubKey.add(k2.pub, k2.pub),
                          CPubKey.sub(pub_sum, pub_diff))
         self.assertEqual(k1,
                          CKey.combine(k1, k2, k_sum,
                                       k2.negated(), k_sum.negated()))
         self.assertEqual(k1.pub,
                          CPubKey.combine(k1.pub, k2.pub, k_sum.pub,
                                          k2.pub.negated(),
                                          k_sum.pub.negated()))
         self.assertEqual(CKey.combine(k_sum, k2, k1, k_diff),
                          CKey.combine(k1, k2, k_sum, k_diff))
         self.assertEqual(CPubKey.combine(k_sum.pub, k2.pub, k1.pub,
                                          k_diff.pub),
                          CPubKey.combine(k1.pub, k2.pub, k_sum.pub,
                                          k_diff.pub))
         with self.assertRaises(ValueError):
             CKey.sub(k1, k1)
         with self.assertRaises(ValueError):
             CKey.combine(k1, k2, k1.negated(), k2.negated())
         with self.assertRaises(ValueError):
             CPubKey.sub(k1.pub, k1.pub)
         with self.assertRaises(ValueError):
             CPubKey.combine(k1.pub, k2.pub,
                             k1.pub.negated(), k2.pub.negated())
     else:
         logging.basicConfig()
         log = logging.getLogger("Test_CKey")
         log.warning('secp256k1 does not export pubkey negation function. '
                     'You should use newer version of secp256k1 library. '
                     'Tests that involve key substraction are skipped')
Example #4
0
    def test_p2sh_p2wpkh_signaturehash(self):
        unsigned_tx = x(
            '0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000'
        )
        scriptpubkey = CScript(
            x('001479091972186c449eb1ded22b78e40d009bdf0089'))
        value = coins_to_satoshi(10)

        address = CCoinAddress.from_scriptPubKey(scriptpubkey)
        self.assertEqual(
            SignatureHash(address.to_redeemScript(),
                          CTransaction.deserialize(unsigned_tx), 0,
                          SIGHASH_ALL, value, SIGVERSION_WITNESS_V0),
            x('64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6'
              ))
Example #5
0
    def test_p2wpkh_signaturehash(self):
        unsigned_tx = x(
            '0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000'
        )
        scriptpubkey = CScript(
            x('00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1'))
        value = coins_to_satoshi(6)

        address = CBech32BitcoinAddress.from_scriptPubKey(scriptpubkey)
        self.assertEqual(
            SignatureHash(address.to_redeemScript(),
                          CTransaction.deserialize(unsigned_tx), 1,
                          SIGHASH_ALL, value, SIGVERSION_WITNESS_V0),
            x('c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670'
              ))
Example #6
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))
Example #7
0
    def test_from_bare_checksig_scriptPubKey(self):
        def T(hex_scriptpubkey, expected_str_address):
            scriptPubKey = CScript(x(hex_scriptpubkey))
            # test that CBitcoinAddressError is raised, we do not support
            # bare checksig
            with self.assertRaises(CBitcoinAddressError):
                P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey)

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

        # uncompressed
        T(
            '410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ac',
            '13VmALKHkCdSN1JULkP6RqW3LcbpWvgryV')

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

        # odd-lengths are *not* accepted
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_scriptPubKey(
                CScript(
                    x('2200000000000000000000000000000000000000000000000000000000000000000000ac'
                      )))
    def load(cls):
        with open(cls.PATH, "r") as rf:
            wallet_json = json.load(rf)
            wallet_xpub = ExtPubKey(wallet_json["wallet_xpub"])
            master_fingerprint = x(wallet_json["master_fingerprint"])
            base_keypath = HDKeyPath(wallet_json["base_keypath"])
            current_block = Block.from_json(wallet_json["current_block"])
            raw_external_addresses = wallet_json["external_addresses"]
            raw_change_addresses = wallet_json["change_addresses"]

            external_addresses = [
                WalletAddress(
                    wallet_xpub, base_keypath, child_number, False,
                    address["was_recovered"], address["is_fresh"],
                    [Utxo.from_json(utxo) for utxo in address["utxos"]],
                    address.get("label"))
                for child_number, address in enumerate(raw_external_addresses)
            ]

            change_addresses = [
                WalletAddress(
                    wallet_xpub, base_keypath, child_number, True,
                    address["was_recovered"], address["is_fresh"],
                    [Utxo.from_json(utxo) for utxo in address["utxos"]])
                for child_number, address in enumerate(raw_change_addresses)
            ]

            return (wallet_xpub, master_fingerprint, base_keypath,
                    current_block, external_addresses, change_addresses)
Example #9
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',
            '13VmALKHkCdSN1JULkP6RqW3LcbpWvgryV')

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

        # odd-lengths are *not* accepted
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_scriptPubKey(
                x('2200000000000000000000000000000000000000000000000000000000000000000000ac'
                  ))
Example #10
0
 def T(hex_pubkey: str,
       is_nonempty: bool, is_fullyvalid: bool, is_compressed: bool
       ) -> None:
     key = CPubKey(x(hex_pubkey))
     self.assertEqual(key.is_nonempty(), is_nonempty)
     self.assertEqual(key.is_fullyvalid(), is_fullyvalid)
     self.assertEqual(key.is_compressed(), is_compressed)
Example #11
0
    def test_from_valid_pubkey(self) -> None:
        """Create P2PKHBitcoinAddress's from valid pubkeys"""

        def T(pubkey: bytes, expected_str_addr: str) -> None:
            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')
Example #12
0
    def test_from_redeemScript(self) -> None:
        def T(script: CScript, expected_str_address: str) -> None:
            addr = P2SHBitcoinAddress.from_redeemScript(script)
            self.assertEqual(str(addr), expected_str_address)

        T(CScript(), '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
        T(CScript(x('76a914751e76e8199196d454941c45d1b3a323f1433bd688ac')),
          '3LRW7jeCvQCRdPF8S3yUCfRAx4eqXFmdcr')
Example #13
0
 def test_standard_bip32_vectors(self):
     for vector in BIP32_TEST_VECTORS:
         _, seed = vector[0]
         key = CBitcoinExtKey.from_seed(x(seed))
         for xpub, xpriv, child_num in vector[1:]:
             self.assertEqual(xpub, str(key.neuter()))
             self.assertEqual(xpriv, str(key))
             key = key.derive(child_num)
Example #14
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)
Example #15
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)
Example #16
0
def load_test_vectors(name):
    with open(os.path.dirname(__file__) + '/data/' + name, 'r') as fd:
        for tx_decoded in json.load(fd):
            if isinstance(tx_decoded, str):
                continue  # skip comment
            tx_bytes = x(tx_decoded['hex'])
            assert len(tx_bytes) == tx_decoded['size']
            tx = CTransaction.deserialize(tx_bytes)
            yield (tx_decoded, tx, tx_bytes)
def sign_input(tx, input_index, utxo):
    """Sign an input of transaction.
    Single-signature signing with SIGHASH_ALL"""

    key = utxo['key']
    src_addr = CCoinAddress(utxo['address'])

    script_for_sighash = CScript(
        [OP_DUP, OP_HASH160,
         Hash160(key.pub), OP_EQUALVERIFY, OP_CHECKSIG])

    assert isinstance(src_addr, (P2PKHCoinAddress, P2SHCoinAddress,
                                 P2WPKHCoinAddress)),\
        'only p2pkh, p2wpkh and p2sh_p2wpkh addresses are supported'

    if isinstance(src_addr, P2PKHCoinAddress):
        sigversion = SIGVERSION_BASE
    else:
        sigversion = SIGVERSION_WITNESS_V0

    if 'amountcommitment' in utxo:
        amountcommitment = CConfidentialValue(x(utxo['amountcommitment']))
    else:
        amountcommitment = CConfidentialValue(coins_to_satoshi(utxo['amount']))

    sighash = script_for_sighash.sighash(tx,
                                         input_index,
                                         SIGHASH_ALL,
                                         amount=amountcommitment,
                                         sigversion=sigversion)

    sig = key.sign(sighash) + bytes([SIGHASH_ALL])

    if isinstance(src_addr, P2PKHCoinAddress):
        tx.vin[input_index].scriptSig = CScript(
            [CScript(sig), CScript(key.pub)])
        scriptpubkey = src_addr.to_scriptPubKey()
    elif isinstance(src_addr, P2WPKHCoinAddress):
        tx.vin[input_index].scriptSig = CScript()
        tx.wit.vtxinwit[input_index] = CTxInWitness(
            CScriptWitness([CScript(sig), CScript(key.pub)]))
        scriptpubkey = src_addr.to_scriptPubKey()
    else:
        # Assume that this is p2sh-wrapped p2wpkh address
        inner_scriptPubKey = CScript([0, Hash160(key.pub)])
        tx.vin[input_index].scriptSig = CScript([inner_scriptPubKey])
        tx.wit.vtxinwit[input_index] = CTxInWitness(
            CScriptWitness([CScript(sig), CScript(key.pub)]))
        scriptpubkey = inner_scriptPubKey.to_p2sh_scriptPubKey()

    VerifyScript(tx.vin[input_index].scriptSig,
                 scriptpubkey,
                 tx,
                 input_index,
                 amount=amountcommitment,
                 flags=(SCRIPT_VERIFY_P2SH, ))
    def check_sign(self, blinded_tx: CTransaction, signed_tx: CTransaction,
                   bundle: Dict[str, Any]) -> None:
        tx_to_sign = blinded_tx.to_mutable()
        for n, vin in enumerate(tx_to_sign.vin):
            utxo = bundle['vin_utxo'][n]
            amount = -1 if utxo['amount'] == -1 else coins_to_satoshi(
                utxo['amount'])

            scriptPubKey = CScript(x(utxo['scriptPubKey']))
            a = CCoinAddress(utxo['address'])
            if 'privkey' in utxo:
                privkey = CCoinKey(utxo['privkey'])
                assert isinstance(a, P2PKHCoinAddress),\
                    "only P2PKH is supported for single-sig"
                assert a == P2PKHElementsAddress.from_pubkey(privkey.pub)
                assert scriptPubKey == a.to_scriptPubKey()
                sighash = SignatureHash(scriptPubKey,
                                        tx_to_sign,
                                        n,
                                        SIGHASH_ALL,
                                        amount=amount,
                                        sigversion=SIGVERSION_BASE)
                sig = privkey.sign(sighash) + bytes([SIGHASH_ALL])
                tx_to_sign.vin[n].scriptSig = CScript(
                    [CScript(sig), CScript(privkey.pub)])
            else:
                pk_list = [CCoinKey(pk) for pk in utxo['privkey_list']]
                redeem_script_data = [utxo['num_p2sh_participants']]
                redeem_script_data.extend([pk.pub for pk in pk_list])
                redeem_script_data.extend([len(pk_list), OP_CHECKMULTISIG])
                redeem_script = CScript(redeem_script_data)
                assert isinstance(a, P2SHCoinAddress),\
                    "only P2SH is supported for multi-sig."
                assert scriptPubKey == redeem_script.to_p2sh_scriptPubKey()
                assert a == P2SHElementsAddress.from_scriptPubKey(
                    redeem_script.to_p2sh_scriptPubKey())
                sighash = SignatureHash(redeem_script,
                                        tx_to_sign,
                                        n,
                                        SIGHASH_ALL,
                                        amount=amount,
                                        sigversion=SIGVERSION_BASE)
                sigs = [
                    pk.sign(sighash) + bytes([SIGHASH_ALL]) for pk in pk_list
                ]
                tx_to_sign.vin[n].scriptSig = CScript([b''] + sigs +
                                                      [redeem_script])

            VerifyScript(tx_to_sign.vin[n].scriptSig,
                         scriptPubKey,
                         tx_to_sign,
                         n,
                         amount=amount)

        self.assertEqual(tx_to_sign.serialize(), signed_tx.serialize())
Example #19
0
        def T(serialized_script_str: str,
              expected_tokens: List[Union[bytes, int]],
              test_roundtrip: bool = True) -> None:
            serialized_script = x(serialized_script_str)
            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)
Example #20
0
    def test_from_invalid_pubkeys(self) -> None:
        """Create P2PKHBitcoinAddress's from invalid pubkeys"""

        # first test with accept_invalid=True
        def T(invalid_pubkey: bytes, expected_str_addr: str) -> None:
            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')))
Example #21
0
def try_reclaim_elt(say, elt_rpc, txid, elt_contract, key, blinding_key, die):

    ensure_rpc_connected(say, elt_rpc)

    # we won't return from this function, so we can just
    # set the chain with select_chain_params
    select_chain_params(elements_chain_name)

    from_addr = P2SHCoinAddress.from_redeemScript(elt_contract)

    say('Will try to reclaim my Elements bitcoin asset from {}'.format(
        from_addr))

    tx_json = elt_rpc.getrawtransaction(txid, 1)
    confirmations = int(tx_json['confirmations'])

    while confirmations < elements_contract_timeout:
        tx_json = elt_rpc.getrawtransaction(txid, 1)
        confirmations = int(tx_json['confirmations'])

    commit_tx = CElementsTransaction.deserialize(x(tx_json['hex']))

    vout_n, unblind_result = find_and_unblind_vout(say, commit_tx, from_addr,
                                                   blinding_key, die)

    dst_addr = CElementsAddress(elt_rpc.getnewaddress())

    say('Will reclaim my Elements asset to {}'.format(dst_addr))
    reclaim_tx = create_elt_spend_tx(
        dst_addr,
        txid,
        vout_n,
        elt_contract,
        die,
        spend_key=key,
        blinding_factor=unblind_result.blinding_factor,
        asset_blinding_factor=unblind_result.asset_blinding_factor,
        branch_condition=False)

    say('Sending my Elements-reclaim transaction')
    new_txid = elt_rpc.sendrawtransaction(b2x(reclaim_tx.serialize()))

    def custom_die(msg):
        say(msg)
        die('Failed to reclaim by Elemets asset')

    wait_confirm(say,
                 'Elements',
                 new_txid,
                 custom_die,
                 elt_rpc,
                 num_confirms=3)

    say('Reclaimed my Elements asset. Swap failed.')
Example #22
0
    def test_repr(self):
        def T(script, expected_repr):
            actual_repr = repr(script)
            self.assertEqual(actual_repr, expected_repr)

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

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

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

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

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

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

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

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

        T(CScript(x('614c0200')),
          "CBitcoinScript([OP_NOP, x('00')...<ERROR: PUSHDATA1: truncated data>])")
Example #23
0
    def test_standard_bip32_vectors(self):
        for vector in BIP32_TEST_VECTORS:
            _, seed = vector[0]
            base_key = CBitcoinExtKey.from_seed(x(seed))
            key = base_key
            path = []
            for xpub, xpriv, child_num in vector[1:]:
                self.assertEqual(xpub, str(key.neuter()))
                self.assertEqual(xpriv, str(key))
                key = key.derive(child_num)
                path.append(child_num)

            key_from_path = base_key.derive_path(str(BIP32Path(path)))
            self.assertEqual(key, key_from_path)
    def test(self):

        def T(confidential_addr, expected_bytes, unconfidential_addr,
              expected_blinding_pubkey, expected_class):
            a = CCoinAddress(confidential_addr)
            self.assertIsInstance(a, expected_class)
            self.assertEqual(a.to_bytes(), expected_bytes)
            self.assertEqual(unconfidential_addr, a.to_unconfidential())
            self.assertEqual(
                confidential_addr,
                str(a.__class__.from_unconfidential(
                    unconfidential_addr, a.blinding_pubkey)))
            self.assertEqual(expected_blinding_pubkey, a.blinding_pubkey)
            a2 = CCoinConfidentialAddress(str(a))
            self.assertEqual(a, a2)
            a2 = CCoinConfidentialAddress.from_unconfidential(unconfidential_addr,
                                                              a.blinding_pubkey)
            self.assertEqual(a, a2)

        T('CTEp1wviJ6U7SdAAs5sRJ1NzzRzAbmQGt1veiswjWrkzv98W7UJMQjBccafpS6v9w6evWTqeLsGc7TC1',
          x('029ffb47606c3d672a3429d91650960c63ff7d8f8ff9e00b4a8e3430c6549b4cc83422fe11c415bb9c8618f9d8498d9ad945056bdb'),
          P2PKHElementsAddress('2deBRSp69HSsJ5WAegsaksoWj8PfaQ2PqDd'),
          x('029ffb47606c3d672a3429d91650960c63ff7d8f8ff9e00b4a8e3430c6549b4cc8'),
          P2PKHElementsConfidentialAddress)
Example #25
0
    def test_p2wsh_signaturehash1(self):
        unsigned_tx = x(
            '0100000002fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e0000000000ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac00000000'
        )
        value2 = coins_to_satoshi(49)
        scriptcode1 = CScript(
            x('21026dccc749adc2a9d0d89497ac511f760f45c47dc5ed9cf352a58ac706453880aeadab210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac'
              ))
        # This is the same script with everything up to the last executed OP_CODESEPARATOR, including that
        # OP_CODESEPARATOR removed
        scriptcode2 = CScript(
            x('210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac'
              ))

        self.assertEqual(
            SignatureHash(scriptcode1, CTransaction.deserialize(unsigned_tx),
                          1, SIGHASH_SINGLE, value2, SIGVERSION_WITNESS_V0),
            x('82dde6e4f1e94d02c2b7ad03d2115d691f48d064e9d52f58194a6637e4194391'
              ))
        self.assertEqual(
            SignatureHash(scriptcode2, CTransaction.deserialize(unsigned_tx),
                          1, SIGHASH_SINGLE, value2, SIGVERSION_WITNESS_V0),
            x('fef7bd749cce710c5c052bd796df1af0d935e59cea63736268bcbe2d2134fc47'
              ))
Example #26
0
    def test_from_non_canonical_scriptPubKey(self) -> None:
        def T(hex_scriptpubkey: str, expected_str_address: str) -> None:
            scriptPubKey = CScript(x(hex_scriptpubkey))
            # now test that CBitcoinAddressError is raised, non-canonical
            # pushdata is not allowed
            with self.assertRaises(CBitcoinAddressError):
                P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey)

        T('76a94c14000000000000000000000000000000000000000088ac', '1111111111111111111114oLvT2')
        T('76a94d1400000000000000000000000000000000000000000088ac', '1111111111111111111114oLvT2')
        T('76a94e14000000000000000000000000000000000000000000000088ac', '1111111111111111111114oLvT2')

        # make sure invalid scripts raise CBitcoinAddressError
        with self.assertRaises(CBitcoinAddressError):
            P2PKHBitcoinAddress.from_scriptPubKey(CScript(x('76a94c14')))
Example #27
0
    def test_get_output_size(self):
        pub1 = CPubKey(
            x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71'
              ))
        pub2 = CPubKey(
            x('02546c76587482cd2468b76768da70c0166ecb2aa2eb1038624f4fedc138b042bc'
              ))
        for chainparam in get_params_list():
            with ChainParams(chainparam):
                smpl = get_unconfidential_address_samples(pub1, pub2)
                # 1 byte for 'no asset', 1 byte for 'no nonce',
                # 9 bytes for explicit value,
                # minus 8 bytes of len of bitcoin nValue
                elements_unconfidential_size_extra = 1 + 1 + 9 - 8

                # 33 bytes for asset, 33 bytes for nonce,
                # 33 bytes for confidential value,
                # minus 8 bytes of len of bitcoin nValue
                elements_confidential_size_extra = 33 + 33 + 33 - 8

                self.assertEqual(smpl.p2pkh.get_output_size(),
                                 34 + elements_unconfidential_size_extra)
                self.assertEqual(smpl.p2wpkh.get_output_size(),
                                 31 + elements_unconfidential_size_extra)
                self.assertEqual(smpl.p2sh.get_output_size(),
                                 32 + elements_unconfidential_size_extra)
                self.assertEqual(smpl.p2wsh.get_output_size(),
                                 43 + elements_unconfidential_size_extra)
                self.assertEqual(smpl.conf_p2pkh.get_output_size(),
                                 34 + elements_confidential_size_extra)
                self.assertEqual(smpl.conf_p2wpkh.get_output_size(),
                                 31 + elements_confidential_size_extra)
                self.assertEqual(smpl.conf_p2sh.get_output_size(),
                                 32 + elements_confidential_size_extra)
                self.assertEqual(smpl.conf_p2wsh.get_output_size(),
                                 43 + elements_confidential_size_extra)
Example #28
0
class CoreLitecoinParams(CoreChainParams):
    NAME = 'litecoin-mainnet'
    GENESIS_BLOCK = CBlock.deserialize(x(
        '0100000000000000000000000000000000000000000000000000000000000000'
        '00000000d9ced4ed1130f7b7faad9be25323ffafa33232a17c3edf6cfd97bee6'
        'bafbdd97b9aa8e4ef0ff0f1ecd513f7c01010000000100000000000000000000'
        '00000000000000000000000000000000000000000000ffffffff4804ffff001d'
        '0104404e592054696d65732030352f4f63742f32303131205374657665204a6f'
        '62732c204170706c65e280997320566973696f6e6172792c2044696573206174'
        '203536ffffffff0100f2052a010000004341040184710fa689ad5023690c80f3'
        'a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f47'
        '0216fe1b51850b4acf21b179c45070ac7b03a9ac00000000'))
    SUBSIDY_HALVING_INTERVAL = 840000
    PROOF_OF_WORK_LIMIT = 2 ** 256 - 1 >> 20
    MAX_MONEY = 84000000 * COIN
Example #29
0
 def request_sign_transaction(
         self, psbt: PartiallySignedTransaction) -> Transaction:
     message = json.dumps({
         "header": OutgoingMessageHeader.REQUEST_SIGN_TRANSACTION,
         "payload": {
             "psbt": psbt.serialize().hex()
         }
     })
     self.write_message(message)
     response = self.read_message(
         IncomingMessageHeader.SIGN_TRANSACTION_RESULT)
     payload = response["payload"]
     if not bool(payload["success"]):
         return None
     psbt = PartiallySignedTransaction.deserialize(x(payload["psbt"]))
     return psbt.extract_transaction()
Example #30
0
 def test_get_output_size(self) -> None:
     pub = CPubKey(x('0378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71'))
     a0 = P2PKHCoinAddress.from_pubkey(pub)
     self.assertEqual(P2PKHCoinAddress.get_output_size(), 34)
     self.assertEqual(a0.get_output_size(), 34)
     a1 = P2WPKHCoinAddress.from_pubkey(pub)
     self.assertEqual(P2WPKHCoinAddress.get_output_size(), 31)
     self.assertEqual(a1.get_output_size(), 31)
     a2 = P2SHCoinAddress.from_redeemScript(
         CScript(b'\xa9' + Hash160(pub) + b'\x87'))
     self.assertEqual(P2SHCoinAddress.get_output_size(), 32)
     self.assertEqual(a2.get_output_size(), 32)
     a3 = P2WSHCoinAddress.from_redeemScript(
         CScript(b'\xa9' + Hash160(pub) + b'\x87'))
     self.assertEqual(P2WSHCoinAddress.get_output_size(), 43)
     self.assertEqual(a3.get_output_size(), 43)