def carlisle_method(data, compress=False): """ Use the Carlisle method to generate a bitcoin address the hash of data. Args: data: bytes, data to hash compress: bool, whether to compress the public key Returns: dictionary with address generation information """ # Compute the sha256 hash of the data sha256_hash = hashlib.sha256(data) private_key = sha256_hash.hexdigest() # Generate public key public_key = bitcoin.privkey_to_pubkey(private_key) if compress: public_key = bitcoin.compress(public_key) # Generate bitcoin address address = bitcoin.pubkey_to_address(public_key) return { 'private_key': private_key, 'public_key': public_key, 'compressed': compress, 'address': address, 'url ': 'https://blockchain.info/address/{}'.format(address), }
def __init__(self, private_key: bytes): self.private_key = private_key self.public_key = None bitcoin.change_curve( 115792089210356248762697446949407573530086143415290314195533631308867097853951, 115792089210356248762697446949407573529996955224135760342422259061068512044369, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291, 48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109 ) length = len(self.private_key) if length != 32: raise ValueError("Invalid private key") if length == 32: try: pubkey_encoded_not_compressed = bitcoin.privkey_to_pubkey( private_key) pubkey_points = bitcoin.decode_pubkey( pubkey_encoded_not_compressed, 'bin') pubx = pubkey_points[0] puby = pubkey_points[1] self.public_key = cryptography.ECDSA.secp256r1().Curve.point( pubx, puby) except Exception: raise ValueError("Could not determine public key")
def sign_tx(raw_tx, index, privkey, version_byte, hashcode, redem=""): if (py_version == 3 and isinstance( re, bytes)) or not re.match('^[0-9a-fA-F]*$', raw_tx): raw_tx = safe_hexlify(raw_tx) return binascii.unhexlify(sign_tx(raw_tx, index, privkey, hashcode)) if version_byte in version_dict["pubkeyhash"].values(): pubkey = privkey_to_pubkey(privkey) signing_tx = sign_form(raw_tx, index, mk_pkscript(version_byte, hash160(pubkey)), hashcode) elif version_byte in version_dict["scripthash"].values(): assert redem != "", "Empty string found in parameter redem ." signing_tx = sign_form(raw_tx, index, redem, hashcode) else: raise ValueError("Unknown version_byte: '%s' ." % version_byte) rawsig = ecdsa_raw_sign(bytes.fromhex(txhash(signing_tx, hashcode)), privkey) sig = der_encode_sig(*rawsig) + dec2byte(hashcode, 1, mode="big-endian") json_tx = raw2json(raw_tx) if version_byte in version_dict["pubkeyhash"].values(): json_tx["vin"][index]["scriptSig"]["hex"] = call_len( len(sig)) + sig + call_len(len(pubkey)) + pubkey elif version_byte in version_dict["scripthash"].values(): json_tx["vin"][index]["scriptSig"]["hex"] = deal_sig( json_tx["vin"][index]["scriptSig"]["hex"], sig, redem, privkey) else: raise ValueError("Unknown version_byte: '%s' ." % version_byte) return json2raw(json_tx)
def __init__(self, PrivateKey = None): if PrivateKey == None: print("THERE WAS NO PRIVATE KEY GIVEN AS ARGUMENT \n") raise else: self.private_key = PrivateKey try: self.decoded_private_key = bitcoin.decode_privkey(self.private_key, 'hex') except Exception as e: pass #creates decimal of private key - this function turns it into either decimal or hex check = self.checkIfPrivateKeyIsValid(); if check: print("Valid Private Key \n") self.wif_encoded_private_key = bitcoin.encode_privkey(self.decoded_private_key, 'wif') # GENERATE PUBLIC KEYS self.public_key = bitcoin.privkey_to_pubkey(self.private_key) # located in files # self.bitcoinAddress = bitcoin.pubkey_to_address(self.public_key) # # # self.public_key_f_m = bitcoin.fast_multiply(bitcoin.G, self.decoded_private_key) # self.hex_encoded_public_key = bitcoin.encode_pubkey(self.public_key_f_m, 'hex') # # self.hex_compressed_public_key = self.generateHexCompressedPublicKey(self.public_key_f_m) # self.bitcoinAddress2 = bitcoin.pubkey_to_address(self.public_key_f_m) # self.compressedBitcoinAddress = bitcoin.pubkey_to_address(self.hex_compressed_public_key.encode('utf-8')) else: print(" Invalid Private Key Check Failed!!! \n")
def sign(tx, i, priv, t="default", script="", hashcode=SIGHASH_ALL): i = int(i) #if (not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx): if not re.match('^[0-9a-fA-F]*$', tx): return binascii.unhexlify( custom_sign(safe_hexlify(tx), i, priv, hashcode)) if len(priv) <= 33: priv = b.safe_hexlify(priv) pub = b.privkey_to_pubkey(priv) address = b.pubkey_to_address(pub) if t not in ["atomic_1", "atomic_2"]: script = b.mk_pubkey_script(address) if script == "": error() signing_tx = b.signature_form( tx, i, script, hashcode) #mk_pubkey_scrip needs to be our custom scriptn sig = b.ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = b.deserialize(tx) if t == "atomic_1": txobj["ins"][i]["script"] = b.serialize_script([sig]) if t == "atomic_2": old_sig = txobj["ins"][i]["script"] txobj["ins"][i]["script"] = b.serialize_script([old_sig, sig, 1]) else: txobj["ins"][i]["script"] = b.serialize_script([sig, pub]) return b.serialize(txobj)
def __init__(self, priv_key=None): """ Create an instance :param priv_key: a private key """ if priv_key is None: priv_key = bytes(random_bytes(32)) length = len(priv_key) if length != 32: # Just handle 32 byte version raise ValueError("Invalid private key length") self.PrivateKey = bytearray(priv_key[-32:]) #Get last 32 bytes try: pubkey_encoded_not_compressed = bitcoin.privkey_to_pubkey(priv_key) except Exception as e: raise Exception("Could not determine public key") if pubkey_encoded_not_compressed: pubkey_points = bitcoin.decode_pubkey( pubkey_encoded_not_compressed, 'bin') pubx = pubkey_points[0] puby = pubkey_points[1] edcsa = ECDSA.secp256r1() self.PublicKey = edcsa.Curve.point(pubx, puby)
def __init__(self, private_key): self.PrivateKey = private_key self.PublicKey = privkey_to_pubkey(self.PrivateKey) self.PublicKeyHash = redeem_to_scripthash( pubkey_to_redeem(self.PublicKey))
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None): i = int(i) txobj = tx if isinstance(tx, dict) else deserialize(tx) if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)): return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv)) if len(priv) <= 33: priv = binascii.hexlify(priv) pub = privkey_to_pubkey(priv) address = pubkey_to_address(pub) wscript = mk_pubkey_script(address) if not script else script stripped_script = segwit_strip_script_separator(wscript, separator_index) signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode) rawsig = ecdsa_raw_sign( hashlib.sha256( hashlib.sha256( binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv) sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2) txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script] return serialize(txobj)
def _do_config_set(args): """Executes the 'set' subcommand. Given a key file, and a series of key/value pairs, it generates batches of sawtooth_config transactions in a BatchList instance, and stores it in a file. """ settings = [s.split('=', 1) for s in args.setting] with open(args.key, 'r') as key_file: wif_key = key_file.read().strip() signing_key = bitcoin.encode_privkey( bitcoin.decode_privkey(wif_key, 'wif'), 'hex') pubkey = bitcoin.encode_pubkey(bitcoin.privkey_to_pubkey(signing_key), 'hex') txns = [ _create_config_txn(pubkey, signing_key, setting) for setting in settings ] txn_ids = [txn.header_signature for txn in txns] batch_header = BatchHeader(signer_pubkey=pubkey, transaction_ids=txn_ids).SerializeToString() batch = Batch(header=batch_header, header_signature=bitcoin.ecdsa_sign(batch_header, signing_key), transactions=txns) batch_list = BatchList(batches=[batch]).SerializeToString() try: with open(args.output, 'wb') as batch_file: batch_file.write(batch_list) except: raise CliException('Unable to write to {}'.format(args.output))
def _private_value_to_public_values(self, private_value): """ Return the public values from the private value """ public_value_x, public_value_y = bitcoin.privkey_to_pubkey( private_value) return (public_value_x, public_value_y)
def sign_donation_tx(tx, i, priv): from bitcoin.main import fast_multiply, decode_privkey, G, inv, N from bitcoin.transaction import der_encode_sig k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) # k = deterministic_generate_k(msghash, priv) r, y = fast_multiply(G, k) s = inv(k, N) * (z + r * decode_privkey(priv)) % N rawsig = 27 + (y % 2), r, s sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2) # sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def do_populate(args): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") words = generate_word_list(args.pool_size) batches = [] total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction( verb='set', name=words[i], value=random.randint(9000, 100000), private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral=None, isTestnet=False, *args, **kwargs): QObject.__init__(self, *args, **kwargs) if collateral is None: collateral = {} self.tab_main = tab_main self.name = name self.ip = ip self.port = str(port) self.mnPrivKey = wif_to_privkey(mnPrivKey) self.mnWIF = mnPrivKey self.mnPubKey = bitcoin.privkey_to_pubkey(self.mnPrivKey) self.hwAcc = hwAcc self.spath = collateral['spath'] self.nodePath = "%d'/0/%d" % (self.hwAcc, self.spath) self.collateral = collateral self.isTestnet = isTestnet self.currHeight = 0 Masternode.mnCount += 1 printOK("Initializing MNode with collateral: %s" % self.nodePath)
def get_wallet_balance_from_seed(bip39_mnemonic, bip39_password, derivation_path, last_child_index_to_search, network=Network.MAINNET): bip39_mnemonic = bip39_mnemonic.strip() mnemonic_words = bip39_mnemonic.split() with open('words.txt') as file: lines = file.read().splitlines() validate_mnemonic(mnemonic_words, lines) entropy_and_checksum = mnemonic_to_entropy_and_checksum(bip39_mnemonic, lines) verify_checksum(entropy_and_checksum, int(len(mnemonic_words) / 3)) salt = "mnemonic" + bip39_password seed = hashlib.pbkdf2_hmac('sha512', bytearray(bip39_mnemonic, 'utf-8'), bytearray(salt, 'utf-8'), 2048) debug_print("seed: " + print_hex(seed)) (master_private_key, master_chain_code) = hmac_digest_and_split(bytearray("Bitcoin seed", 'utf-8'), seed, 'sha512') debug_print("Master Private Key: " + print_hex(master_private_key)) debug_print("Master Chain Code: " + print_hex(master_chain_code)) master_public_key = bitcoin.privkey_to_pubkey(master_private_key) compressed_master_public_key = bitcoin.compress(master_public_key) debug_print("Master Public Key: " + print_hex(master_public_key)) debug_print("Master Public Key (Compressed) : " + print_hex(compressed_master_public_key)) print_extended_keys(master_chain_code, master_private_key, compressed_master_public_key, 0, 0, True, None) total_balance = 0 magic_byte = public_magic_byte if network == Network.MAINNET else testnet_magic_byte for i in range(0, last_child_index_to_search): child_key, child_chain_code, child_pub_key = derive_child_from_path( derivation_path=derivation_path + str(i), parent_key=master_private_key, key_type=KeyType.PRIVATE, parent_chain_code=master_chain_code, network=network) address = bitcoin.pubkey_to_address(bitcoin.compress(child_pub_key), magic_byte) print("\nAddress: " + address + "\n") total_balance += query_address_info(address, network) print("Total Balance for this Wallet: " + pretty_format_account_balance(total_balance))
def do_populate(args): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey(bitcoin.privkey_to_pubkey(private_key), "hex") words = generate_word_list(args.pool_size) batches = [] total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction(verb='set', name=words[i], value=random.randint(9000, 100000), private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch(transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def test_spend_p2sh_utxos(setup_tx_creation): #make a multisig address from 3 privs privs = [chr(x) * 32 + '\x01' for x in range(1, 4)] pubs = [btc.privkey_to_pubkey(binascii.hexlify(priv)) for priv in privs] script = btc.mk_multisig_script(pubs, 2) msig_addr = btc.scriptaddr(script, magicbyte=196) #pay into it wallet = make_wallets(1, [[2, 0, 0, 0, 1]], 3)[0]['wallet'] jm_single().bc_interface.sync_wallet(wallet) amount = 350000000 ins_full = wallet.select_utxos(0, amount) txid = make_sign_and_push(ins_full, wallet, amount, output_addr=msig_addr) assert txid #wait for mining time.sleep(4) #spend out; the input can be constructed from the txid of previous msig_in = txid + ":0" ins = [msig_in] #random output address and change addr output_addr = wallet.get_new_addr(1, 1) amount2 = amount - 50000 outs = [{'value': amount2, 'address': output_addr}] tx = btc.mktx(ins, outs) sigs = [] for priv in privs[:2]: sigs.append(btc.multisign(tx, 0, script, binascii.hexlify(priv))) tx = btc.apply_multisignatures(tx, 0, script, sigs) txid = jm_single().bc_interface.pushtx(tx) assert txid
def sign_donation_tx(tx, i, priv): from bitcoin.main import fast_multiply, decode_privkey, G, inv, N from bitcoin.transaction import der_encode_sig k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form( tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) # k = deterministic_generate_k(msghash, priv) r, y = fast_multiply(G, k) s = inv(k, N) * (z + r * decode_privkey(priv)) % N rawsig = 27 + (y % 2), r, s sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2) # sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def generatekey(): keyword = request.args.get('keyword') mypriv = bitcoin.sha256(keyword) mypubl = bitcoin.privkey_to_pubkey(mypriv) myaddress = bitcoin.pubkey_to_address(mypubl) myInfo = {'mypriv': mypriv, 'mypubl': mypubl, 'myaddress': myaddress} return json.dumps(myInfo)
def controller_recover_key(recovery_phrase): #function to recover a public and private key pair from a mnemonic phrase mnemonic_base = Mnemonic(language='english') seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey
def test_set_status(self): """Tests that set_status() has the correct behavior. Basically: 1. Adds a batch which has two transactions. 2. Calls next_transaction() to get the first Transaction. 3. Calls next_transaction() to verify that it returns None. 4. Calls set_status() to mark the first transaction applied. 5. Calls next_transaction() to get the second Transaction. Step 3 returns None because the first transaction hasn't been marked as applied, and the SerialScheduler will only return one not-applied Transaction at a time. Step 5 is expected to return the second Transaction, not None, since the first Transaction was marked as applied in the previous step. """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) txns = [] for name in ['a', 'b']: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) scheduler.add_batch(batch) scheduled_txn_info = scheduler.next_transaction() self.assertIsNotNone(scheduled_txn_info) self.assertEquals('a', scheduled_txn_info.txn.payload.decode()) self.assertIsNone(scheduler.next_transaction()) scheduler.set_transaction_execution_result( scheduled_txn_info.txn.header_signature, is_valid=False, context_id=None) scheduled_txn_info = scheduler.next_transaction() self.assertIsNotNone(scheduled_txn_info) self.assertEquals('b', scheduled_txn_info.txn.payload.decode())
def ecdsa_sign_bin(msgbin, priv): v, r, s = ecdsa_raw_sign(msgbin, priv) sig = encode_sig(v, r, s) pubkey = privkey_to_pubkey(wif_to_privkey(priv)) ok = ecdsa_raw_verify(msgbin, decode_sig(sig), pubkey) if not ok: raise Exception('Bad signature!') return sig
def ecdsa_sign(msg: str, wif_priv_key: str, dash_network: str): """Signs a message with the Elliptic Curve algorithm.""" v, r, s = bitcoin.ecdsa_raw_sign(electrum_sig_hash(msg), wif_priv_key) sig = bitcoin.encode_sig(v, r, s) pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(wif_priv_key, dash_network)) ok = bitcoin.ecdsa_raw_verify(electrum_sig_hash(msg), bitcoin.decode_sig(sig), pubkey) if not ok: raise Exception('Bad signature!') return sig
def get_key_pair(): v = False while not v: private_key = bitcoin.random_key() private_key = bitcoin.decode_privkey(private_key) v = 0 < private_key < bitcoin.N wif_private_key = bitcoin.encode_privkey(private_key, 'wif') public_key = bitcoin.privkey_to_pubkey(wif_private_key) address = bitcoin.pubkey_to_address(public_key) return address, wif_private_key
def sign(self, priv): # tx_in들에 sign에 self.hash에 대한 서명을 작성 for tx_in in self.inputs: # digest = SHA256.new(str(tx_in).encode()) # signer = PKCS1_v1_5.new(priv) # tx_in.sign = signer.sign(digest) # 서명 # tx_in.pubk = str(priv.publickey()) tx_in.pubk = bitcoin.privkey_to_pubkey(priv) digest = bitcoin.sha256(str(tx_in)) tx_in.sign = bitcoin.ecdsa_sign(digest, priv)
def test_transaction_order(self): """Tests the that transactions are returned in order added. Adds three batches with varying number of transactions, then tests that they are returned in the appropriate order when using an iterator. This test also creates a second iterator and verifies that both iterators return the same transactions. This test also finalizes the scheduler and verifies that StopIteration is thrown by the iterator. """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) txns = [] for names in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]: batch_txns = [] for name in names: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) batch_txns.append(txn) txns.append(txn) batch = create_batch( transactions=batch_txns, private_key=private_key, public_key=public_key) scheduler.add_batch(batch) scheduler.finalize() iterable1 = iter(scheduler) iterable2 = iter(scheduler) for txn in txns: scheduled_txn_info = next(iterable1) self.assertEqual(scheduled_txn_info, next(iterable2)) self.assertIsNotNone(scheduled_txn_info) self.assertEquals(txn.payload, scheduled_txn_info.txn.payload) scheduler.set_transaction_execution_result( txn.header_signature, False, None) with self.assertRaises(StopIteration): next(iterable1)
def test_pubkey_to_address(self): # generate random private key and convert to public randomPubKey = bitcoin.privkey_to_pubkey(generate_privkey()) # compute address randomPivxAddr = pubkey_to_address(randomPubKey) # check leading char 'D' self.assertEqual(randomPivxAddr[0], 'D') # decode and verify checksum randomPivxAddr_bin = bytes.fromhex(b58decode(randomPivxAddr).hex()) randomPivxAddr_bin_check = bitcoin.bin_dbl_sha256(randomPivxAddr_bin[0:-4])[0:4] self.assertEqual(randomPivxAddr_bin[-4:], randomPivxAddr_bin_check)
def ecdsa_sign_raw(msg_raw: bytes, wif_priv_key: str, dash_network: str): """Signs raw bytes (a message hash) with the Elliptic Curve algorithm. """ v, r, s = bitcoin.ecdsa_raw_sign(msg_raw, wif_priv_key) sig = bitcoin.encode_sig(v, r, s) pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(wif_priv_key, dash_network)) ok = bitcoin.ecdsa_raw_verify(msg_raw, bitcoin.decode_sig(sig), pubkey) if not ok: raise Exception('Bad signature!') return sig
def ecdsa_sign(msg, priv): """ Based on project: https://github.com/chaeplin/dashmnb. """ v, r, s = ecdsa_raw_sign(electrum_sig_hash(msg), priv) sig = encode_sig(v, r, s) pubkey = privkey_to_pubkey(wif_to_privkey(priv)) ok = ecdsa_raw_verify(electrum_sig_hash(msg), decode_sig(sig), pubkey) if not ok: raise Exception('Bad signature!') return sig
def controller_keygen(): #function to generate a random mnemonic recovery phrase #and in turn a private a public keys decode_hex = codecs.getdecoder("hex_codec") entropy_hex = bc.random_key() entropy_bytes = decode_hex(entropy_hex)[0] mnemonic_base = Mnemonic(language='english') recovery_phrase = mnemonic_base.to_mnemonic(entropy_bytes) seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey, recovery_phrase
def ecdsa_sign(msg, priv): """ Based on project: https://github.com/chaeplin/dashmnb with some changes related to usage of bitcoin library. """ v, r, s = bitcoin.ecdsa_raw_sign(electrum_sig_hash(msg), priv) sig = bitcoin.encode_sig(v, r, s) pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(priv)) ok = bitcoin.ecdsa_raw_verify(electrum_sig_hash(msg), bitcoin.decode_sig(sig), pubkey) if not ok: raise Exception('Bad signature!') return sig
def derive_child_key(parent_key, parent_chain_code, index, key_type, hardened=False): if hardened: if key_type == KeyType.PUBLIC: exit_with_error("Can not derive a hardened public child key from parent public key") input_data = bytearray(b'\x00') + parent_key else: if key_type == KeyType.PUBLIC: input_data = bitcoin.compress(parent_key) else: public_key = bitcoin.privkey_to_pubkey(parent_key) input_data = bitcoin.compress(public_key) input_data += int(index).to_bytes(4, byteorder='big') key = parent_chain_code (key_offset, chain_code) = hmac_digest_and_split(key, input_data) if key_type == KeyType.PUBLIC: point = bitcoin.decompress(bitcoin.privkey_to_pubkey(key_offset)) parent_point = bitcoin.decompress(parent_key) return bitcoin.add_pubkeys(point, parent_point), chain_code else: key = (int.from_bytes(parent_key, byteorder='big', signed=False) + int.from_bytes(key_offset, byteorder='big', signed=False)) % bitcoin.N return key.to_bytes(32, byteorder='big', signed=False), chain_code
def do_generate(args): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") words = generate_word_list(args.pool_size) batches = [] start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def __init__(self, priv_key): """ Create an instance. Args: priv_key (bytes): a private key. Raises: ValueError: if the input `priv_key` length is not 32, 96, or 104 if the input `priv_key` length is 32 but the public key still could not be determined """ self.setup_curve() self.PublicKeyHash = None self.PublicKey = None self.PrivateKey = None length = len(priv_key) if length != 32 and length != 96 and length != 104: raise ValueError("Invalid private key") self.PrivateKey = bytearray(priv_key[-32:]) pubkey_encoded_not_compressed = None if length == 32: try: pubkey_encoded_not_compressed = bitcoin.privkey_to_pubkey( priv_key) except Exception: raise ValueError("Could not determine public key") elif length == 96 or length == 104: skip = length - 96 pubkey_encoded_not_compressed = bytearray(b'\x04') + bytearray( priv_key[skip:skip + 64]) if pubkey_encoded_not_compressed: pubkey_points = bitcoin.decode_pubkey( pubkey_encoded_not_compressed, 'bin') pubx = pubkey_points[0] puby = pubkey_points[1] edcsa = ECDSA.secp256r1() self.PublicKey = edcsa.Curve.point(pubx, puby) self.PublicKeyHash = Crypto.ToScriptHash( self.PublicKey.encode_point(True), unhex=True)
def test_high_volume_derivation(self): number_of_keys = 10 public_keychain = PublicKeychain.from_public_key(self.public_key_hex) private_keychain = PrivateKeychain.from_private_key(self.private_key_hex) keypairs = [] print "" for i in range(number_of_keys): print "making key %i of %i" % (i+1, number_of_keys) public_key = public_keychain.child(i).public_key() private_key = private_keychain.child(i).private_key() keypairs.append({ 'public': public_key, 'private': private_key }) for i in range(len(keypairs)): keypair = keypairs[i] print "checking key %i of %i" % (i+1, number_of_keys) self.assertEqual(privkey_to_pubkey(keypair['private']), keypair['public'])
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None): i = int(i) txobj = tx if isinstance(tx, dict) else deserialize(tx) if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)): return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv)) if len(priv) <= 33: priv = binascii.hexlify(priv) pub = privkey_to_pubkey(priv) address = pubkey_to_address(pub) wscript = mk_pubkey_script(address) if not script else script stripped_script = segwit_strip_script_separator(wscript, separator_index) signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode) rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv) sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2) txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script] return serialize(txobj)
def do_generate(args, batches, words): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop
def do_populate(args, batches, words): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction( verb='set', name=words[i], value=random.randint(9000, 100000), private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch)
def sign(tx, i, priv, t="default", script="", hashcode=SIGHASH_ALL): i = int(i) #if (not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx): if not re.match('^[0-9a-fA-F]*$', tx): return binascii.unhexlify(custom_sign(safe_hexlify(tx), i, priv, hashcode)) if len(priv) <= 33: priv = b.safe_hexlify(priv) pub = b.privkey_to_pubkey(priv) address = b.pubkey_to_address(pub) if t not in ["atomic_1", "atomic_2"]: script=b.mk_pubkey_script(address) if script=="": error() signing_tx = b.signature_form(tx, i, script, hashcode)#mk_pubkey_scrip needs to be our custom scriptn sig = b.ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = b.deserialize(tx) if t=="atomic_1": txobj["ins"][i]["script"] = b.serialize_script([sig]) if t=="atomic_2": old_sig = txobj["ins"][i]["script"] txobj["ins"][i]["script"] = b.serialize_script([old_sig, sig, 1]) else: txobj["ins"][i]["script"] = b.serialize_script([sig, pub]) return b.serialize(txobj)
elif len(buf) < 0x100: self.add(ScriptOp.OP_PUSHDATA1) self.add(len(buf)) self.add(buf) elif len(buf) < 0x10000: self.add(ScriptOp.OP_PUSHDATA2) self.add(len(buf) & 0xff) self.add(len(buf) >> 8) self.add(buf) elif len(buf) < 0x100000000: self.add(ScriptOp.OP_PUSHDATA4) self.add(len(buf) & 0xff) self.add((len(buf) >> 8) & 0xff) self.add((len(buf) >> 16) & 0xff) self.add(len(buf) >> 24) self.add(buf) return def toArray(self): return self.ms.toArray() if __name__ == '__main__': from bitcoin import privkey_to_pubkey pubkey = privkey_to_pubkey('L1RrT1f4kXJGnF2hESU1AbaQQG82WqLsmWQWEPGm2fbrNLwdrAV9') sb = ScriptBuilder() sb.add(21) sb.push(pubkey) sb.add(ScriptOp.OP_CHECKSIG) print sb.toArray()
def _private_to_public(private): return bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private), "hex" )
def put_mutable(name, data_id, data_text, privatekey, proxy=None, create=True, txid=None, ver=None, make_ver=None, conf=None ): """ put_mutable ** Consistency ** ver, if given, is the version to include in the data. make_ver, if given, is a callback that takes the data_id, data_text, and current version as arguments, and generates the version to be included in the data record uploaded. If ver is not given, but make_ver is, then make_ver will be used to generate the version. If neither ver nor make_ver are given, the mutable data (if it already exists) is fetched, and the version is calculated as the larget known version + 1. ** Durability ** Replication is best-effort. If one storage provider driver succeeds, the put_mutable succeeds. If they all fail, then put_mutable fails. More complex behavior can be had by creating a "meta-driver" that calls existing drivers' methods in the desired manner. """ if proxy is None: proxy = get_default_proxy() result = {} user = get_name_record(name, create_if_absent=create) if 'error' in user: return {'error': "Unable to load user record: %s" % user['error']} route = None exists = user_db.has_mutable_data_route(user, data_id) old_hash = None cur_hash = None new_ver = ver if ver is None: if exists: # mutable record already exists. # generate one automatically. # use the existing locally-stored version, # and fall back to using the last-known version # from the existing mutable data record. new_ver = load_mutable_data_version( config.get_config(), name, data_id, try_remote=True ) if new_ver is None: # data exists, but we couldn't figure out the version return {'error': "Unable to determine version"} if make_ver is not None: # generate version new_ver = make_ver( data_id, data_text, new_ver ) else: # no version known, and no way to generate it. # by default, start at 1. we'll manage it ourselves. if new_ver is None: new_ver = 1 else: new_ver += 1 # do we have a route for this data yet? if not exists: if not create: # won't create; expect it to exist return {'error': 'No such route'} # need to put one urls = storage.make_mutable_urls(data_id) if len(urls) == 0: return {"error": "No routes constructed"} writer_pubkey = pybitcointools.privkey_to_pubkey(privatekey) route = storage.mutable_data_route(data_id, urls, writer_pubkey=writer_pubkey) user_db.add_mutable_data_route(user, route) user_json = user_db.serialize_user(user) # update the user record with the new route update_result = update(name, user_json, privatekey, txid=txid, proxy=proxy) if 'error' in update_result: # update failed; caller should try again return update_result txid = update_result['transaction_hash'] cur_hash = update_result['value_hash'] else: route = user_db.get_mutable_data_route(user, data_id) if route is None: return {"error": "No such route"} # generate the data data = storage.mutable_data(data_id, data_text, new_ver, privkey=privatekey) if data is None: return {"error": "Failed to generate data record"} # serialize... data_json = parsing.json_stable_serialize(data) # replicate... store_rc = storage.put_mutable_data( data, privatekey ) if not store_rc: result['error'] = "Failed to store mutable data" else: result['status'] = True result['transaction_hash'] = txid if cur_hash: # propagate result['value_hash'] = cur_hash # cache new version store_mutable_data_version( conf, data_id, new_ver ) return result
addr = utils.privtoaddr(key) # get address from private key gen = blocks.genesis({addr: 10**60}) assembly = serpent.compile_to_assembly(open('tester.se').read()) print assembly code = serpent.assemble(assembly) print code msg_hash = utils.sha3('heres a message') v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key) pub = bitcoin.privkey_to_pubkey(key) verified = bitcoin.ecdsa_raw_verify(msg_hash, (v, r, s), pub) print verified tx_make_root = transactions.contract(0,10,10**30, 10**30, code).sign(key) success, root_contract = processblock.apply_tx(gen, tx_make_root) #tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([msg_hash, v, r, s])).sign(key) #tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist(['hi', 'bye'])).sign(key) tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([2, '139dcd5cc79e260272e05147c349ab5f2db3f102', 1])).sign(key) #tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([2, 1])).sign(key) print assembly success, ans = processblock.apply_tx(gen, tx_init_root) print ans data = serpent.decode_datalist(ans) print data
def _private_value_to_public_values(self, private_value): """ Return the public values from the private value """ public_value_x, public_value_y = bitcoin.privkey_to_pubkey(private_value) return (public_value_x, public_value_y)
def handle_bid_order(self, bid): self.log.info('Bid Order: %s', bid) new_peer = self.transport.get_crypto_peer(bid.get('merchantGUID'), bid.get('merchantURI'), bid.get('merchantPubkey')) # Generate unique id for this bid order_id = random.randint(0, 1000000) while len(self.db.selectEntries("contracts", {"id": order_id})) > 0: order_id = random.randint(0, 1000000) # Add to contract and sign contract = bid.get('rawContract') contract_stripped = "".join(contract.split('\n')) bidder_pgp_start_index = contract_stripped.find("buyer_pgp", 0, len(contract_stripped)) bidder_pgp_end_index = contract_stripped.find("buyer_GUID", 0, len(contract_stripped)) bidder_pgp = contract_stripped[bidder_pgp_start_index + 13:bidder_pgp_end_index] self.gpg.import_keys(bidder_pgp) v = self.gpg.verify(contract) if v: self.log.info('Sellers contract verified') notary_section = {} notary_section['Notary'] = { 'notary_GUID': self.transport.guid, 'notary_BTC_uncompressed_pubkey': privkey_to_pubkey(self.transport.settings['privkey']), 'notary_pgp': self.transport.settings['PGPPubKey'], 'notary_fee': "", 'notary_order_id': order_id } offer_data_json = self.get_offer_json(contract, Orders.State.SENT) bid_data_json = self.get_buyer_json(contract, Orders.State.SENT) pubkeys = [ offer_data_json['Seller']['seller_BTC_uncompressed_pubkey'], bid_data_json['Buyer']['buyer_BTC_uncompressed_pubkey'], privkey_to_pubkey(self.transport.settings['privkey']) ] script = mk_multisig_script(pubkeys, 2, 3) multisig_address = scriptaddr(script) notary_section['Escrow'] = { 'multisig_address': multisig_address, 'redemption_script': script } self.log.debug('Notary: %s', notary_section) gpg = self.gpg # Prepare contract body notary_json = json.dumps(notary_section, indent=0) seg_len = 52 out_text = "\n".join( notary_json[x:x + seg_len] for x in range(0, len(notary_json), seg_len) ) # Append new data to contract out_text = "%s\n%s" % (contract, out_text) signed_data = gpg.sign(out_text, passphrase='P@ssw0rd', keyid=self.transport.settings.get('PGPPubkeyFingerprint')) self.log.debug('Double-signed Contract: %s', signed_data) # Hash the contract for storage contract_key = hashlib.sha1(str(signed_data)).hexdigest() hash_value = hashlib.new('ripemd160') hash_value.update(contract_key) contract_key = hash_value.hexdigest() self.log.info('Order ID: %s', order_id) # Push buy order to DHT and node if available # self.transport.store(contract_key, str(signed_data), self.transport.guid) # self.update_listings_index() # Find Seller Data in Contract offer_data = ''.join(contract.split('\n')[8:]) index_of_seller_signature = offer_data.find('- -----BEGIN PGP SIGNATURE-----', 0, len(offer_data)) offer_data_json = "{\"Seller\": {" + offer_data[0:index_of_seller_signature] self.log.info('Offer Data: %s', offer_data_json) offer_data_json = json.loads(str(offer_data_json)) # Find Buyer Data in Contract bid_data_index = offer_data.find('"Buyer"', index_of_seller_signature, len(offer_data)) end_of_bid_index = offer_data.find('-----BEGIN PGP SIGNATURE', bid_data_index, len(offer_data)) bid_data_json = "{" + offer_data[bid_data_index:end_of_bid_index] bid_data_json = json.loads(bid_data_json) self.log.info('Bid Data: %s', bid_data_json) buyer_order_id = "%s-%s" % ( bid_data_json['Buyer']['buyer_GUID'], bid_data_json['Buyer']['buyer_order_id'] ) pubkeys = [ offer_data_json['Seller']['seller_BTC_uncompressed_pubkey'], bid_data_json['Buyer']['buyer_BTC_uncompressed_pubkey'], privkey_to_pubkey(self.transport.settings['privkey']) ] script = mk_multisig_script(pubkeys, 2, 3) multisig_address = scriptaddr(script) self.db.insertEntry( "orders", { 'market_id': self.transport.market_id, 'contract_key': contract_key, 'signed_contract_body': str(signed_data), 'state': Orders.State.NOTARIZED, 'buyer_order_id': buyer_order_id, 'order_id': order_id, 'merchant': offer_data_json['Seller']['seller_GUID'], 'buyer': bid_data_json['Buyer']['buyer_GUID'], 'address': multisig_address, 'item_price': offer_data_json['Contract'].get('item_price', 0), 'shipping_price': offer_data_json['Contract']['item_delivery'].get('shipping_price', ""), 'note_for_merchant': bid_data_json['Buyer']['note_for_seller'], "updated": time.time() } ) # Send order to seller and buyer self.log.info('Sending notarized contract to buyer and seller %s', bid) if self.transport.handler is not None: self.transport.handler.send_to_client(None, {"type": "order_notify", "msg": "You just auto-notarized a contract."}) notarized_order = { "type": "order", "state": "Notarized", "rawContract": str(signed_data) } if new_peer is not None: new_peer.send(notarized_order) self.transport.send(notarized_order, bid_data_json['Buyer']['buyer_GUID']) self.log.info('Sent notarized contract to Seller and Buyer')
def test_valid_batch_invalid_batch(self): """Tests the squash function. That the correct hash is being used for each txn and that the batch ending state hash is being set. Basically: 1. Adds two batches, one where all the txns are valid, and one where one of the txns is invalid. 2. Run through the scheduler executor interaction as txns are processed. 3. Verify that the valid state root is obtained through the squash function. 4. Verify that correct batch statuses are set """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) # 1) batch_signatures = [] for names in [['a', 'b'], ['invalid', 'c']]: batch_txns = [] for name in names: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) batch_txns.append(txn) batch = create_batch( transactions=batch_txns, private_key=private_key, public_key=public_key) batch_signatures.append(batch.header_signature) scheduler.add_batch(batch) scheduler.finalize() # 2) sched1 = iter(scheduler) invalid_payload = hashlib.sha512('invalid'.encode()).hexdigest() while not scheduler.complete(block=False): txn_info = next(sched1) txn_header = transaction_pb2.TransactionHeader() txn_header.ParseFromString(txn_info.txn.header) inputs_or_outputs = list(txn_header.inputs) c_id = context_manager.create_context(txn_info.state_hash, inputs_or_outputs, inputs_or_outputs) if txn_header.payload_sha512 == invalid_payload: scheduler.set_transaction_execution_result( txn_info.txn.header_signature, False, c_id) else: context_manager.set(c_id, [{inputs_or_outputs[0]: 1}]) scheduler.set_transaction_execution_result( txn_info.txn.header_signature, True, c_id) sched2 = iter(scheduler) # 3) txn_info_a = next(sched2) self.assertEquals(first_state_root, txn_info_a.state_hash) txn_a_header = transaction_pb2.TransactionHeader() txn_a_header.ParseFromString(txn_info_a.txn.header) inputs_or_outputs = list(txn_a_header.inputs) address_a = inputs_or_outputs[0] c_id_a = context_manager.create_context(first_state_root, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_a, [{address_a: 1}]) state_root2 = context_manager.commit_context([c_id_a], virtual=False) txn_info_b = next(sched2) self.assertEquals(txn_info_b.state_hash, state_root2) txn_b_header = transaction_pb2.TransactionHeader() txn_b_header.ParseFromString(txn_info_b.txn.header) inputs_or_outputs = list(txn_b_header.inputs) address_b = inputs_or_outputs[0] c_id_b = context_manager.create_context(state_root2, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_b, [{address_b: 1}]) state_root3 = context_manager.commit_context([c_id_b], virtual=False) txn_infoInvalid = next(sched2) self.assertEquals(txn_infoInvalid.state_hash, state_root3) txn_info_c = next(sched2) self.assertEquals(txn_info_c.state_hash, state_root3) # 4) batch1_result = scheduler.get_batch_execution_result( batch_signatures[0]) self.assertTrue(batch1_result.is_valid) self.assertEquals(batch1_result.state_hash, state_root3) batch2_result = scheduler.get_batch_execution_result( batch_signatures[1]) self.assertFalse(batch2_result.is_valid) self.assertIsNone(batch2_result.state_hash)