本文整理汇总了Python中bitcoin.core.CTransaction类的典型用法代码示例。如果您正苦于以下问题:Python CTransaction类的具体用法?Python CTransaction怎么用?Python CTransaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CTransaction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculate_tx_fees
def calculate_tx_fees(coins, currency, tx_hex):
#Process source TX.
rpc = coins[currency]["rpc"]["sock"]
tx = CTransaction.deserialize(binascii.unhexlify(tx_hex))
#Tally input coins.
input_total = decimal.Decimal(0)
for vin in tx.vin:
txid = b2lx(vin.prevout.hash)
vin_tx_hex = rpc.getrawtransaction(txid)
vin_tx = CTransaction.deserialize(binascii.unhexlify(vin_tx_hex))
input_value = vin_tx.vout[vin.prevout.n].nValue
input_total += decimal.Decimal(str_money_value(input_value))
#Tally output coins.
output_total = decimal.Decimal(0)
for vout in tx.vout:
output_value = decimal.Decimal(str_money_value(vout.nValue))
output_total += output_value
#TX fees are the difference between the source and
fees = input_total - output_total
#Return totals and fees.
return [input_total, output_total, fees]
示例2: getrawtransaction
def getrawtransaction(self, txid, verbose=False):
"""Return transaction with hash txid
Raises IndexError if transaction not found.
verbse - If true a dict is returned instead with additional information
on the transaction.
Note that if all txouts are spent and the transaction index is not
enabled the transaction may not be available.
"""
try:
r = self._call('getrawtransaction', b2lx(txid), 1 if verbose else 0)
except JSONRPCException as ex:
raise IndexError('%s.getrawtransaction(): %s (%d)' %
(self.__class__.__name__, ex.error['message'], ex.error['code']))
if verbose:
r['tx'] = CTransaction.deserialize(unhexlify(r['hex']))
del r['hex']
del r['txid']
del r['version']
del r['locktime']
del r['vin']
del r['vout']
r['blockhash'] = lx(r['blockhash']) if 'blockhash' in r else None
else:
r = CTransaction.deserialize(unhexlify(r))
return r
示例3: getrawtransaction
def getrawtransaction(self, txid, verbose=False):
"""Return transaction with hash txid
Raises IndexError if transaction not found.
verbose - If true a dict is returned instead with additional
information on the transaction.
Note that if all txouts are spent and the transaction index is not
enabled the transaction may not be available.
"""
try:
r = self._call("getrawtransaction", b2lx(txid), 1 if verbose else 0)
except JSONRPCError as ex:
raise IndexError(
"%s.getrawtransaction(): %s (%d)" % (self.__class__.__name__, ex.error["message"], ex.error["code"])
)
if verbose:
r["tx"] = CTransaction.deserialize(unhexlify(r["hex"]))
del r["hex"]
del r["txid"]
del r["version"]
del r["locktime"]
del r["vin"]
del r["vout"]
r["blockhash"] = lx(r["blockhash"]) if "blockhash" in r else None
else:
r = CTransaction.deserialize(unhexlify(r))
return r
示例4: withdrawfromvault
def withdrawfromvault(self, fromvaultaddress, toaddress, amount):
vault = self.getvault(fromvaultaddress)
received = self.chaindb.listreceivedbyvault(fromvaultaddress)
received = received.values()[0]
if received['value'] < amount + 2 * utils.calculate_fees(None):
self.logger.warning("Insufficient funds in vault, exiting, return")
return
# create transaction
tx = CTransaction()
# to the receiver
txout = CTxOut()
txout.nValue = amount
txout.scriptPubKey = utils.address_to_pay_to_pubkey_hash(toaddress)
tx.vout.append(txout)
# from the sender
nValueIn = 0
nValueOut = amount
txin = CTxIn()
txin.prevout = COutPoint()
txin.prevout.hash = received['txhash']
txin.prevout.n = received['n']
txin.scriptSig = received['scriptPubKey']
tx.vin.append(txin)
# calculate nValueIn
nValueIn = received['value']
# calculate the total excess amount
excessAmount = nValueIn - nValueOut
# calculate the fees
fees = 2 * utils.calculate_fees(tx)
# create change transaction, if there is any change left
if excessAmount > fees:
change_txout = CTxOut()
change_txout.nValue = excessAmount - fees
account = self.getaccount()
changeaddress = fromvaultaddress
self.logger.debug("Change address: %s" % changeaddress)
change_txout.scriptPubKey = \
utils.vault_address_to_pay_to_vault_script(changeaddress)
tx.vout.append(change_txout)
# calculate txhash
tx.calc_sha256()
txhash = str(tx.sha256)
key = CKey()
key.set_pubkey(vault['public_key'])
key.set_privkey(vault['private_key'])
signature = key.sign(txhash)
vaultscript = utils.create_vault_script(vault['address'], \
vault['master_address'], vault['timeout'], vault['maxfees'])
scriptSig = chr(OP_VAULT_WITHDRAW) + chr(len(signature)) + signature + \
chr(len(vaultscript)) + vaultscript
self.logger.debug("Adding signature: %s" % binascii.hexlify(scriptSig))
txin.scriptSig = scriptSig
return tx
示例5: overridevaulttx
def overridevaulttx(self, fromvaultaddress, toaddress):
vault = self.getvault(fromvaultaddress)
# select the input addresses
received = self.chaindb.listallreceivedbyvault(fromvaultaddress)
if not received:
self.logger.warning("Empty vault, exiting, return")
return None, None
received = received.values()[0]
if received['value'] < 2 * utils.calculate_fees(None):
self.logger.warning("Insufficient funds in vault, exiting, return")
return None, None
# calculate remaining amount
amount = received['value'] - 2 * utils.calculate_fees(None)
# create transaction
tx = CTransaction()
# to the receiver
txout = CTxOut()
txout.nValue = amount
txout.scriptPubKey = utils.address_to_pay_to_pubkey_hash(toaddress)
tx.vout.append(txout)
# from the sender
nValueIn = 0
nValueOut = amount
txin = CTxIn()
txin.prevout = COutPoint()
txin.prevout.hash = received['txhash']
txin.prevout.n = received['n']
txin.scriptSig = received['scriptPubKey']
tx.vin.append(txin)
# calculate nValueIn
nValueIn = received['value']
# calculate the total excess amount
excessAmount = nValueIn - nValueOut
# calculate the fees
fees = utils.calculate_fees(tx)
# calculate txhash
tx.calc_sha256()
txhash = str(tx.sha256)
key = CKey()
key.set_pubkey(vault['public_key'])
key.set_privkey(vault['private_key'])
signature = key.sign(txhash)
# get the script
vaultscript = utils.create_vault_script(vault['address'], \
vault['master_address'], vault['timeout'], vault['maxfees'])
scriptSig = chr(OP_VAULT_OVERRIDE) + chr(len(vault['master_public_key'])) + \
vault['master_public_key'] + chr(len(signature)) + signature + \
chr(len(vaultscript)) + vaultscript
self.logger.debug("Adding signature: %s" % binascii.hexlify(scriptSig))
txin.scriptSig = scriptSig
return amount, tx
示例6: as_tx
def as_tx(self):
sum_in = sum(prevtx.nValue for _,prevtx,_ in self.prevouts)
sig_size = sum(redeemer.spendbytes for _,_,redeemer in self.prevouts)
tx_size = (4 + # version field
2 + # # of txins
len(self.prevouts) * 41 + # txins, excluding sigs
sig_size + # txins, sigs only
1 + # # of txouts
34 + # txout
4 # nLockTime field
)
feerate = int(self.proxy._call('estimatefee', 1) * COIN)
# satoshi's per KB
if feerate <= 0:
feerate = 10000
fees = int(tx_size * feerate / 1000)
tx = CMutableTransaction(
[CTxIn(outpoint, nSequence=0)
for outpoint,_,_ in self.prevouts],
[CTxOut(sum_in - fees, self.payto.to_scriptPubKey())],
0)
for n,(_,_,redeemer) in enumerate(self.prevouts):
redeemer.mutate_spend(tx, n)
unsigned_tx = CTransaction.from_tx(tx)
for n,(_,_,redeemer) in enumerate(self.prevouts):
txin = CMutableTxIn.from_txin(tx.vin[n])
txin.scriptSig = redeemer.sign_spend(unsigned_tx, n)
tx.vin[n] = CTxIn.from_txin(txin)
print(b2x(tx.serialize()))
示例7: cmd_mkwitness
def cmd_mkwitness(args):
tx = None
if args.tx is not None:
serialized_tx = args.tx
tx = CTransaction.deserialize(serialized_tx)
else:
tx = args.proxy.getrawtransaction(args.txid)
txproof = TxProof(tx=tx)
for seal_fd in args.seal_fds:
seal = BitcoinSingleUseSeal.deserialize(seal_fd.read())
txinproof = None
txoutproof = None
for i, txin in enumerate(txproof.tx.vin):
if txin.prevout == seal.outpoint:
txinproof = TxInProof(i=i, txproof=txproof)
txoutproof = TxOutProof(i=0, txproof=txproof)
break
else:
args.parser.error("Seal '%s' not closed by this transaction" % seal_fd.name)
witness = BitcoinSealWitness(seal=seal, txinproof=txinproof, txoutproof=txoutproof)
witness_filename = seal_fd.name + '.witness'
logging.info("Creating witness file '%s'" % witness_filename)
with open(seal_fd.name + '.witness', 'xb') as witness_fd:
witness_fd.write(witness.serialize())
示例8: check_refund_works
def check_refund_works(self, tx_hex, owner_first_sig, owner_second_sig, recipient_sig, actor):
global error_log_path
try:
tx = CTransaction.deserialize(binascii.unhexlify(tx_hex))
redeem_script = bond_redeem_script(self.ecdsa_us, self.ecdsa_them, self.factory.ecdsa_arbiters[0], actor)
redeem_script_hash160 = hash160_script(redeem_script)
print(tx_hex)
print(redeem_script)
tx.vin[0].scriptSig = CScript([OP_0, owner_first_sig, owner_second_sig, recipient_sig, redeem_script["bin"]])
p2sh_script_pub_key = CScript([OP_HASH160, redeem_script_hash160["bin"], OP_EQUAL])
print(redeem_script_hash160)
VerifyScript(tx.vin[0].scriptSig, p2sh_script_pub_key, tx, 0, (SCRIPT_VERIFY_P2SH,))
signed_tx_hex = b2x(tx.serialize())
return {
"tx_hex": signed_tx_hex,
"txid": calculate_txid(signed_tx_hex)
}
except Exception as e:
error = parse_exception(e)
log_exception(error_log_path, error)
print(error)
print("Check refund failed.")
return None
示例9: provide_transaction
def provide_transaction(self, transaction_data):
self.send_lock.acquire()
if self.send_transaction_cache.contains(transaction_data):
self.send_lock.release()
return
if len(transaction_data) > self.MAX_RELAY_TRANSACTION_BYTES and (len(transaction_data) > self.MAX_RELAY_OVERSIZE_TRANSACTION_BYTES or self.send_transaction_cache.get_flag_count() >= MAX_EXTRA_OVERSIZE_TRANSACTIONS):
self.send_lock.release()
return
try:
relay_data = pack('>3I', self.MAGIC_BYTES, self.TRANSACTION_TYPE, len(transaction_data))
relay_data += transaction_data
self.relay_sock.sendall(relay_data)
self.send_transaction_cache.add(transaction_data, len(transaction_data) > self.MAX_RELAY_OVERSIZE_TRANSACTION_BYTES)
if deserialize_utils:
transaction = CTransaction.deserialize(transaction_data)
print("Sent transaction " + str(b2lx(transaction.GetHash())) + " of size " + str(len(transaction_data)))
else:
print("Sent transaction of size " + str(len(transaction_data)))
except (OSError, socket.error) as err:
print("Failed to send to relay node: ", err)
self.send_lock.release()
示例10: createrawtransaction
def createrawtransaction(self, *args):
"""Get rawtransactions when provided vin and vout
FIXME: Implement options and accept outpoints instead of user args
"""
r = self._call('createrawtransaction', *args)
r = str(r)
tx = CTransaction.deserialize(unhexlify(r))
return tx
示例11: msg_tx
class msg_tx(MsgSerializable):
command = b"tx"
def __init__(self, protover=PROTO_VERSION):
super(msg_tx, self).__init__(protover)
self.tx = CTransaction()
@classmethod
def msg_deser(cls, f, protover=PROTO_VERSION):
c = cls()
c.tx = CTransaction.stream_deserialize(f)
return c
def msg_ser(self, f):
self.tx.stream_serialize(f)
def __repr__(self):
return "msg_tx(tx=%s)" % (repr(self.tx))
示例12: signrawtransaction
def signrawtransaction(self, tx, *args):
"""Sign inputs for transaction
FIXME: implement options
"""
hextx = hexlify(tx.serialize())
r = self._call('signrawtransaction', hextx, *args)
r['tx'] = CTransaction.deserialize(unhexlify(r['hex']))
del r['hex']
return r
示例13: mutate_tx
def mutate_tx(tx_hex):
"""
Mutates a raw transaction using TX malleability in the scriptSig (specifically, the OP codes.) This function shouldn't be used beyond testing as it uses an ugly eval() hack.
https://en.bitcoin.it/wiki/Transaction_Malleability
"""
tx = CTransaction.deserialize(binascii.unhexlify(tx_hex))
script_sig = repr(tx.vin[0].scriptSig)[9:]
script_sig = eval("CScript([OP_1, OP_DROP, " + script_sig)
tx.vin[0].scriptSig = script_sig
return b2x(tx.serialize())
示例14: sign_refund_tx
def sign_refund_tx(self, tx_hex, key_no=1, actor="us"):
key_no -= 1
if key_no == 0:
ecdsa = self.ecdsa_us[0]
if key_no == 1:
ecdsa = self.ecdsa_us[1]
tx = CTransaction.deserialize(binascii.unhexlify(tx_hex))
sighash = SignatureHash(bond_redeem_script(self.ecdsa_us, self.ecdsa_them, self.factory.ecdsa_arbiters[0], actor)["bin"], tx, 0, SIGHASH_ALL)
seckey = CBitcoinSecret.from_secret_bytes(ecdsa.get_private_key("bin"), compressed=True)
sig = seckey.sign(sighash) + bytes([SIGHASH_ALL])
return sig
示例15: __init__
def __init__(self, nVersion=2, hashPrevBlock=b'\x00'*32,
hashMerkleRoot=b'\x00'*32, nTime=0, nBits=0, nNonce=0,
auxpow=None, vtx=()):
"""Create a new block"""
super(CAltcoinBlock, self).__init__(nVersion, hashPrevBlock,
hashMerkleRoot, nTime, nBits,
nNonce, auxpow)
vMerkleTree = tuple(bitcoin.core.CBlock.build_merkle_tree_from_txs(vtx))
object.__setattr__(self, 'vMerkleTree', vMerkleTree)
object.__setattr__(self, 'vtx', tuple(CTransaction.from_tx(tx)
for tx in vtx))