本文整理汇总了Python中test_framework.util.hex_str_to_bytes函数的典型用法代码示例。如果您正苦于以下问题:Python hex_str_to_bytes函数的具体用法?Python hex_str_to_bytes怎么用?Python hex_str_to_bytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hex_str_to_bytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: p2pkh_address_to_script
def p2pkh_address_to_script(self,v):
pubkey = hex_str_to_bytes(v['pubkey'])
p2wpkh = CScript([OP_0, hash160(pubkey)])
p2sh_p2wpkh = CScript([OP_HASH160, hash160(p2wpkh), OP_EQUAL])
p2pk = CScript([pubkey, OP_CHECKSIG])
p2pkh = CScript(hex_str_to_bytes(v['scriptPubKey']))
p2sh_p2pk = CScript([OP_HASH160, hash160(p2pk), OP_EQUAL])
p2sh_p2pkh = CScript([OP_HASH160, hash160(p2pkh), OP_EQUAL])
p2wsh_p2pk = CScript([OP_0, sha256(p2pk)])
p2wsh_p2pkh = CScript([OP_0, sha256(p2pkh)])
p2sh_p2wsh_p2pk = CScript([OP_HASH160, hash160(p2wsh_p2pk), OP_EQUAL])
p2sh_p2wsh_p2pkh = CScript([OP_HASH160, hash160(p2wsh_p2pkh), OP_EQUAL])
return [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh]
示例2: assert_tx_format_also_signed
def assert_tx_format_also_signed(self, utxo, segwit):
raw = self.nodes[0].createrawtransaction(
[{"txid": utxo["txid"], "vout": utxo["vout"]}],
[{self.unknown_addr: "49.9"}, {"fee": "0.1"}]
)
unsigned_decoded = self.nodes[0].decoderawtransaction(raw)
assert_equal(len(unsigned_decoded["vin"]), 1)
assert('txinwitness' not in unsigned_decoded["vin"][0])
# Cross-check python serialization
tx = CTransaction()
tx.deserialize(BytesIO(hex_str_to_bytes(raw)))
assert_equal(tx.vin[0].prevout.hash, int("0x"+utxo["txid"], 0))
assert_equal(len(tx.vin), len(unsigned_decoded["vin"]))
assert_equal(len(tx.vout), len(unsigned_decoded["vout"]))
# assert re-encoding
serialized = bytes_to_hex_str(tx.serialize())
assert_equal(serialized, raw)
# Now sign and repeat tests
signed_raw = self.nodes[0].signrawtransactionwithwallet(raw)["hex"]
signed_decoded = self.nodes[0].decoderawtransaction(signed_raw)
assert_equal(len(signed_decoded["vin"]), 1)
assert(("txinwitness" in signed_decoded["vin"][0]) == segwit)
# Cross-check python serialization
tx = CTransaction()
tx.deserialize(BytesIO(hex_str_to_bytes(signed_raw)))
assert_equal(tx.vin[0].prevout.hash, int("0x"+utxo["txid"], 0))
assert_equal(bytes_to_hex_str(tx.vin[0].scriptSig), signed_decoded["vin"][0]["scriptSig"]["hex"])
# test witness
if segwit:
wit_decoded = signed_decoded["vin"][0]["txinwitness"]
for i in range(len(wit_decoded)):
assert_equal(bytes_to_hex_str(tx.wit.vtxinwit[0].scriptWitness.stack[i]), wit_decoded[i])
# assert re-encoding
serialized = bytes_to_hex_str(tx.serialize())
assert_equal(serialized, signed_raw)
txid = self.nodes[0].sendrawtransaction(serialized)
nodetx = self.nodes[0].getrawtransaction(txid, 1)
assert_equal(nodetx["txid"], tx.rehash())
# cross-check wtxid report from node
wtxid = bytes_to_hex_str(ser_uint256(tx.calc_sha256(True))[::-1])
assert_equal(nodetx["wtxid"], wtxid)
assert_equal(nodetx["hash"], wtxid)
# witness hash stuff
assert_equal(nodetx["withash"], tx.calc_witness_hash())
return (txid, wtxid)
示例3: buildDummySegwitNameUpdate
def buildDummySegwitNameUpdate (self, name, value, addr):
"""
Builds a transaction that updates the given name to the given value and
address. We assume that the name is at a native segwit script. The witness
of the transaction will be set to two dummy stack elements so that the
program itself is "well-formed" even if it won't execute successfully.
"""
data = self.node.name_show (name)
u = self.findUnspent (Decimal ('0.01'))
ins = [data, u]
outs = {addr: Decimal ('0.01')}
txHex = self.node.createrawtransaction (ins, outs)
nameOp = {"op": "name_update", "name": name, "value": value}
txHex = self.node.namerawtransaction (txHex, 0, nameOp)['hex']
txHex = self.node.signrawtransactionwithwallet (txHex)['hex']
tx = CTransaction ()
tx.deserialize (io.BytesIO (hex_str_to_bytes (txHex)))
tx.wit = CTxWitness ()
tx.wit.vtxinwit.append (CTxInWitness ())
tx.wit.vtxinwit[0].scriptWitness = CScriptWitness ()
tx.wit.vtxinwit[0].scriptWitness.stack = [b"dummy"] * 2
txHex = tx.serialize ().hex ()
return txHex
示例4: sign_transaction
def sign_transaction(node, unsignedtx):
rawtx = ToHex(unsignedtx)
signresult = node.signrawtransactionwithwallet(rawtx)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(signresult['hex']))
tx.deserialize(f)
return tx
示例5: create_transaction
def create_transaction(node, txid, to_address, amount):
inputs = [{"txid": txid, "vout": 0}]
outputs = {to_address: amount}
rawtx = node.createrawtransaction(inputs, outputs)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(rawtx))
tx.deserialize(f)
return tx
示例6: setScriptSigOps
def setScriptSigOps (self, txHex, ind, scriptSigOps):
"""
Update the given hex transaction by setting the scriptSig for the
input with the given index.
"""
tx = CTransaction ()
tx.deserialize (io.BytesIO (hex_str_to_bytes (txHex)))
tx.vin[ind].scriptSig = CScript (scriptSigOps)
return tx.serialize ().hex ()
示例7: addAuxpow
def addAuxpow (self, block, blkHash, ok):
"""
Fills in the auxpow for the given block message. It is either
chosen to be valid (ok = True) or invalid (ok = False).
"""
target = b"%064x" % uint256_from_compact (block.nBits)
auxpowHex = computeAuxpow (blkHash, target, ok)
block.auxpow = CAuxPow ()
block.auxpow.deserialize (BytesIO (hex_str_to_bytes (auxpowHex)))
return block
示例8: make_utxo
def make_utxo(node, amount, confirmed=True, scriptPubKey=CScript([1])):
"""Create a txout with a given amount and scriptPubKey
Mines coins as needed.
confirmed - txouts created will be confirmed in the blockchain;
unconfirmed otherwise.
"""
fee = 1*COIN
while node.getbalance()['bitcoin'] < satoshi_round((amount + fee)/COIN):
node.generate(100)
new_addr = node.getnewaddress()
unblinded_addr = node.validateaddress(new_addr)["unconfidential"]
txidstr = node.sendtoaddress(new_addr, satoshi_round((amount+fee)/COIN))
tx1 = node.getrawtransaction(txidstr, 1)
txid = int(txidstr, 16)
i = None
for i, txout in enumerate(tx1['vout']):
if txout['scriptPubKey']['type'] == "fee":
continue # skip fee outputs
if txout['scriptPubKey']['addresses'] == [unblinded_addr]:
break
assert i is not None
tx2 = CTransaction()
tx2.vin = [CTxIn(COutPoint(txid, i))]
tx1raw = CTransaction()
tx1raw.deserialize(BytesIO(hex_str_to_bytes(node.getrawtransaction(txidstr))))
feeout = CTxOut(CTxOutValue(tx1raw.vout[i].nValue.getAmount() - amount))
tx2.vout = [CTxOut(amount, scriptPubKey), feeout]
tx2.rehash()
signed_tx = node.signrawtransactionwithwallet(txToHex(tx2))
txid = node.sendrawtransaction(signed_tx['hex'], True)
# If requested, ensure txouts are confirmed.
if confirmed:
mempool_size = len(node.getrawmempool())
while mempool_size > 0:
node.generate(1)
new_size = len(node.getrawmempool())
# Error out if we have something stuck in the mempool, as this
# would likely be a bug.
assert(new_size < mempool_size)
mempool_size = new_size
return COutPoint(int(txid, 16), 0)
示例9: create_and_mine_tx_from_txids
def create_and_mine_tx_from_txids(self, txids, success = True):
tx = CTransaction()
for i in txids:
txtmp = CTransaction()
txraw = self.nodes[0].getrawtransaction(i)
f = BytesIO(hex_str_to_bytes(txraw))
txtmp.deserialize(f)
for j in range(len(txtmp.vout)):
tx.vin.append(CTxIn(COutPoint(int('0x'+i,0), j)))
tx.vout.append(CTxOut(0, CScript()))
tx.rehash()
signresults = self.nodes[0].signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize_without_witness()))['hex']
self.nodes[0].sendrawtransaction(signresults, True)
self.nodes[0].generate(1)
sync_blocks(self.nodes)
示例10: submit_block_with_tx
def submit_block_with_tx(node, tx):
ctx = CTransaction()
ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx)))
tip = node.getbestblockhash()
height = node.getblockcount() + 1
block_time = node.getblockheader(tip)["mediantime"] + 1
block = create_block(int(tip, 16), create_coinbase(height), block_time)
block.vtx.append(ctx)
block.rehash()
block.hashMerkleRoot = block.calc_merkle_root()
add_witness_commitment(block)
block.solve()
node.submitblock(block.serialize(True).hex())
return block
示例11: cltv_validate
def cltv_validate(node, tx, height):
'''Modify the signature in vin 0 of the tx to pass CLTV
Prepends <height> CLTV DROP in the scriptSig, and sets
the locktime to height'''
tx.vin[0].nSequence = 0
tx.nLockTime = height
# Need to re-sign, since nSequence and nLockTime changed
signed_result = node.signrawtransactionwithwallet(ToHex(tx))
new_tx = CTransaction()
new_tx.deserialize(BytesIO(hex_str_to_bytes(signed_result['hex'])))
new_tx.vin[0].scriptSig = CScript([CScriptNum(height), OP_CHECKLOCKTIMEVERIFY, OP_DROP] +
list(CScript(new_tx.vin[0].scriptSig)))
return new_tx
示例12: get_key
def get_key(node):
"""Generate a fresh key on node
Returns a named tuple of privkey, pubkey and all address and scripts."""
addr = node.getnewaddress()
pubkey = node.getaddressinfo(addr)['pubkey']
pkh = hash160(hex_str_to_bytes(pubkey))
return Key(privkey=node.dumpprivkey(addr),
pubkey=pubkey,
p2pkh_script=CScript([OP_DUP, OP_HASH160, pkh, OP_EQUALVERIFY, OP_CHECKSIG]).hex(),
p2pkh_addr=key_to_p2pkh(pubkey),
p2wpkh_script=CScript([OP_0, pkh]).hex(),
p2wpkh_addr=key_to_p2wpkh(pubkey),
p2sh_p2wpkh_script=CScript([OP_HASH160, hash160(CScript([OP_0, pkh])), OP_EQUAL]).hex(),
p2sh_p2wpkh_redeem_script=CScript([OP_0, pkh]).hex(),
p2sh_p2wpkh_addr=key_to_p2sh_p2wpkh(pubkey))
示例13: get_key
def get_key(self):
"""Generate a fresh key on node0
Returns a named tuple of privkey, pubkey and all address and scripts."""
addr = self.nodes[0].getnewaddress()
pubkey = self.nodes[0].getaddressinfo(addr)['pubkey']
pkh = hash160(hex_str_to_bytes(pubkey))
return Key(self.nodes[0].dumpprivkey(addr),
pubkey,
CScript([OP_DUP, OP_HASH160, pkh, OP_EQUALVERIFY, OP_CHECKSIG]).hex(), # p2pkh
key_to_p2pkh(pubkey), # p2pkh addr
CScript([OP_0, pkh]).hex(), # p2wpkh
key_to_p2wpkh(pubkey), # p2wpkh addr
CScript([OP_HASH160, hash160(CScript([OP_0, pkh])), OP_EQUAL]).hex(), # p2sh-p2wpkh
CScript([OP_0, pkh]).hex(), # p2sh-p2wpkh redeem script
key_to_p2sh_p2wpkh(pubkey)) # p2sh-p2wpkh addr
示例14: run_test
def run_test (self):
node = self.nodes[0]
p2pStore = node.add_p2p_connection (P2PDataStore ())
p2pGetter = node.add_p2p_connection (P2PBlockGetter ())
self.log.info ("Adding a block with non-zero hash in the auxpow...")
blk, blkHash = self.createBlock ()
blk.auxpow.hashBlock = 12345678
blkHex = blk.serialize ().hex ()
assert_equal (node.submitblock (blkHex), None)
assert_equal (node.getbestblockhash (), blkHash)
self.log.info ("Retrieving block through RPC...")
gotHex = node.getblock (blkHash, 0)
assert gotHex != blkHex
gotBlk = CBlock ()
gotBlk.deserialize (BytesIO (hex_str_to_bytes (gotHex)))
assert_equal (gotBlk.auxpow.hashBlock, 0)
self.log.info ("Retrieving block through P2P...")
gotBlk = p2pGetter.getBlock (blkHash)
assert_equal (gotBlk.auxpow.hashBlock, 0)
self.log.info ("Sending zero-hash auxpow through RPC...")
blk, blkHash = self.createBlock ()
blk.auxpow.hashBlock = 0
assert_equal (node.submitblock (blk.serialize ().hex ()), None)
assert_equal (node.getbestblockhash (), blkHash)
self.log.info ("Sending zero-hash auxpow through P2P...")
blk, blkHash = self.createBlock ()
blk.auxpow.hashBlock = 0
p2pStore.send_blocks_and_test ([blk], node, success=True)
assert_equal (node.getbestblockhash (), blkHash)
self.log.info ("Sending non-zero nIndex auxpow through RPC...")
blk, blkHash = self.createBlock ()
blk.auxpow.nIndex = 42
assert_equal (node.submitblock (blk.serialize ().hex ()), None)
assert_equal (node.getbestblockhash (), blkHash)
self.log.info ("Sending non-zero nIndex auxpow through P2P...")
blk, blkHash = self.createBlock ()
blk.auxpow.nIndex = 42
p2pStore.send_blocks_and_test ([blk], node, success=True)
assert_equal (node.getbestblockhash (), blkHash)
示例15: get_multisig
def get_multisig(self):
"""Generate a fresh multisig on node0
Returns a named tuple of privkeys, pubkeys and all address and scripts."""
addrs = []
pubkeys = []
for _ in range(3):
addr = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())
addrs.append(addr['address'])
pubkeys.append(addr['pubkey'])
script_code = CScript([OP_2] + [hex_str_to_bytes(pubkey) for pubkey in pubkeys] + [OP_3, OP_CHECKMULTISIG])
witness_script = CScript([OP_0, sha256(script_code)])
return Multisig([self.nodes[0].dumpprivkey(addr) for addr in addrs],
pubkeys,
CScript([OP_HASH160, hash160(script_code), OP_EQUAL]).hex(), # p2sh
script_to_p2sh(script_code), # p2sh addr
script_code.hex(), # redeem script
witness_script.hex(), # p2wsh
script_to_p2wsh(script_code), # p2wsh addr
CScript([OP_HASH160, witness_script, OP_EQUAL]).hex(), # p2sh-p2wsh
script_to_p2sh_p2wsh(script_code)) # p2sh-p2wsh addr