def human_readable_output(txoutput): """ Returns a dict of human-readable entries for this output. """ assert isinstance(txoutput, CTxOut) outdict = {} outdict["value_sats"] = txoutput.nValue outdict["scriptPubKey"] = bintohex(txoutput.scriptPubKey) try: addr = CCoinAddress.from_scriptPubKey(txoutput.scriptPubKey) outdict["address"] = str(addr) except CCoinAddressError: pass # non standard script return outdict
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' ))
def test_valid_bip341_scriptpubkeys_addresses(): with ChainParams("bitcoin"): with open(os.path.join(testdir, "bip341_wallet_test_vectors.json"), "r") as f: json_data = json.loads(f.read()) for x in json_data["scriptPubKey"]: sPK = hextobin(x["expected"]["scriptPubKey"]) addr = x["expected"]["bip350Address"] res, message = validate_address(addr) assert res, message print("address {} was valid bech32m".format(addr)) # test this specific conversion because this is how # our human readable outputs work: assert str(CCoinAddress.from_scriptPubKey( btc.CScript(sPK))) == addr print("and it converts correctly from scriptPubKey: {}".format( btc.CScript(sPK)))
def payment_ack(serialized_payment_message: bytes, ) -> Tuple[bytes, Dict[str, str], CCoinAddress]: """Generates a PaymentACK object, captures client refund address and returns a tuple (message, refund_address)""" pao = o.PaymentACK() pao.payment.ParseFromString(serialized_payment_message) pao.memo = 'String shown to user after payment confirmation' refund_address = CCoinAddress.from_scriptPubKey( CScript(pao.payment.refund_to[0].script)) sds_pa = pao.SerializeToString() headers = {'Content-Type': 'application/bitcoin-payment', 'Accept': 'application/bitcoin-paymentack'} return sds_pa, headers, refund_address
# Iterate through transaction ouptputs, and unblind what we can. print("") for n, vout in enumerate(tx.vout): # Note that nValue of vout in Elements is not a simple int, # but CConfidentialValue, which can either be explicit, and can be # converted to satoshis with to_amount(), or it can be blinded, in # which case you need to unblind the output to know its value. if vout.nValue.is_explicit(): # The output is not blinded, we can access the values right away assert vout.nAsset.is_explicit(), "unblinding just the asset is not supported" if vout.is_fee(): print("vout {}: fee".format(n)) else: print("vout {}: explicit".format(n)) print(" destination address:", CCoinAddress.from_scriptPubKey(tx.vout[n].scriptPubKey)) print(" amount:\t\t", satoshi_to_coins(vout.nValue.to_amount())) print(" asset:\t\t", vout.nAsset.to_asset()) else: # Try to unblind the output with the given blinding key result = vout.unblind_confidential_pair( bkey, tx.wit.vtxoutwit[n].rangeproof) if result.error: # Nope, our blinding key is not good for this output print("vout {}: cannot unblind: {}".format(n, result.error)) print(" destination address:", CCoinAddress.from_scriptPubKey(tx.vout[n].scriptPubKey)) if not tx.wit.is_null(): rpinfo = tx.wit.vtxoutwit[n].get_rangeproof_info() if rpinfo:
def check_serialize_deserialize(self, tx, tx_bytes, tx_decoded): self.assertEqual(tx_bytes, tx.serialize()) self.assertEqual(tx_bytes, CTransaction.deserialize(tx.serialize()).serialize()) self.assertEqual(tx_bytes, tx.to_mutable().to_immutable().serialize()) self.assertEqual(tx_decoded['version'], tx.nVersion) self.assertEqual(tx_decoded['locktime'], tx.nLockTime) # we ignore withash field - we do not have ComputeWitnessHash() function # as it is only relevant for blocks, not transactions self.assertEqual(tx_decoded['hash'], b2lx(tx.GetHash())) self.assertEqual(tx_decoded['txid'], b2lx(tx.GetTxid())) for n, vout in enumerate(tx_decoded['vout']): if 'amountcommitment' in vout: self.assertEqual(x(vout['amountcommitment']), tx.vout[n].nValue.commitment) if 'assetcommitment' in vout: self.assertEqual(x(vout['assetcommitment']), tx.vout[n].nAsset.commitment) if 'asset' in vout: self.assertEqual(vout['asset'], tx.vout[n].nAsset.to_asset().to_hex()) if 'scriptPubKey' in vout: spk = vout['scriptPubKey'] self.assertEqual(x(spk['hex']), tx.vout[n].scriptPubKey) if 'pegout_type' in spk: self.assertEqual(spk['type'], 'nulldata') self.assertTrue(tx.vout[n].scriptPubKey.is_pegout()) genesis_hash, pegout_scriptpubkey = tx.vout[ n].scriptPubKey.get_pegout_data() if spk['pegout_type'] != 'nonstandard': assert spk['pegout_type'] in ('pubkeyhash', 'scripthash') addr = CCoinAddress.from_scriptPubKey( pegout_scriptpubkey) self.assertEqual(len(spk['pegout_addresses']), 1) self.assertEqual(spk['pegout_addresses'][0], str(addr)) self.assertEqual(spk['pegout_hex'], b2x(pegout_scriptpubkey)) self.assertEqual(spk['pegout_chain'], b2lx(genesis_hash)) if spk['type'] in ('pubkeyhash', 'scripthash'): self.assertEqual(len(spk['addresses']), 1) addr = CCoinAddress.from_scriptPubKey( tx.vout[n].scriptPubKey) self.assertEqual(spk['addresses'][0], str(addr)) elif spk['type'] == 'nulldata': self.assertEqual(tx.vout[n].scriptPubKey, x(spk['hex'])) else: self.assertEqual(spk['type'], 'fee') self.assertEqual(len(tx.vout[n].scriptPubKey), 0) if secp256k1_has_zkp: if tx.wit.is_null(): rpinfo = None else: rpinfo = tx.wit.vtxoutwit[n].get_rangeproof_info() if 'value-minimum' in vout: self.assertIsNotNone(rpinfo) self.assertEqual(vout['ct-exponent'], rpinfo.exp) self.assertEqual(vout['ct-bits'], rpinfo.mantissa) self.assertEqual( coins_to_satoshi(vout['value-minimum'], check_range=False), rpinfo.value_min) self.assertEqual( coins_to_satoshi(vout['value-maximum'], check_range=False), rpinfo.value_max) else: self.assertTrue(rpinfo is None or rpinfo.exp == -1) if rpinfo is None: value = tx.vout[n].nValue.to_amount() else: value = rpinfo.value_min self.assertEqual(coins_to_satoshi(vout['value']), value) else: warn_zkp_unavailable() if 'value' in vout and tx.vout[n].nValue.is_explicit(): self.assertEqual(coins_to_satoshi(vout['value']), tx.vout[n].nValue.to_amount()) for n, vin in enumerate(tx_decoded['vin']): if 'scripSig' in vin: self.assertEqual( x(vin['scriptSig']['hex'], tx.vin[n].scriptSig)) if 'txid' in vin: self.assertEqual(vin['txid'], b2lx(tx.vin[n].prevout.hash)) if 'vout' in vin: self.assertEqual(vin['vout'], tx.vin[n].prevout.n) if 'is_pegin' in vin: self.assertEqual(vin['is_pegin'], tx.vin[n].is_pegin) if vin['is_pegin'] is False: if 'scriptWitness' in vin: self.assertTrue( tx.wit.vtxinwit[n].scriptWitness.is_null()) if 'pegin_witness' in vin: self.assertTrue( tx.wit.vtxinwit[n].pegin_witness.is_null()) else: for stack_index, stack_item in enumerate( vin['scriptWitness']): self.assertTrue( stack_item, b2x(tx.wit.vtxinwit[n].scriptWitness. stack[stack_index])) for stack_index, stack_item in enumerate( vin['pegin_witness']): self.assertTrue( stack_item, b2x(tx.wit.vtxinwit[n].pegin_witness. stack[stack_index])) if 'sequence' in vin: self.assertEqual(vin['sequence'], tx.vin[n].nSequence) if 'coinbase' in vin: self.assertTrue(tx.is_coinbase()) if 'issuance' in vin: iss = vin['issuance'] self.assertEqual( iss['assetBlindingNonce'], tx.vin[n].assetIssuance.assetBlindingNonce.to_hex()) if 'asset' in iss: if iss['isreissuance']: self.assertTrue(not tx.vin[n].assetIssuance. assetBlindingNonce.is_null()) self.assertEqual( iss['assetEntropy'], tx.vin[n].assetIssuance.assetEntropy.to_hex()) asset = calculate_asset( tx.vin[n].assetIssuance.assetEntropy) else: entropy = generate_asset_entropy( tx.vin[n].prevout, tx.vin[n].assetIssuance.assetEntropy) self.assertEqual(iss['assetEntropy'], entropy.to_hex()) asset = calculate_asset(entropy) reiss_token = calculate_reissuance_token( entropy, tx.vin[n].assetIssuance.nAmount.is_commitment()) self.assertEqual(iss['token'], reiss_token.to_hex()) self.assertEqual(iss['asset'], asset.to_hex()) if 'assetamount' in iss: self.assertEqual( coins_to_satoshi(iss['assetamount']), tx.vin[n].assetIssuance.nAmount.to_amount()) elif 'assetamountcommitment' in iss: self.assertEqual( iss['assetamountcommitment'], b2x(tx.vin[n].assetIssuance.nAmount.commitment)) if 'tokenamount' in iss: self.assertEqual( coins_to_satoshi(iss['tokenamount']), tx.vin[n].assetIssuance.nInflationKeys.to_amount()) elif 'tokenamountcommitment' in iss: self.assertEqual( iss['tokenamountcommitment'], b2x(tx.vin[n].assetIssuance.nInflationKeys.commitment))
vault_in_privkey = CBitcoinSecret.from_secret_bytes( hashlib.sha256(b'Vault Tx Brain Secret').digest()) vault_in_pubkey = vault_in_privkey.pub fee_wallet_privkey = CBitcoinSecret.from_secret_bytes( hashlib.sha256(b'Fee Wallet Brain Secret').digest()) fee_wallet_pubkey = fee_wallet_privkey.pub # # Create P2WSH address for depositor. depositor_witnessScript = CScript([depositor_pubkey, OP_CHECKSIG]) depositor_scripthash = hashlib.sha256(depositor_witnessScript).digest() depositor_redeemScript = CScript([OP_0, depositor_scripthash]) depositor_address = CCoinAddress.from_scriptPubKey( depositor_redeemScript) # # Create P2WSH address for fee_wallet. fee_wallet_witnessScript = CScript([fee_wallet_pubkey, OP_CHECKSIG]) fee_wallet_scripthash = hashlib.sha256(fee_wallet_witnessScript).digest() fee_wallet_redeemScript = CScript([OP_0, fee_wallet_scripthash]) fee_wallet_address = CCoinAddress.from_scriptPubKey( fee_wallet_redeemScript) # # Create P2WSH vault address (used for vault_transaction and p2rw_transaction) vault_in_witnessScript = CScript([vault_in_pubkey, OP_CHECKSIG]) vault_in_scripthash = hashlib.sha256(vault_in_witnessScript).digest() vault_in_redeemScript = CScript([OP_0, vault_in_scripthash]) vault_in_address = CCoinAddress.from_scriptPubKey(vault_in_redeemScript) # # Create P2WSH output address for vault tx.