本文整理汇总了Python中pycoin.tx.Tx.tx_from_hex方法的典型用法代码示例。如果您正苦于以下问题:Python Tx.tx_from_hex方法的具体用法?Python Tx.tx_from_hex怎么用?Python Tx.tx_from_hex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycoin.tx.Tx
的用法示例。
在下文中一共展示了Tx.tx_from_hex方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_unprocessed
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def check_unprocessed(top_height):
for tx_hash in unprocessed_txs.members():
txid = hash_to_hex(tx_hash).decode()
tx = Tx.tx_from_hex(txs[tx_hash].decode())
tx_blockchain = get_tx(txid)
logging.info('Checking %s' % txid)
if tx_blockchain.block_height == -1:
continue
if top_height - tx_blockchain.block_height + 1 >= REQUIRED_CONFIRMATIONS: # off by one error - if tx in top block that is 1 conf
unprocessed_txs.remove(tx_hash)
for out in tx.txs_out:
address = out.bitcoin_address()
if address not in all_addresses:
continue
account = Account(addr_to_uid[address])
satoshis = out.coin_value
satoshis = int(satoshis / (1 + account.tip.get())) # scale for tip
account.total_coins.incr(satoshis)
node_minutes_d = calc_node_minutes(satoshis, exchange_rate=exchange_rate.get())
account.total_minutes.incr(node_minutes_d)
total_nodeminutes.incr(node_minutes_d)
nodes_recently_updated.append(account.uid)
account.add_msg('Detected payment via txid: %s' % (txid,))
account.add_msg('Increased total paid by %.8f to %.8f (considering tip of %d %%)' % (satoshis / COIN, account.total_coins.get() / COIN, account.tip.get() * 100))
account.add_msg('Increased node life by %d minutes; expiring around %s' % (node_minutes_d, account.get_expiry().isoformat()))
示例2: get_tx
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def get_tx(self, tx_hash):
url = "%s/rawtx/%s" % (self.base_url, b2h_rev(tx_hash))
result = json.loads(urlopen(url).read().decode("utf8"))
tx = Tx.tx_from_hex(result["rawtx"])
if tx.hash() == tx_hash:
return tx
return None
示例3: broadcastTransaction
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def broadcastTransaction (self, transaction):
print (transaction)
t = Tx.tx_from_hex (transaction)
deserializer = serializers.TxSerializer ()
tx = deserializer.deserialize (BytesIO (bytearray.fromhex(transaction)))
h = t.id ()
print ('BROADCAST:', str (tx.calculate_hash ())[2:-1], h)
#try:
# t = Tx.tx_from_hex (transaction)
# print ('OMG',t.id ())
#except Exception as e:
# print (e)
if not h in self.db['mempool']:
mp = self.db['mempool']
mp[h] = tx
self.db['mempool'] = mp
self.db.sync ()
self.mempooltimer = Timer (1.0, self.announceTransactions)
self.mempooltimer.start ()
return h
示例4: get_tx
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def get_tx(self, tx_hash):
URL = "%s/api/rawtx/%s" % (self.base_url, b2h_rev(tx_hash))
r = json.loads(urlopen(URL).read().decode("utf8"))
tx = Tx.tx_from_hex(r['rawtx'])
if tx.hash() == tx_hash:
return tx
return None
示例5: main
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def main():
tx = Tx.tx_from_hex(sys.argv[1])
print('Input Scripts:')
for inp in tx.txs_in:
print(' - ' + disassemble(inp.script))
print('Output Scripts:')
for out in tx.txs_out:
print(' - ' + disassemble(out.script))
示例6: sign_with_paths
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def sign_with_paths(self, tx, input_chain_paths, output_chain_paths, spend_id=None, verifications=None, callback=None):
"""
Have the Oracle sign the transaction
:param tx: the transaction to be signed
:type tx: Tx
:param input_chain_paths: the derivation path for each input, or None if the input does not need to be signed
:type input_chain_paths: list[str or None]
:param output_chain_paths: the derivation path for each change output, or None if the output is not change
:type output_chain_paths: list[str or None]
:param spend_id: an additional hex ID to disambiguate sends to the same outputs
:type spend_id: str
:param verifications: an optional dictionary with authorization code for each verification type. Keys include "otp" and "code" (for SMS).
:type verifications: dict of [str, str]
:return: a dictionary with the transaction in 'transaction' if successful
:rtype: dict
"""
req = self._create_oracle_request(input_chain_paths, output_chain_paths, spend_id, tx, verifications, callback=callback)
body = json.dumps(req)
url = self._url() + "/transactions"
if self.verbose > 0:
print(body)
self._request_logger.before('post', url, self._default_headers, body)
response = requests.post(url, body, headers=self._default_headers)
self._request_logger.after('post', url, response)
if response.status_code >= 500:
raise OracleInternalError(response.content)
result = response.json()
if response.status_code == 200 and result.get('result', None) == 'success':
tx = None
if 'transaction' in result:
tx = Tx.tx_from_hex(result['transaction']['bytes'])
return SignatureResult({
'transaction': tx,
'now': result['now'],
'spend_id': result['spendId'],
'deferral': result.get('deferral')
})
if result.get('result') == 'deferred':
deferral = result['deferral']
until = None
if deferral and deferral['reason'] == 'delay':
tzlocal = dateutil.tz.tzlocal()
until = dateutil.parser.parse(deferral['until']).astimezone(tzlocal)
#remain = int((until - datetime.datetime.now(tzlocal)).total_seconds())
raise OracleDeferralException(deferral.get('verifications'), until, result['spendId'])
elif result.get('result') == 'rejected':
raise OracleRejectionException()
elif result.get('result') == 'locked':
raise OracleLockoutException()
elif result.get('error') == 'Platform velocity hard-limit exceeded':
raise OraclePlatformVelocityHardLimitException('Platform velocity hard-limit exceeded')
elif response.status_code == 200 or response.status_code == 400:
raise OracleError(response.content)
else:
raise IOError("Unknown response %d" % (response.status_code,))
示例7: broadcastTransaction
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def broadcastTransaction (self, transaction):
#print (transaction)
t = Tx.tx_from_hex (transaction)
h = t.id ()
#print ('BROADCAST:', t.id ())
if not h in self.db['mempool']:
mp = self.db['mempool']
mp[h] = t
self.db['mempool'] = mp
self.db.sync ()
self.mempooltimer = Timer (1.0, self.announceTransactions)
self.mempooltimer.start ()
return h
示例8: got_message
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def got_message(self, message):
if self.last_sent + 30 * 60 < time.time():
self.send_message(bitcoin.messages.msg_ping(self.ver_send))
self.print_debug("Received: %s" % repr(message))
if message.command == "version":
self.send_message(bitcoin.messages.msg_verack(self.ver_send))
self.ver_send = min(self.ver_send, message.protover)
elif message.command == "verack":
self.ver_recv = self.ver_send
elif message.command == "inv":
self.request_objects(message.inv)
elif message.command == "tx":
self.new_tx_callback(Tx.tx_from_hex(message.tx.serialize().encode('hex')))
elif message.command == "block":
self.new_block_callback(Block.parse(cStringIO.StringIO(message.block.serialize()))) # todo - use msg_block or block stream_serialize
else:
self.print_debug("received unknown message %s: %s" % (message.command, repr(message)))
示例9: pycoin_sign_raw_transaction
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
def pycoin_sign_raw_transaction(tx_hex, private_key_wif):
for char in private_key_wif:
if char not in script.b58_digits:
raise exceptions.TransactionError('invalid private key')
if config.TESTNET:
allowable_wif_prefixes = [config.PRIVATEKEY_VERSION_TESTNET]
else:
allowable_wif_prefixes = [config.PRIVATEKEY_VERSION_MAINNET]
secret_exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
private_key_wif, allowable_wif_prefixes=allowable_wif_prefixes)
public_pair = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
hash160 = public_pair_to_hash160_sec(public_pair, compressed)
hash160_lookup = {hash160: (secret_exponent, public_pair, compressed)}
tx = Tx.tx_from_hex(tx_hex)
for idx, tx_in in enumerate(tx.txs_in):
tx.sign_tx_in(hash160_lookup, idx, tx_in.script, hash_type=SIGHASH_ALL)
return tx.as_hex()
示例10: main
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
#.........这里部分代码省略.........
return None
keys = [make_key(x) for x in possible_keys]
for key in keys:
if key:
key_iters.append((k.wif() for k in key.subkeys("")))
# if len(keys) == 1 and key.hierarchical_wallet() is None:
# # we have exactly 1 WIF. Let's look for an address
# potential_addresses = address_re.findall(line)
# we create the tx_db lazily
tx_db = None
for arg in args.argument:
# hex transaction id
if TX_ID_RE.match(arg):
if tx_db is None:
warning_tx_cache = message_about_tx_cache_env()
warning_get_tx = message_about_get_tx_env()
tx_db = get_tx_db()
tx = tx_db.get(h2b_rev(arg))
if not tx:
for m in [warning_tx_cache, warning_get_tx, warning_spendables]:
if m:
print("warning: %s" % m, file=sys.stderr)
parser.error("can't find Tx with id %s" % arg)
txs.append(tx)
continue
# hex transaction data
try:
tx = Tx.tx_from_hex(arg)
txs.append(tx)
continue
except Exception:
pass
try:
key = Key.from_text(arg)
# TODO: check network
if key.wif() is None:
payables.append((key.address(), 0))
continue
# TODO: support paths to subkeys
key_iters.append((k.wif() for k in key.subkeys("")))
continue
except Exception:
pass
if os.path.exists(arg):
try:
with open(arg, "rb") as f:
if f.name.endswith("hex"):
f = io.BytesIO(codecs.getreader("hex_codec")(f).read())
tx = Tx.parse(f)
txs.append(tx)
try:
tx.parse_unspents(f)
except Exception as ex:
pass
continue
except Exception:
pass
示例11:
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
#!/usr/bin/env python3
import argparse
import sys
from pycoin.tx import Tx
from models import txs, known_txs, unprocessed_txs, addr_to_uid, Account, known_blocks, all_addresses
from wallet import process_tx_initial
parser = argparse.ArgumentParser()
parser.add_argument('--tx-hex')
parser.add_argument('--txid')
args = parser.parse_args()
if args.txid in known_txs:
sys.exit()
tx = Tx.tx_from_hex(args.tx_hex)
process_tx_initial(tx)
示例12: get_latest_block
# 需要导入模块: from pycoin.tx import Tx [as 别名]
# 或者: from pycoin.tx.Tx import tx_from_hex [as 别名]
logging.basicConfig(level=logging.INFO)
if __name__ == '__main__':
while True:
latest_block = get_latest_block()
best_block_hash = latest_block.hash
top_height = latest_block.height
if best_block_hash == last_block_checked.get():
time.sleep(10) # only do this at most once per block
continue
logging.info('Latest block: %s' % best_block_hash)
for tx_hash in unprocessed_txs.members():
txid = hash_to_hex(tx_hash).decode()
tx = Tx.tx_from_hex(txs[tx_hash].decode())
tx_blockchain = get_tx(txid)
logging.info('Checking %s' % txid)
if tx_blockchain.block_height == -1:
continue
if top_height - tx_blockchain.block_height + 1 >= REQUIRED_CONFIRMATIONS: # off by one error - if tx in top block that is 1 conf
unprocessed_txs.remove(tx_hash)
for out in tx.txs_out:
address = out.bitcoin_address()
if address not in all_addresses:
continue
account = Account(addr_to_uid[address])
satoshis = out.coin_value
satoshis = int(satoshis / (1 + account.tip.get())) # scale for tip
account.total_coins.incr(satoshis)
node_minutes_d = calc_node_minutes(satoshis, exchange_rate=exchange_rate.get())