本文整理汇总了Python中pycoin.key.BIP32Node.BIP32Node.from_hwif方法的典型用法代码示例。如果您正苦于以下问题:Python BIP32Node.from_hwif方法的具体用法?Python BIP32Node.from_hwif怎么用?Python BIP32Node.from_hwif使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycoin.key.BIP32Node.BIP32Node
的用法示例。
在下文中一共展示了BIP32Node.from_hwif方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def __init__(self, private={}, public={}, private_seeds={}):
# It is possible to distinguish between private and public seeds
# based on the string content. Consider modifying this function
# to take merely one dict of seeds. Trees should still be stored
# separately.
self.trees = {}
self.private_trees = {}
self.public_trees = {}
def treegen(value, entropy=False):
if entropy:
# this method also takes a netcode parameter, but we don't care
# what network pycoin thinks this node is, because we only use it
# for key derivation.
return BIP32Node.from_master_secret(unhexlify(value))
else:
# this method will infer a network from the header bytes. We
# don't care right now for the same reason as above, but we will
# if Gem's API stops returning 'xpub' as the pubkey header bytes
# because if pycoin doesn't recognize a header it will error.
return BIP32Node.from_hwif(value)
for name, seed in iteritems(private):
tree = treegen(seed)
self.private_trees[name] = self.trees[name] = tree
for name, seed in iteritems(private_seeds):
tree = treegen(seed, True)
self.private_trees[name] = self.trees[name] = tree
for name, seed in iteritems(public):
tree = BIP32Node.from_hwif(seed)
self.public_trees[name] = self.trees[name] = tree
示例2: bip32node_for_slug
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def bip32node_for_slug(self, slug):
c = self._exec_sql("select id, as_text from BIP32Key where slug=?", slug)
r = c.fetchone()
if r is None:
return None
bip32_node = BIP32Node.from_hwif(r[1])
bip32_node.id = r[0]
return bip32_node
示例3: create_new_address
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def create_new_address(self):
n = n_addresses.incr()
bip32node = BIP32Node.from_hwif(xpub.get())
subkey = bip32node.subkey(0).subkey(n) # match electrum path
new_address = subkey.address()
addr_to_uid[new_address] = self.uid
uid_to_addr[self.uid] = new_address
all_addresses.add(new_address)
return True
示例4: treegen
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def treegen(value, entropy=False):
if entropy:
# this method also takes a netcode parameter, but we don't care
# what network pycoin thinks this node is, because we only use it
# for key derivation.
return BIP32Node.from_master_secret(unhexlify(value))
else:
# this method will infer a network from the header bytes. We
# don't care right now for the same reason as above, but we will
# if Gem's API stops returning 'xpub' as the pubkey header bytes
# because if pycoin doesn't recognize a header it will error.
return BIP32Node.from_hwif(value)
示例5: evaluate_key_input
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def evaluate_key_input(self, txt):
self.ext_key_widget.clear()
self.subkey_widget.clear()
txt = str(txt)
if not txt:
return self.invalid_key_label.setVisible(False)
# Variable substitution.
elif txt.startswith('$'):
return
try:
key = BIP32Node.from_hwif(txt)
except Exception as e:
self.invalid_key_label.setVisible(True)
else:
self.invalid_key_label.setVisible(False)
self.ext_key_widget.set_key(key)
self.derive_child()
finally:
self.ext_key_widget.mapper.setCurrentIndex(0)
示例6: createTransaction
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def createTransaction(self, address, amount, keychain, fee="standard",
confirms=0):
unspents_result = yield self.unspents()
spendables = []
p2sh = []
chain_paths = []
# Strip leading /
keychain_path = keychain['path'][1:]
for unspent in unspents_result["unspents"]:
if unspent["confirmations"] < confirms:
continue
p2sh.append(h2b(unspent["redeemScript"]))
spendable = Spendable(unspent["value"],
h2b(unspent["script"]),
h2b_rev(unspent["tx_hash"]),
unspent["tx_output_n"])
spendables.append(spendable)
chain_paths.append(keychain_path + unspent['chainPath'])
p2sh_lookup = build_p2sh_lookup(p2sh)
address_result = yield self.createAddress(1)
change = address_result["address"]
tx = tx_utils.create_tx(spendables, [(address, amount), change], fee)
# address_keys = [BIP32Node.from_hwif(keychain["xprv"]).subkey_for_path("0/0/0/0"),
# BIP32Node.from_hwif(keychain["xprv"]).subkey_for_path(address_result['path'])]
spendable_keys = [BIP32Node.from_hwif(keychain["xprv"]).subkey_for_path(path) for path in chain_paths]
# all_keys = address_keys + spendable_keys
hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])
pprint(tx)
tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
pprint(tx)
returnValue({'tx': tx.as_hex(),
'fee': tx.fee()})
示例7: main
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def main():
if len(sys.argv) != 2:
print("usage: %s bip32_key_file" % sys.argv[0])
sys.exit(-1)
with open(sys.argv[1], "r") as f:
hwif = f.readline().strip()
# turn the bip32 text into a BIP32Node object
BIP32_KEY = BIP32Node.from_hwif(hwif)
# create three sec_keys (these are public keys, streamed using the SEC format)
SEC_0 = BIP32_KEY.subkey_for_path("0/0/0").sec()
SEC_1 = BIP32_KEY.subkey_for_path("0/1/0").sec()
SEC_2 = BIP32_KEY.subkey_for_path("0/2/0").sec()
public_key_sec_list = [SEC_0, SEC_1, SEC_2]
# create the 2-of-3 multisig script
# any 2 signatures can release the funds
pay_to_multisig_script = ScriptMultisig(2, public_key_sec_list).script()
# create a "2-of-3" multisig address_for_multisig
the_address = address_for_pay_to_script(pay_to_multisig_script)
print("Here is your pay 2-of-3 address: %s" % the_address)
print("Here is the pay 2-of-3 script: %s" % b2h(pay_to_multisig_script))
print("The hex script should go into p2sh_lookup.hex")
base_dir = os.path.dirname(sys.argv[1])
print("The three WIFs are written into %s as wif0, wif1 and wif2" % base_dir)
for i in range(3):
wif = BIP32_KEY.subkey_for_path("0/%d/0" % i).wif()
with open(os.path.join(base_dir, "wif%d" % i), "w") as f:
f.write(wif)
示例8: derive_child
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def derive_child(self):
strkey = str(self.key_edit.text())
subkey_path = str(self.subkey_path.text())
subkey_path = subkey_path.replace("'", "H").replace("h", "H")
# Don't clear if the user is typing a path.
if subkey_path.endswith('/'):
return
self.subkey_widget.clear()
if not strkey or not subkey_path:
return
try:
ext_key = BIP32Node.from_hwif(strkey)
result = ext_key.subkey_for_path(subkey_path)
except Exception as e:
self.invalid_subkey_label.setText(str(e))
self.invalid_subkey_label.setVisible(True)
else:
self.invalid_subkey_label.setVisible(False)
self.subkey_widget.set_key(result)
finally:
self.subkey_widget.mapper.setCurrentIndex(0)
示例9: coerce_base58
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def coerce_base58(v):
key = BIP32Node.from_hwif(v)
return key
示例10: send
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def send(self, wallet_id, passcode, address, amount, message='', fee=10000):
"""
Send bitcoins to address
:param wallet_id: bitgo wallet id
:param address: bitcoin address
:param amount: btc amount in satoshis
:return: boolean
"""
wallet = self.get_wallet(wallet_id)
if not wallet['spendingAccount']:
raise NotSpendableWallet()
if not wallet['isActive']:
raise NotActiveWallet()
if amount < 10000:
raise Exception('amount to small')
if wallet['confirmedBalance'] < amount:
raise NotEnoughFunds('Not enough funds: balance %s amount %s' %
(wallet['confirmedBalance'], amount)
)
change_address = self.create_address(wallet_id, chain=1)
usableKeychain = False
spendables = []
chain_paths = []
p2sh = []
payables = [(address, amount)]
keychain_path = ""
for keychain in wallet['private']['keychains']:
keychain_path = keychain['path'][1:]
keychain = self.get_keychain(keychain['xpub'])
if 'encryptedXprv' not in keychain:
continue
usableKeychain = True
break
if not usableKeychain:
raise BitGoError("didn't found a spendable keychain")
data = json.loads(keychain['encryptedXprv'])
#add base64 paddings
for k in ['iv', 'salt', 'ct']:
data[k] = data[k] + "=="
cipher = sjcl.SJCL()
xprv = cipher.decrypt(data, passcode)
unspents = self.get_unspents(wallet_id)
total_value = 0
for d in unspents['unspents'][::-1]:
path = keychain_path + d['chainPath']
chain_paths.append(path)
p2sh.append(h2b(d["redeemScript"]))
spendables.append(Spendable(d["value"],
h2b(d["script"]),
h2b_rev(d["tx_hash"]),
d["tx_output_n"]))
total_value += d['value']
if total_value > amount:
break
if total_value > (amount + fee):
#add a change address
#TODO: create address
payables.append(change_address)
p2sh_lookup = build_p2sh_lookup(p2sh)
spendable_keys = []
priv_key = BIP32Node.from_hwif(xprv)
spendable_keys = [priv_key.subkey_for_path(path) for path in chain_paths]
hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])
tx = create_tx(spendables, payables)
tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
r = requests.post(self.url + '/tx/send', {
'tx': tx.as_hex(),
'message': message
}, headers={
'Authorization': 'Bearer %s' % self.access_token,
})
return r.json()
示例11: int
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
import sys
import subprocess
from pycoin.key import Key
from pycoin.key.electrum import ElectrumWallet
from pycoin.key.validate import netcode_and_type_for_data, netcode_and_type_for_text, is_address_valid, is_wif_valid, is_public_bip32_valid
from pycoin.key.BIP32Node import BIP32Node
mpk = sys.argv[1]
index = int(sys.argv[2])
#print(is_public_bip32_valid(MPK))
wallet = BIP32Node.from_hwif(mpk)
key = wallet.subkey(0)
subkey = key.subkey(index)
calculated_address = subkey.address()
print("%s" % calculated_address)
sys.exit(calculated_address)
示例12: decode_key
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def decode_key(dct):
if 'hwif' in dct:
return BIP32Node.from_hwif(dct['hwif'])
return dct
示例13: main
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def main():
parser = argparse.ArgumentParser(description="Process blinktrade withdrawals requests")
parser.add_argument('-c',
"--config",
action="store",
dest="config",
help='Configuration file', type=str)
arguments = parser.parse_args()
candidates = [ os.path.join(site_config_dir('blinktrade'), 'blinktrade_withdrawer.ini'),
os.path.expanduser('~/.blinktrade/blinktrade_withdrawer.ini')]
if arguments.config:
candidates.append(arguments.config)
config = ConfigParser.SafeConfigParser()
config.read( candidates )
password = getpass.getpass('password: ')
mandrill_api = mandrill.Mandrill(config.get("blinktrade", "mandrill_apikey"))
try:
mandrill_api.users.ping()
except mandrill.Error:
raise RuntimeError("Invalid Mandrill API key")
blinktrade_port = 443
should_connect_on_ssl = True
blinktrade_url = urlparse( config.get("blinktrade", "webscoket_url"))
if blinktrade_url.port is None and blinktrade_url.scheme == 'ws':
should_connect_on_ssl = False
blinktrade_port = 80
db_engine = config.get("database", "sqlalchemy_engine") + ':///' +\
os.path.expanduser(config.get("database", "sqlalchemy_connection_string"))
engine = create_engine(db_engine, echo=config.getboolean('database', 'sqlalchmey_verbose'))
Base.metadata.create_all(engine)
factory = BlinkTradeClientFactory(blinktrade_url.geturl())
factory.db_session = scoped_session(sessionmaker(bind=engine))
factory.verbose = config.getboolean("blinktrade", "verbose")
factory.blinktrade_broker_id = config.get("blinktrade", "broker_id")
factory.blinktrade_user = config.get("blinktrade", "api_key")
factory.blinktrade_password = decrypt(password, unhexlify(config.get("blinktrade", "api_password")))
factory.currencies = json.loads(config.get("blinktrade", "currencies"))
factory.methods = json.loads(config.get("blinktrade", "methods"))
factory.blocked_accounts = json.loads(config.get("blinktrade", "blocked_accounts"))
factory.mandrill_api = mandrill_api
if config.has_section('blockchain_info'):
from blockchain_info import BlockchainInfoWithdrawalProtocol
factory.blockchain_guid = decrypt(password, unhexlify(config.get("blockchain_info", "guid")))
factory.blockchain_main_password = decrypt(password, unhexlify(config.get("blockchain_info", "main_password")))
factory.blockchain_second_password = decrypt(password, unhexlify(config.get("blockchain_info", "second_password")))
factory.blockchain_api_key = config.get("blockchain_info", "api_key")
factory.from_address = config.get("blockchain_info", "from_address")
factory.note = config.get("blockchain_info", "note")
factory.protocol = BlockchainInfoWithdrawalProtocol
if config.has_section('blocktrail'):
import blocktrail
from mnemonic.mnemonic import Mnemonic
from pycoin.key.BIP32Node import BIP32Node
is_testnet = False
if config.get("blocktrail", "testnet") == '1':
is_testnet = True
client = blocktrail.APIClient(api_key=config.get("blocktrail", "api_key"),
api_secret=decrypt(password, unhexlify(config.get("blocktrail", "api_secret"))),
network='BTC',
testnet=is_testnet)
data = client.get_wallet(config.get("blocktrail", "wallet_identifier"))
primary_seed = Mnemonic.to_seed(data['primary_mnemonic'], decrypt(password, unhexlify(config.get("blocktrail", "wallet_passphrase"))))
primary_private_key = BIP32Node.from_master_secret(primary_seed, netcode='XTN' if client.testnet else 'BTC')
backup_public_key = BIP32Node.from_hwif(data['backup_public_key'][0])
checksum = client.create_checksum(primary_private_key)
if checksum != data['checksum']:
raise Exception("Checksum [%s] does not match expected checksum [%s], " \
"most likely due to incorrect password" % (checksum, data['checksum']))
blocktrail_public_keys = {}
for v,k in data['blocktrail_public_keys']:
if k in blocktrail_public_keys:
blocktrail_public_keys[k].append(v)
else:
blocktrail_public_keys[k] = [v]
key_index = data['key_index']
wallet = blocktrail.wallet.Wallet(client=client,
identifier= config.get("blocktrail", "wallet_identifier"),
primary_mnemonic=data['primary_mnemonic'],
primary_private_key=primary_private_key,
backup_public_key=backup_public_key,
blocktrail_public_keys=blocktrail_public_keys,
key_index=key_index,
testnet=client.testnet)
#.........这里部分代码省略.........
示例14: send
# 需要导入模块: from pycoin.key.BIP32Node import BIP32Node [as 别名]
# 或者: from pycoin.key.BIP32Node.BIP32Node import from_hwif [as 别名]
def send(self, wallet_id, passcode, address, amount, message='', fee=None, fan_unspend=10):
"""
Send bitcoins to address
:param wallet_id: bitgo wallet id
:param address: bitcoin address
:param amount: btc amount in satoshis
:param split: create new outputs if needed
:return: boolean
"""
MINIMAL_FEE = 20000
MINIMAL_SPLIT = 10000000
MIN_UNSPENTS_FAN = 5
wallet = self.get_wallet(wallet_id)
if not wallet['spendingAccount']:
raise NotSpendableWallet()
if not wallet['isActive']:
raise NotActiveWallet()
if amount < 10000:
raise Exception('amount to small')
if wallet['confirmedBalance'] < amount:
raise NotEnoughFunds('Not enough funds: balance %s amount %s' %
(wallet['confirmedBalance'], amount)
)
change_address = self.create_address(wallet_id, chain=1)
usableKeychain = False
spendables = []
chain_paths = []
p2sh = []
payables = [(address, amount)]
keychain_path = ""
for keychain in wallet['private']['keychains']:
keychain_path = keychain['path'][1:]
keychain = self.get_keychain(keychain['xpub'])
if 'encryptedXprv' not in keychain:
continue
usableKeychain = True
break
if not usableKeychain:
raise BitGoError("didn't found a spendable keychain")
data = json.loads(keychain['encryptedXprv'])
#add base64 paddings
for k in ['iv', 'salt', 'ct']:
data[k] = data[k] + "=="
cipher = sjcl.SJCL()
xprv = cipher.decrypt(data, passcode)
unspents = self.get_unspents(wallet_id)['unspents']
order_unspents = sorted(unspents, key=lambda k: k['confirmations'], reverse=True)
total_value = 0
for d in order_unspents:
path = keychain_path + d['chainPath']
chain_paths.append(path)
p2sh.append(h2b(d["redeemScript"]))
spendables.append(Spendable(d["value"],
h2b(d["script"]),
h2b_rev(d["tx_hash"]),
d["tx_output_n"]))
total_value += d['value']
if total_value > amount:
break
# make many outputs?
if len(order_unspents) < MIN_UNSPENTS_FAN and (total_value > (amount + MINIMAL_SPLIT)) and fan_unspend > 0:
fee = self.calculate_fee(len(spendables), fan_unspend)
value = (total_value - amount - fee) / fan_unspend
for i in range(fan_unspend):
payables.append((change_address, value))
elif total_value > (amount + MINIMAL_FEE):
# add a change address
if fee is None:
fee = self.calculate_fee(len(spendables), 2)
value = total_value - amount - fee
if value > 10000: #avoid dust
payables.append((change_address, value))
p2sh_lookup = build_p2sh_lookup(p2sh)
spendable_keys = []
priv_key = BIP32Node.from_hwif(xprv)
spendable_keys = [priv_key.subkey_for_path(path) for path in chain_paths]
hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])
tx = create_tx(spendables, payables)
tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
#.........这里部分代码省略.........