def main(): ''' Our main function. ''' SelectParams('mainnet') decoded_transaction = eval(open('transaction_to_sign.txt').read()) # pylint: disable=eval-used txin_txid = lx(decoded_transaction['vin'][0]['txid']) txin_vout = 0 tx_in = CMutableTxIn(COutPoint(txin_txid, txin_vout)) tx_out = [] for idx in range(len(decoded_transaction['vout'])): satoshis = int(COIN * decoded_transaction['vout'][idx]['value']) script_pub_key = CScript(bytes.fromhex(decoded_transaction['vout'][idx]['scriptPubKey']['hex'])) tx_out.append(CMutableTxOut(satoshis, script_pub_key)) tx_to_spend = CMutableTransaction([tx_in], tx_out) priv_1 = CBitcoinSecret.from_secret_bytes(bytes.fromhex(PRIV_HEX_1)) priv_2 = CBitcoinSecret.from_secret_bytes(bytes.fromhex(PRIV_HEX_2)) txin_redeem_script = CScript(bytes.fromhex(decoded_transaction['vin'][0]['scriptSig']['hex'])) # Input 0 is fixed. sighash = SignatureHash(txin_redeem_script, tx_to_spend, 0, SIGHASH_ALL) signatures = [] for priv in [priv_1, priv_2]: signatures.append(priv.sign(sighash) + bytes([SIGHASH_ALL])) tx_in.scriptSig = CScript([CScriptOp(0x00), signatures[0], signatures[1], txin_redeem_script]) # script_pub_key Defined in cycle. VerifyScript(tx_in.scriptSig, txin_redeem_script, tx_to_spend, 0, (SCRIPT_VERIFY_P2SH,)) print(b2x(tx_to_spend.serialize()))
def task_handler(database, bitcoind_address, local_address): """Task handler thread main function.""" logger.debug("Starting task handler.") logger.debug("bitcoind address: %s", bitcoind_address) Channel.bitcoind = bitcoin.rpc.Proxy(bitcoind_address) Channel.local_address = local_address try: root_key = database.Get(b'root_key') except KeyError: # TODO: grab a real private key from bitcoind root_key = CBitcoinSecret.from_secret_bytes( bytes(bitcoind_address, 'ascii')) database.Put(b'root_key', root_key) Channel.private_key = root_key while True: address, task = tasks.get() key = address.encode('utf-8') logger.debug("Task for %s: %r", address, task) try: channel = pickle.loads(database.Get(key)) except KeyError: channel = Channel(address) try: channel.handle(task) except: logger.exception("Error handling task %s for %s", task, address) try: channel.bob.error("An unexpected error occured, I'm dying") finally: raise database.Put(key, pickle.dumps(channel))
def make_private_keys(): """ Convert a list of passphrases into a list of private keys. For the purposes of prototyping, the passphrases are static values. System random should be used for the real deal, though. """ # Note that this function uses python-bitcoinlib CBitcoinSecret objects. private_keys = [] passphrases = [ "password", "passphrase", "hello world", "hello cruel world", "correct horse battery staple", "correct horse battery staple 1", "correct horse battery staple 2", "correct horse battery staple 3", "correct horse battery staple 4", ] passphrases = [bytes(each, "utf-8") for each in passphrases] for passphrase in passphrases: hashed = sha256(passphrase) # compressed=True is default private_key = CBitcoinSecret.from_secret_bytes(hashed, compressed=True) private_keys.append(private_key) return private_keys
def get_tz_priv(coin, path): session_id = bytes.fromhex(environ.get('TZ_SESSIONID', '')) if trezor and len(session_id) == 32: device = get_transport() client = TrezorClient(transport=device, ui=ClickUI(), session_id=session_id) n_path = parse_path( "m/10065'/0'") # Logical path for BIP0065 operation info = get_public_node(client, n_path, coin_name=coin) side, pubkey = (info.node.public_key[0], info.node.public_key[1:]) left = True if side == 2 else False print("seed", b2x(pubkey), side) priv = encrypt_keyvalue(client, n_path, path, pubkey, ask_on_decrypt=side, ask_on_encrypt=False) client.close() print("priv", b2x(priv), left) is_valid(priv) return CBitcoinSecret.from_secret_bytes(priv) else: print("trezorlib must be available") print("see: https://pypi.org/project/trezor/") print("TZ_SESSIONID enviroinment variable required") print("See: trezorctl get-session --help") sys.exit(2)
def Normal_Child__extended_private_key(self, index): """ Use an index between 0 and 2147483647. https://learnmeabitcoin.com/technical/hd-wallets """ parent_private_key = self.x_prv[:64] len_parent_public_key = len(self.x_pub) - len(self.chain_code) parent_public_key = self.x_pub[:len_parent_public_key] parent_chain_code = self.chain_code for i in range(index): # TODO: '4' to change index > 2**8 to byte is correctly ?? data = bytes.fromhex(parent_public_key) + i.to_bytes( 4, byteorder='big') key = bytes.fromhex(parent_chain_code) hmac_hash = hmac.new(key=key, msg=data, digestmod=hashlib.sha512).hexdigest() left_32bit = hmac_hash[:64] # 64 hex >> 32 bit child_chain_code = hmac_hash[64:] int_child_private_key = (int(parent_private_key, 16) + int( left_32bit, 16)) % int(Secp256k1_order, 16) child_private_key = hex(int_child_private_key)[2:] child_public_key = CBitcoinSecret.from_secret_bytes( x(child_private_key)).pub.hex() print(" #{}".format(i)) print("\tchild_private_key: {}".format(child_private_key)) print("\tchild_public_key : {}".format(child_public_key)) print("\tchild_chain_code : {}".format(child_chain_code))
def before_request(): """Setup g context""" g.config = current_app.config g.bit = g.config['bitcoind'] secret = hashlib.sha256(g.config['secret']).digest() g.seckey = CBitcoinSecret.from_secret_bytes(secret) g.addr = 'http://localhost:%d/' % int(g.config['port']) g.logger = current_app.logger
def make_self_transaction(): words = get_randomness('keys.txt') # seckey = CBitcoinSecret.from_secret_bytes(our_keys[1]) h = hashlib.sha256(words).digest() seckey = CBitcoinSecret.from_secret_bytes(h) input_hashes = [('08f7e2c1238cc9b918649e40d72815f32be6dc1ad538cb25331bd1f1c58a5f46',0), ('8642baa47de6ece50c2800221e5bc7eefd7adf4158f24af31fdcfa185cb54fce', 1)] address = P2PKHBitcoinAddress.from_pubkey(seckey.pub) # "1F26pNMrywyZJdr22jErtKcjF8R3Ttt55G" return make_transaction(0.00092, input_hashes, address, seckey)
def retrieve_wallettoken(bit_key): bitcoinlib_key = CBitcoinSecret.from_secret_bytes(x(bit_key.to_hex())) pub_key_hex = str(bitcoinlib_key.pub.hex()) message = "bitpost" + str(round( time.time() / 1000)) # we add a timestamp to make the proof valid for only ~ 1h sig = SignMessage(bitcoinlib_key, BitcoinMessage(message)) return bitpost_interface.get_wallettoken(pub_key_hex, sig)
def __init__(self, private_key, network=None): self.private_key = private_key self.public_key = CBitcoinSecret.from_secret_bytes( x(private_key)).pub.hex() if network is None: constants.set_mainnet() self.network = constants.net else: self.network = network
def __init__(self, base_url): super().__init__(base_url) SelectParams("regtest") for key in self.private_keys: seckey = CBitcoinSecret.from_secret_bytes( codecs.decode(key, "hex_codec")) self.call("importprivkey", str(seckey))
def __init__(self, key1: CPubKey, relative_timeout): """ a life signal is a coin that can be spent by key1 immediately or a tmp key after a relative_timeout :param key1: :param relative_timeout: """ self._key1 = key1 self._key2 = CBitcoinSecret.from_secret_bytes( Hash("tmpsecret".encode())) self._relative_timeout = relative_timeout self._life_signal_amount = 0.0001 * COIN
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
def make_multisig(self, n = None): if n is None: n = random.randrange(0, len(self.keypairs)) secret_bytes = Hash(self.seed + struct.pack('>L', n)) secret_key = CBitcoinSecret.from_secret_bytes(secret_bytes) # 1-of-1 CHECKMULTISIG scriptPubKey's scriptPubKey = CScript([1, secret_key.pub, 1, OP_CHECKMULTISIG]) self.keypairs[scriptPubKey] = secret_key return scriptPubKey
def make_paytopubkeyhash(self, n = None): if n is None: n = random.randrange(0, len(self.keypairs)) secret_bytes = Hash(self.seed + struct.pack('>L', n)) secret_key = CBitcoinSecret.from_secret_bytes(secret_bytes) # pay-to-pubkeyhash scriptPubKey = CScript([OP_DUP, OP_HASH160, Hash160(secret_key.pub), OP_EQUALVERIFY, OP_CHECKSIG]) self.keypairs[scriptPubKey] = secret_key return scriptPubKey
def get_private_key(self): """Attempt to parse the private key that was input.""" txt = str(self.privkey_edit.text()) privkey = None if is_hex(txt): txt = format_hex_string(txt, with_prefix=False) try: privkey = CBitcoinSecret.from_secret_bytes(x(txt)) except Exception: pass return privkey
def create_signature(self, privkey, reedem_script): """ Exports a raw signature suitable for use in a multisig transaction """ seckey = CBitcoinSecret.from_secret_bytes(x(bitcointools.encode_privkey(privkey, "hex"))) signatures = [] for i in range(len(self.tx.vin)): sighash = SignatureHash(CScript(x(reedem_script)), self.tx, i, SIGHASH_ALL) signatures.append({ "index": i, "signature": (seckey.sign(sighash) + struct.pack('<B', SIGHASH_ALL)).encode("hex") }) return signatures
def test_build_send_script(self): """ Run simple sanity checks on script generation """ # Set up constants for this test sender_private_key = CBitcoinSecret.from_secret_bytes(x('4f65da9b656de4036076911707d2b2dbf065689245b8674faa8790e36d7e5850')) sender_public_key = sender_private_key.pub recipient_private_key = CBitcoinSecret.from_secret_bytes(x('cfe8e33672f7045f020210f3c7afbca660e053e4c9415c542ff185e97b175cf0')) recipient_public_key = recipient_private_key.pub send_to_key = CBitcoinSecret.from_secret_bytes(x('15a249b4c09286b877d4708191f1ee8de09903bae034dd9dc8e3286451fa1c80')) send_to_address = P2PKHBitcoinAddress.from_pubkey(send_to_key.pub) secret = x('88d6e51f777b0b8dc0f429da9f372fbc') secret_hash = Hash(secret) quantity = 1000 # Build the send transaction txins = [] # TODO: Provide some random inputs txouts = [CTxOut(quantity, build_send_out_script(sender_public_key, recipient_public_key, secret_hash))] send_tx = CMutableTransaction(txins, txouts) send_tx_n = 0 # We're working with the first transaction input # Build the refund transaction nLockTime = 1422177943 refund_tx = build_unsigned_refund_tx(send_tx, send_tx_n, send_to_address, nLockTime, CFeeRate(0)) # Actually verify the signatures sighash = SignatureHash(send_tx.vout[0].scriptPubKey, refund_tx, 0, SIGHASH_ALL) sender_sig = get_refund_tx_sig(refund_tx, sender_private_key, sender_public_key, recipient_public_key, secret_hash) self.assertTrue(sender_public_key.verify(sighash, sender_sig[:-1])) recipient_sig = get_refund_tx_sig(refund_tx, recipient_private_key, sender_public_key, recipient_public_key, secret_hash) self.assertTrue(recipient_public_key.verify(sighash, recipient_sig[:-1])) # Test building a complete refund transaction refund_tx = build_signed_refund_tx(send_tx, send_tx_n, refund_tx, recipient_sig, recipient_public_key, sender_private_key, secret_hash) # This throws an exception in case of a problem VerifyScript(refund_tx.vin[0].scriptSig, send_tx.vout[send_tx_n].scriptPubKey, refund_tx, 0, (SCRIPT_VERIFY_P2SH,))
def sign(self, privkey): """ Sign each of the inputs with the private key. Inputs should all be sent to the same scriptPubkey so we should only need one key. """ seckey = CBitcoinSecret.from_secret_bytes(x(bitcointools.encode_privkey(privkey, "hex"))) for i in range(len(self.tx.vin)): txin_scriptPubKey = self.tx.vin[i].scriptSig sighash = SignatureHash(txin_scriptPubKey, self.tx, i, SIGHASH_ALL) sig = seckey.sign(sighash) + struct.pack('<B', SIGHASH_ALL) self.tx.vin[i].scriptSig = CScript([sig, seckey.pub]) VerifyScript(self.tx.vin[i].scriptSig, txin_scriptPubKey, self.tx, i, (SCRIPT_VERIFY_P2SH,))
def make_address_from_passphrase(passphrase, compressed=True, as_str=True): """ Create a Bitcoin address from a passphrase. The passphrase is hashed and then used as the secret bytes to construct the CBitcoinSecret. """ if not isinstance(passphrase, bytes): passphrase = bytes(passphrase, "utf-8") passphrasehash = hashlib.sha256(passphrase).digest() private_key = CBitcoinSecret.from_secret_bytes(passphrasehash, compressed=compressed) address = P2PKHBitcoinAddress.from_pubkey(private_key.pub) if as_str: return str(address) else: return address
def create_signature(self, privkey): """ Exports a raw signature suitable for use in a multisig transaction """ seckey = CBitcoinSecret.from_secret_bytes(unhexlify(privkey)) signatures = [] for i in range(len(self.tx.vin)): txin_scriptPubKey = self.tx.vin[i].scriptSig sighash = SignatureHash(txin_scriptPubKey, self.tx, i, SIGHASH_ALL) signatures.append({ "index": i, "signature": (seckey.sign(sighash) + struct.pack('<B', SIGHASH_ALL)).encode("hex") }) return signatures
def decode_minikey(minikey): """Decode minikey from str or bytes to a CBitcoinSecret""" if isinstance(minikey, str): minikey = minikey.encode('ascii') length = len(minikey) if length not in [22, 30]: raise InvalidMinikeyError('Minikey length %d is not 22 or 30' % length) h0 = sha256(minikey) h1 = h0.copy() h1.update(b'?') checksum = _bord(h1.digest()[0]) if checksum != 0: raise InvalidMinikeyError('Minikey checksum %s is not 0' % checksum) return CBitcoinSecret.from_secret_bytes(h0.digest(), False)
def sign_setup_tx(tx_hex, redeem_script, ecdsa): tx = CTransaction.deserialize(binascii.unhexlify(tx_hex)) sighash = SignatureHash(redeem_script["bin"], tx, 0, SIGHASH_ALL) print(b"Signing = " + sighash) print(ecdsa.get_public_key()) seckey = CBitcoinSecret.from_secret_bytes(ecdsa.get_private_key("bin"), compressed=True) sig = seckey.sign(sighash) + bytes([SIGHASH_ALL]) print(b"Pub key = " + ecdsa.get_public_key("bin")) print(b"Sig = " + sig) print() return sig
def __init__(self, private_key=None, encrypted_private_key=None, password=None): if private_key is None and encrypted_private_key is None: _, secret_hash = generate_secret_with_hash() self.private_key = CBitcoinSecret.from_secret_bytes(secret=secret_hash) elif private_key is not None: self.private_key = CBitcoinSecret(private_key) elif encrypted_private_key is not None and password is not None: self.private_key = CBitcoinSecret(self.decrypt_private_key(encrypted_private_key, password)) elif password is None: raise TypeError( "__init__() missing 'password' argument, since 'encrypted_private_key' argument was provided" ) self.public_key = self.private_key.pub self.address = str(P2PKHBitcoinAddress.from_pubkey(self.public_key))
def __init__(self, seed: hex): """ Extended Keys: Private keys and public keys that you can derive children from. learn about Extend Key: https://learnmeabitcoin.com/technical/extended-keys """ self.seed = bytes.fromhex(seed) self.key = b'Bitcoin seed' # extend_private_key (x_prv) length is 128 chr in hex :>> 128 * 4 = 512 :>> 512 / 8 == 64 byte. # the first 32 bytes (64 hex) is the private key. # the last 32 bytes (64 hex) is the chain code. self.x_prv = hmac.new(key=self.key, msg=self.seed, digestmod=hashlib.sha512).hexdigest() private_key, chain_code = self.x_prv[:64], self.x_prv[64:] public_key = CBitcoinSecret.from_secret_bytes(x(private_key)).pub.hex() self.x_pub = public_key + chain_code # The chain code is just an extra 32 bytes that we couple with the private # key to create what we call an extended key. self.chain_code = chain_code
def make_signed_tx(ins, outs, priv): print('####### in make_signed_tx #######') print('ins: {}'.format(ins)) print('outs: {}'.format(outs)) print('priv: {}'.format(priv)) txins = [] txouts = [] txin_scriptPubKeys = [] # txin_scriptPubKeys = [] for i, inp in enumerate(ins): print('inp[tx_id]: {}'.format(inp['tx_id'])) txin = CMutableTxIn(COutPoint(lx(inp['tx_id']), inp['index'])) seckey = CBitcoinSecret.from_secret_bytes( pygcoinlib.script_to_address(inp['script']).encode('utf-8')) txin_scriptPubKeys.append( CScript([ OP_DUP, OP_HASH160, Hash160(seckey.pub), OP_EQUALVERIFY, OP_CHECKSIG ])) # txin_scriptPubKeys.append(CScript([OP_DUP, OP_HASH160, Hash160(seckey.pub), OP_EQUALVERIFY, OP_CHECKSIG])) txins.append(txin) for o, out in enumerate(outs): # print('out[\'address\']: {}'.format(out['address'])) if 'script' in out: # txouts.append(CMutableTxOut(0, CScript([bytes(out['script'], encoding='UTF-8')]), 2)) print('song') else: txouts.append( CMutableTxOut( out['value'], CBitcoinAddress(out['address']).to_scriptPubKey(), out['color'])) # print('address: {}'.format(pygcoinlib.script_to_address(spk['script']))) tx = CMutableTransaction(txins, txouts) for i, inp in enumerate(ins): sighash = SignatureHash(txin_scriptPubKeys[i], tx, i, SIGHASH_ALL) sig = seckey.sign(sighash) + bytes([SIGHASH_ALL]) txins[i].scriptSig = CScript([sig, seckey.pub]) VerifyScript(txins[i].scriptSig, txin_scriptPubKeys[i], tx, i, (SCRIPT_VERIFY_P2SH, )) return b2x(tx.serialize())
def sign(s): if not os.path.exists(s.hsm_secret) and os.path.isfile(s.hsm_secret): sys.exit("not a file? %s" % s.hsm_secret) if os.path.getsize(s.hsm_secret) != 32: sys.exit("not private key file? %s" % s.hsm_secret) f = open(s.hsm_secret, "rb") hsm_secret = f.read(32) f.close() node_priv_key = HKDF_SHA256(hsm_secret).extract_key() priv_key = CBitcoinSecret.from_secret_bytes(node_priv_key) pub_key = priv_key.pub #print("pub: %s" % pub_key.hex()) #addr = pubkey_to_address("p2wpkh", pub_key.hex()) #print("addr: %s" % addr) msg = signed_msg(s.message, pub_key.hex(), priv_key) print(msg)
def test_send_script_spend(self): """ Run more in-depth execution checks on the script generated for the send transaction """ sender_private_key = CBitcoinSecret.from_secret_bytes(x('4f65da9b656de4036076911707d2b2dbf065689245b8674faa8790e36d7e5850')) sender_public_key = sender_private_key.pub recipient_private_key = CBitcoinSecret.from_secret_bytes(x('cfe8e33672f7045f020210f3c7afbca660e053e4c9415c542ff185e97b175cf0')) recipient_public_key = recipient_private_key.pub secret = x('88d6e51f777b0b8dc0f429da9f372fbc') secret_hash = Hash(secret) send_to_key = CBitcoinSecret.from_secret_bytes(x('15a249b4c09286b877d4708191f1ee8de09903bae034dd9dc8e3286451fa1c80')) send_to_address = P2PKHBitcoinAddress.from_pubkey(send_to_key.pub) random_tx_id = x('8390b4c8198198c6447da1a6fad498209436a785459936b95a1e3b63618c1d8a') value = 10 * COIN send_tx_script_pub_key = build_send_out_script(sender_public_key, recipient_public_key, secret_hash) send_txins = [CMutableTxIn(COutPoint(random_tx_id, 0))] send_txouts = [CMutableTxOut(value, send_tx_script_pub_key)] send_tx = CMutableTransaction(send_txins, send_txouts) # Test the standard spend transaction txins = [CMutableTxIn(COutPoint(Hash(send_tx.serialize()), 0))] txouts = [CMutableTxOut(value, send_to_address.to_scriptPubKey())] recv_tx = CMutableTransaction(txins, txouts) sighash = SignatureHash(send_tx_script_pub_key, recv_tx, 0, SIGHASH_ALL) recipient_sig = recipient_private_key.sign(sighash) + (b'\x01') # bytes([SIGHASH_ALL]) recv_tx.vin[0].scriptSig = CScript([secret, 0, recipient_sig, recipient_public_key]) VerifyScript(recv_tx.vin[0].scriptSig, send_tx.vout[0].scriptPubKey, recv_tx, 0, (SCRIPT_VERIFY_P2SH,)) # Test a refund transaction refund_tx = CMutableTransaction(txins, txouts) sighash = SignatureHash(send_tx_script_pub_key, refund_tx, 0, SIGHASH_ALL) sender_sig = sender_private_key.sign(sighash) + (b'\x01') # bytes([SIGHASH_ALL]) recipient_sig = recipient_private_key.sign(sighash) + (b'\x01') # bytes([SIGHASH_ALL]) refund_tx.vin[0].scriptSig = CScript([sender_sig, sender_public_key, 1, recipient_sig, recipient_public_key]) VerifyScript(refund_tx.vin[0].scriptSig, send_tx_script_pub_key, refund_tx, 0, (SCRIPT_VERIFY_P2SH,)) # Test invalid transactions are rejected invalid_tx = CMutableTransaction(txins, txouts) sighash = SignatureHash(send_tx_script_pub_key, invalid_tx, 0, SIGHASH_ALL) sender_sig = sender_private_key.sign(sighash) + (b'\x01') # bytes([SIGHASH_ALL]) recipient_sig = recipient_private_key.sign(sighash) + (b'\x01') # bytes([SIGHASH_ALL]) invalid_tx.vin[0].scriptSig = CScript([]) with self.assertRaises(MissingOpArgumentsError): VerifyScript(invalid_tx.vin[0].scriptSig, send_tx_script_pub_key, invalid_tx, 0, (SCRIPT_VERIFY_P2SH,)) invalid_tx.vin[0].scriptSig = CScript([recipient_sig, recipient_public_key, 0]) with self.assertRaises(VerifyOpFailedError): VerifyScript(invalid_tx.vin[0].scriptSig, send_tx_script_pub_key, invalid_tx, 0, (SCRIPT_VERIFY_P2SH,)) invalid_tx.vin[0].scriptSig = CScript([recipient_sig, recipient_public_key, 1]) with self.assertRaises(VerifyOpFailedError): VerifyScript(invalid_tx.vin[0].scriptSig, send_tx_script_pub_key, invalid_tx, 0, (SCRIPT_VERIFY_P2SH,)) invalid_tx.vin[0].scriptSig = CScript([recipient_sig, recipient_public_key, 1, recipient_sig, recipient_public_key]) with self.assertRaises(VerifyOpFailedError): VerifyScript(invalid_tx.vin[0].scriptSig, send_tx_script_pub_key, invalid_tx, 0, (SCRIPT_VERIFY_P2SH,)) invalid_tx.vin[0].scriptSig = CScript([sender_sig, sender_public_key, 1, sender_sig, sender_public_key]) with self.assertRaises(VerifyOpFailedError): VerifyScript(invalid_tx.vin[0].scriptSig, send_tx_script_pub_key, invalid_tx, 0, (SCRIPT_VERIFY_P2SH,))
def dummy_user(name: str): secret = CBitcoinSecret.from_secret_bytes(Hash(name.encode())) return secret, Party(name, secret.pub)
def __setstate__(self, state): self.__dict__.update(state) # convert text secrets back to CBitcoinSecrets for pubkey, seckey in self.keypairs.items(): self.keypairs[pubkey] = CBitcoinSecret.from_secret_bytes(seckey)
def generate_secret_key(): random_bytes = open("/dev/random", "rb").read(100) secret_bytes = sha256(random_bytes).digest() return CBitcoinSecret.from_secret_bytes(secret_bytes)
my_public_key]) VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH,)) response = broadcast_transaction(tx, network) print(response.status_code, response.reason) print(response.text) if __name__ == '__main__': SelectParams('testnet') ###################################################################### # TODO: set these parameters correctly # # my_private_key = CBitcoinSecret('cRaUQma9fHfs1bbf7ygZdrABA9riGMrBDWyxE1boryBXrkh8242P') my_private_key = CBitcoinSecret.from_secret_bytes(x('1b84362fdf6f618dd176fd0187fe59b4ea41838cfa35605775a5a03a8d2e1f32')) my_public_key = my_private_key.pub my_address = P2PKHBitcoinAddress.from_pubkey(my_public_key) amount_to_send = 0.01 # amount of BTC in the output you're splitting minus fee txid_to_spend = ( 'cab354b01e9895f80c49b9e16bdbd0ec71de34b4451638c81286baea88e50368') utxo_index = 0 n = 10 # number of outputs to split the input into network = 'bcy-test' # either 'btc-test3' or 'bcy-test' # # ######################################################################
CTxIn(unsigned_tx.vin[i].prevout, d.params.spend_redeemScript('exch', exch_seckey, unsigned_tx, i), nSequence=0) for i, d in enumerate(deposits) ] signed_tx = CTransaction(signed_ins, unsigned_tx.vout, unsigned_tx.nLockTime) print(b2x(signed_tx.serialize())) # test script logging.root.setLevel('DEBUG') bitcoin.SelectParams('testnet') user_a_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'alice')) user_b_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'bob')) exch_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'exch')) users = [user_a_seckey, user_b_seckey] params = [] for ukey in users: params.append( DepositParams( user_scriptPubKey=P2PKHBitcoinAddress.from_pubkey( ukey.pub).to_scriptPubKey(), exch_scriptPubkey=P2PKHBitcoinAddress.from_pubkey( exch_seckey.pub).to_scriptPubKey(), locktime=1000000, # block 1 million
# Only to be imported by bob.py bob_secret_key_BTC = CBitcoinSecret( 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') ###################################################################### # # TODO: Fill this in with address secret key for BCY testnet # # Create address in hex with # curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=$YOURTOKEN # # Send coins with # curl -d '{"address": "BCY_ADDRESS", "amount": 1000000}' https://api.blockcypher.com/v1/bcy/test/faucet?token=<YOURTOKEN> # Only to be imported by alice.py alice_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')) # Only to be imported by bob.py # Bob should have coins!! bob_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')) # Can be imported by alice.py or bob.py alice_public_key_BTC = alice_secret_key_BTC.pub alice_address_BTC = P2PKHBitcoinAddress.from_pubkey(alice_public_key_BTC) bob_public_key_BTC = bob_secret_key_BTC.pub bob_address_BTC = P2PKHBitcoinAddress.from_pubkey(bob_public_key_BTC) alice_public_key_BCY = alice_secret_key_BCY.pub alice_address_BCY = P2PKHBitcoinAddress.from_pubkey(alice_public_key_BCY)
from pycoin import encoding from base_script import MySignatureHash, MyCScript from pycoin.tx.Tx import Tx my_netcode = "testnet" #my_netcode = "mainnet" bitcoin.SelectParams(my_netcode) my_params = bitcoin.params my_privkey_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['SECRET_KEY']])) my_pubaddr_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['PUBKEY_ADDR']])) # Create the (in)famous correct brainwallet secret key. h = hashlib.sha256(b'correct horse battery staple').digest() seckey = CBitcoinSecret.from_secret_bytes(h) cec_key = CECKey() cec_key.set_secretbytes(h) print("Secret key hex: ", seckey.hex()); btc_addr = encoding.public_pair_to_bitcoin_address(cec_key.get_pubkey(), address_prefix=my_pubaddr_prefix) print("Bitcoin address: ", btc_addr) # Create a redeemScript, with public key and checksig op code (0xac) # Similar to a scriptPubKey the redeemScript must be satisfied for the funds to be spent. txin_redeemScript = CScript([seckey.pub, OP_CHECKSIG]) print("Public key of address #", seckey.pub.hex()) # 0x21 + secret.pub + OP_CHECKSIG (0x87) print("Tx-in Redeem Script: ", b2x(txin_redeemScript))
# Address: miijP8xPSbyrgsXhoLhbcWnzp1dueP4UKt # getcoin: 0.01232547 # txid: dcacfaaedb28d27c3de731cc4d9e7ab3f33af3c3a275ef9e45943965cf9c096a ###################################################################### # # TODO: Fill this in with address secret key for BCY testnet # # Create address in hex with # curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=0b149be29c0847ce90d79ba0a26455be # Send coins with # curl -d '{"address": "BCY_ADDRESS", "amount": 1000000}' https://api.blockcypher.com/v1/bcy/test/faucet?token=<YOURTOKEN> # Only to be imported by alice.py alice_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('c3408bef2ba53e0c554ec161934e046e376fc162b57d36cc8ec7fd7eb0b6aeea')) # "private": "c3408bef2ba53e0c554ec161934e046e376fc162b57d36cc8ec7fd7eb0b6aeea", # "public": "03e5d1da20403dec1d0ac42f2f472e9a224e1eb3b182b63567704fbfdc617adc28", # "address": "BzSQEcY6jmjXsdVAGKTJ9ML5avVe3tv1BD", # "wif": "BusaKwQqMXj9ZCGAKfHtbuM7FcZvzd1MKav75q6PjMW5Qnu1byuw" # Only to be imported by bob.py # Bob should have coins!! # curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=c35625ecbba9444ca8f1b8885d79d851 bob_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('1b84362fdf6f618dd176fd0187fe59b4ea41838cfa35605775a5a03a8d2e1f32')) #{ # "private": "1b84362fdf6f618dd176fd0187fe59b4ea41838cfa35605775a5a03a8d2e1f32", # "public": "03bde3958f876c6e9ddd9b54e2608d419cc39b926a4617098321bf3e5468d6cc0f", # "address": "C5ApTWoBL72mgrXCXDULHDQrpCq1ysBD6i", # "wif": "BpFX4iQMvs7ptE4yfUZuvb4zesYyUjY4CpfgRVkZ4cEyyKdvFoZ2"
###################################################################### ###################################################################### # NOTE: This section is for Question 4 # TODO: Fill this in with address secret key for BCY testnet # # Create address in hex with # curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=$YOURTOKEN # This request will return a private key, public key and address. Make sure to save these. # # Send coins with # curl -d '{"address": "BCY_ADDRESS", "amount": 1000000}' https://api.blockcypher.com/v1/bcy/test/faucet?token=<YOURTOKEN> # This request will return a transaction reference. Make sure to save this. # Only to be imported by alice.py alice_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('e634a78fa4421cb4df9647c15a7efac7417f4f55d1035a70d731e5414671fbc9')) # Only to be imported by bob.py # Bob should have coins!! bob_secret_key_BCY = CBitcoinSecret.from_secret_bytes( x('4c20fe6737be7c3521dcd05fd317283e19a6823957d5b806f96f06611d6b0833')) # Can be imported by alice.py or bob.py alice_public_key_BCY = alice_secret_key_BCY.pub alice_address_BCY = P2PKHBitcoinAddress.from_pubkey(alice_public_key_BCY) bob_public_key_BCY = bob_secret_key_BCY.pub bob_address_BCY = P2PKHBitcoinAddress.from_pubkey(bob_public_key_BCY) ###################################################################### # print('my_address: ', my_address)
# [txid] a8110bbdd40d65351f615897d98c33cbe33e4ebedb4ba2fc9e8c644423dadc93 # [ref] https://live.blockcypher.com/btc-testnet/tx/{txid}/ # [req] python -m pip install bitcoinlib electrum from bitcoin.core.key import use_libsecp256k1_for_signing from bitcoin.core import x, b2x from bitcoin.wallet import CBitcoinSecret from electrum.ecc import ECPrivkey from electrum.bitcoin import EncodeBase58Check use_libsecp256k1_for_signing(True) sechex = '535b755a4c265772c4f6c7e0316bfd21e24c9e47441989e14e8133c7cb2f41a3' hashhex = '9039c54c1c34aa12b69b4dda962f501bb6c9cdb6745014ef326f5d4d0472aa99' seckey = CBitcoinSecret.from_secret_bytes(x(sechex)) sig = seckey.sign(x(hashhex)) b_wif = str(seckey) b_pub = b2x(seckey.pub) b_sig = b2x(sig) seckey = ECPrivkey(x(sechex)) sig = seckey.sign_transaction(x(hashhex)) e_wif = EncodeBase58Check(b'\x80' + seckey.get_secret_bytes() + b'\x01') e_pub = seckey.get_public_key_hex(compressed=True) e_sig = b2x(sig) assert b_wif == e_wif assert b_pub == e_pub print("wif:", b_wif) print("pub:", b_pub)
def run(self): filename = self.logdirectory + 'msghandlelog.txt' self.logger = logging.getLogger(__name__) self.logger.setLevel(level=logging.INFO) handler = logging.FileHandler(filename) handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s') handler.setFormatter(formatter) self.logger.addHandler(handler) delay = 0.0001 # hash speed latency self.logger.info('Start mining process') cur_time = int(time.time()) prev_time = cur_time - (cur_time % BLOCKGEN_POINT) notstart = True while notstart: cur_time = int(time.time()) if cur_time > prev_time + BLOCKGEN_POINT: # timelog = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime()) + 'Start mining...' # print(timelog) self.logger.info('Start mining...') notstart = False else: time.sleep(1) # pdb.set_trace() glovar.threadLock.acquire() prevhash = glovar.PREV_BLOCKHASH blockheight = glovar.MINEDBLOCK_HEIGHT target = glovar.MINING_TARGET glovar.threadLock.release() while True: # generate privatekey and publickey ranseed = os.urandom(32) h = hashlib.sha256(ranseed).digest() seckey = CBitcoinSecret.from_secret_bytes(h) pubkey = seckey._cec_key.get_pubkey().hex() timepoint = time.time() nounce = 0 while True: # resource control time.sleep(delay) #print('nouce:', nounce) temp = str(prevhash) + pubkey + str(timepoint) + str(nounce) hashvalue = int( hashlib.sha256(temp.encode('utf-8')).hexdigest(), 16) if hashvalue < target: break else: if time.time() - timepoint > TIME_INTERVAL: timepoint = time.time() #print('timepoint change to:', timepoint) nounce = 0 else: nounce += 1 glovar.threadLock.acquire() if prevhash != glovar.PREV_BLOCKHASH: # the state of IDBLOCKCHAIN changed blockheight = glovar.MINEDBLOCK_HEIGHT target = glovar.MINING_TARGET prevhash = glovar.PREV_BLOCKHASH glovar.IDENTITY_POOL.clear() glovar.HASHID_POOL.clear() nounce = 0 glovar.threadLock.release() new_identity = [ seckey, pubkey, timepoint, nounce, target, blockheight ] pool_identity = [ hashvalue, pubkey, timepoint, nounce, prevhash, target ] #print('find hashid: ', hashvalue) glovar.threadLock.acquire() if prevhash == glovar.PREV_BLOCKHASH: # Having mined an identity before next idblock glovar.IDENTITY_LIST.append(new_identity) glovar.IDENTITY_POOL.append(pool_identity) glovar.HASHID_POOL.append(hashvalue) glovar.threadLock.release() # Broadcast new mined identity senddata = { 'No': 1, 'hashid': hashvalue, 'pubkey': pubkey, 'prevhash': prevhash, 'timepoint': timepoint, 'nounce': nounce, 'target': target, 'type': 'minedid' } glovar.threadLock.acquire() glovar.broadqueue.put(senddata) glovar.threadLock.release() else: # the state of IDBLOCKCHAIN changed blockheight = glovar.MINEDBLOCK_HEIGHT target = glovar.MINING_TARGET prevhash = glovar.PREV_BLOCKHASH glovar.IDENTITY_POOL.clear() glovar.HASHID_POOL.clear() glovar.threadLock.release()
sys.stderr.write('Sorry, Python 3.x required by this example.\n') sys.exit(1) import hashlib from bitcoin import SelectParams from bitcoin.core import b2x, lx, COIN, COutPoint, CMutableTxOut, CMutableTxIn, CMutableTransaction, Hash160 from bitcoin.core.script import CScript, OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG, SignatureHash, SIGHASH_ALL from bitcoin.core.scripteval import VerifyScript, SCRIPT_VERIFY_P2SH from bitcoin.wallet import CBitcoinAddress, CBitcoinSecret SelectParams('mainnet') # Create the (in)famous correct brainwallet secret key. h = hashlib.sha256(b'correct horse battery staple').digest() seckey = CBitcoinSecret.from_secret_bytes(h) # Create a redeemScript. Similar to a scriptPubKey the redeemScript must be # satisfied for the funds to be spent. txin_redeemScript = CScript([seckey.pub, OP_CHECKSIG]) print(b2x(txin_redeemScript)) # Create the magic P2SH scriptPubKey format from that redeemScript. You should # look at the CScript.to_p2sh_scriptPubKey() function in bitcoin.core.script to # understand what's happening, as well as read BIP16: # https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey() # Convert the P2SH scriptPubKey to a base58 Bitcoin address and print it. # You'll need to send some funds to it to create a txout to spend. txin_p2sh_address = CBitcoinAddress.from_scriptPubKey(txin_scriptPubKey)
def load_private_key(self, filename): real_path = self.get_path(filename) self.assert_file_exists(real_path) with open(real_path, 'r') as private_key_file: return CBitcoinSecret.from_secret_bytes(x(private_key_file.read()), True)