def sign_btc(msghash, priv, pub): V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) Q = bitcoin.ecdsa_raw_recover(msghash, (V, R, S)) assert addr == bitcoin.encode_pubkey( Q, 'hex_compressed') if V >= 31 else bitcoin.encode_pubkey(Q, 'hex') return (V, R, S)
def generate_address(secret_bytes): int_privkey = int.from_bytes(secret_bytes, 'big') print('privkey (int): {privkey}'.format(privkey=int_privkey)) wif_not_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif') print('privkey (wif, not compressing): {privkey}'.format( privkey=wif_not_compressing_privkey)) wif_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif_compressed') print('privkey (wif, compressing): {privkey}'.format( privkey=wif_compressing_privkey)) print() public_key = bitcoin.fast_multiply(bitcoin.G, int_privkey) print('pubkey pair (int): {pubkey}'.format(pubkey=public_key)) pubkey_not_compressed = bitcoin.encode_pubkey(public_key, 'hex') print('pubkey (not compressed, hex): {pubkey}'.format( pubkey=pubkey_not_compressed)) pubkey_compressed = bitcoin.encode_pubkey(public_key, 'hex_compressed') print( 'pubkey (compressed, hex): {pubkey}'.format(pubkey=pubkey_compressed)) address_not_compressed = bitcoin.pubkey_to_address(public_key) print('address (not compressed, b58check): {address}'.format( address=address_not_compressed)) address_compressed = bitcoin.pubkey_to_address(pubkey_compressed) print('address (compressed, b58check): {address}'.format( address=address_compressed)) return address_compressed
def ecdsa_verify_addr(msg, sig, addr): isTestnet = addr[0] not in P2PKH_PREFIXES if not checkPivxAddr(addr, isTestnet): return False v, r, s = decode_sig(sig) Q = ecdsa_raw_recover(electrum_sig_hash(msg), (v, r, s)) Qenc = encode_pubkey(Q, 'hex_compressed') if v >= 31 else encode_pubkey( Q, 'hex') return pubkey_to_address(Qenc, isTestnet) == addr
def _generate_new_keypair(self): seed = str(random.randrange(2**256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey( bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv new_settings = { "secret": self.secret, "pubkey": self.pubkey, "bip32_seed": seed } self.db_connection.update_entries("settings", new_settings, {"market_id": self.market_id}) self.settings.update(new_settings)
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 verify_signature(addr, h, V_R_S): V, R, S = V_R_S pub = bitcoin.ecdsa_raw_recover(h, (V, R, S)) pub = bitcoin.encode_pubkey(pub, 'bin') addr_ = utils.sha3(pub[1:])[12:] assert addr_ == addr return True
def generate_keypair(crypto, seed, password=None): """ Generate a private key and publickey for any currency, given a seed. That seed can be random, or a brainwallet phrase. """ pub_byte, priv_byte = get_magic_bytes(crypto) priv = sha256(seed) pub = privtopub(priv) priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte) if password: # pycrypto etc. must be installed or this will raise ImportError, hence inline import. from .bip38 import Bip38EncryptedPrivateKey priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password)) compressed_pub = encode_pubkey(pub, 'hex_compressed') ret = { 'public': { 'hex_uncompressed': pub, 'hex': compressed_pub, 'address': pubtoaddr(compressed_pub, pub_byte) }, 'private': { 'wif': priv_wif } } if not password: # only these are valid when no bip38 password is supplied ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte) ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte) ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte) return ret
def encode(public_value_x, public_value_y): """ Encode the public key represented by the decimal values x and y to base58 """ public_value_compressed_hex = bitcoin.encode_pubkey([public_value_x, public_value_y], 'hex_compressed') public_value_compressed_base58 = base58.b58encode(bytes.fromhex(public_value_compressed_hex)) return public_value_compressed_base58
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 _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 encode(public_value_x, public_value_y): """ Encode the public key represented by the decimal values x and y to base58 """ public_value_compressed_hex = bitcoin.encode_pubkey([public_value_x, public_value_y], "hex_compressed") public_value_compressed_base58 = base58.b58encode(bytes.fromhex(public_value_compressed_hex)) return public_value_compressed_base58
def _generate_new_keypair(self): seed = str(random.randrange(2 ** 256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv new_settings = { "secret": self.secret, "pubkey": self.pubkey, "bip32_seed": seed } self.db_connection.update_entries("settings", new_settings, {"market_id": self.market_id}) self.settings.update(new_settings)
def sender(self): if not self._sender: # Determine sender if self.v: if self.r >= N or self.s >= N or self.v < 27 or self.v > 28 \ or self.r == 0 or self.s == 0: raise InvalidTransaction("Invalid signature values!") log.debug('recovering sender') rlpdata = rlp.encode(self, UnsignedTransaction) rawhash = utils.sha3(rlpdata) pk = PublicKey(flags=ALL_FLAGS) try: pk.public_key = pk.ecdsa_recover( rawhash, pk.ecdsa_recoverable_deserialize( zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.r)), 32) + zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.s)), 32), self.v - 27 ), raw=True ) pub = pk.serialize(compressed=False) except Exception: raise InvalidTransaction("Invalid signature values (x^3+7 is non-residue)") if pub[1:] == b"\x00" * 32: raise InvalidTransaction("Invalid signature (zero privkey cannot sign)") pub = encode_pubkey(pub, 'bin') self._sender = utils.sha3(pub[1:])[-20:] assert self.sender == self._sender else: self._sender = 0 return self._sender
def ecdsa_recover(message, signature): assert len(signature) == 65 pub = ecdsa_raw_recover(message, _decode_sig(signature)) assert pub, 'pubkey could not be recovered' pub = bitcoin.encode_pubkey(pub, 'bin_electrum') assert len(pub) == 64 return pub
def __init__(self, nonce, gasprice, startgas, to, value, data, v=0, r=0, s=0): self.nonce = nonce self.gasprice = gasprice self.startgas = startgas self.to = to self.value = value self.data = data self.v, self.r, self.s = v, r, s # Determine sender if self.r and self.s: rawhash = utils.sha3(self.serialize(False)) pub = encode_pubkey( ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin') self.sender = utils.sha3(pub[1:])[-20:].encode('hex') # does not include signature else: self.sender = 0
def becies_encode(ephemeral_pubkey, ciphertext, tag, pubkeys=[], num_to_activate=None, offsets=None): bout = BECIES_MAGIC_BYTES #0xc66b20 3-byte prefix? (encodes to xmsg in base64) isaddresses = bool(pubkeys) isgroup = bool(offsets) #a vli indicating the header contents flags. #offsets,and addresses are first two bits, rest are unused bout += _to_vli( int(isgroup) * BECIES_GROUP_FLAG + int(isaddresses) * BECIES_ADDRESSES_FLAG) if (isaddresses): bout += _to_vli(len(pubkeys)) bout += ''.join( [bitcoin.b58check_to_bin(bitcoin.pubtoaddr(p)) for p in pubkeys]) if (isgroup): bout += _to_vli( num_to_activate) #todo, num_to_activate must be strictly positive bout += _to_vli(len(offsets)) bout += ''.join([bitcoin.encode_privkey(priv) for priv in offsets]) bout += bitcoin.encode_pubkey(ephemeral_pubkey, 'bin_compressed') bout += _to_vli(len(ciphertext)) bout += ciphertext bout += tag #this has to come last for streaming mode too return bout
def test_ecrecover(): s = tester.state() c = s.abi_contract(ecrecover_code) priv = utils.sha3('some big long brainwallet password') pub = bitcoin.privtopub(priv) msghash = utils.sha3('the quick brown fox jumps over the lazy dog') pk = PrivateKey(priv, raw=True) signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(msghash, raw=True) ) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) V = utils.safe_ord(signature[64]) + 27 R = big_endian_to_int(signature[0:32]) S = big_endian_to_int(signature[32:64]) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr result = c.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S) assert result == addr
def test_ecrecover(): s = tester.state() c = s.abi_contract(ecrecover_code) priv = utils.sha3('some big long brainwallet password') pub = bitcoin.privtopub(priv) msghash = utils.sha3('the quick brown fox jumps over the lazy dog') pk = PrivateKey(priv, raw=True) signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(msghash, raw=True)) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) V = utils.safe_ord(signature[64]) + 27 R = big_endian_to_int(signature[0:32]) S = big_endian_to_int(signature[32:64]) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.big_endian_to_int( utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr result = c.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S) assert result == addr
def verify_signature(addr, h, xxx_todo_changeme): (V, R, S) = xxx_todo_changeme pub = bitcoin.ecdsa_raw_recover(h, (V, R, S)) pub = bitcoin.encode_pubkey(pub, 'bin') addr_ = utils.sha3(pub[1:])[12:] assert addr_ == addr return True
def generate_keyfiles(n, m, vf, sf): '''Generate a set of public and private keys for testing. n - the number of OR loops m - the number of keys per loop (note: constant in this crude version) vf - the file path to which to write the verification keys sf - the file path to which to write the signing (private) keys ''' signing_indices = [random.choice(range(m)) for _ in range(n)] priv = [] with open(sf, 'wb') as f: for i in range(n): priv.append(os.urandom(32)) f.write(binascii.hexlify(priv[i]) + '\n') with open(vf, 'wb') as f: for i in range(n): pubkeys = [] for j in range(m): if j == signing_indices[i]: p = btc.privtopub(priv[i]) else: p = btc.privtopub(os.urandom(32)) p = btc.decode_pubkey(p) p = btc.encode_pubkey(p, 'bin_compressed') pubkeys.append(binascii.hexlify(p)) f.write(','.join(pubkeys) + '\n')
def generate_keyfiles(n, m, vf, sf): '''Generate a set of public and private keys for testing. n - the number of OR loops m - the number of keys per loop (note: constant in this crude version) vf - the file path to which to write the verification keys sf - the file path to which to write the signing (private) keys ''' signing_indices = [random.choice(range(m)) for _ in range(n)] priv=[] with open(sf,'wb') as f: for i in range(n): priv.append(os.urandom(32)) f.write(binascii.hexlify(priv[i])+'\n') with open(vf,'wb') as f: for i in range(n): pubkeys = [] for j in range(m): if j==signing_indices[i]: p = btc.privtopub(priv[i]) else: p = btc.privtopub(os.urandom(32)) p = btc.decode_pubkey(p) p = btc.encode_pubkey(p,'bin_compressed') pubkeys.append(binascii.hexlify(p)) f.write(','.join(pubkeys)+'\n')
def recover_sender(self): if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28 \ or self.r == 0 or self.s == 0: raise InvalidSignature() rlpdata = rlp.encode(self, self.__class__.exclude(['v', 'r', 's'])) rawhash = sha3(rlpdata) pk = PublicKey(flags=ALL_FLAGS) try: pk.public_key = pk.ecdsa_recover( rawhash, pk.ecdsa_recoverable_deserialize( zpad( "".join( chr(c) for c in int_to_32bytearray(self.r)), 32) + zpad( "".join( chr(c) for c in int_to_32bytearray(self.s)), 32), self.v - 27), raw=True) pub = pk.serialize(compressed=False) except Exception: raise InvalidSignature() if pub[1:] == "\x00" * 32: raise InvalidSignature() pub = encode_pubkey(pub, 'bin') return sha3(pub[1:])[-20:]
def generate_keypair(crypto, seed, password=None): """ Generate a private key and publickey for any currency, given a seed. That seed can be random, or a brainwallet phrase. """ pub_byte, priv_byte = get_magic_bytes(crypto) priv = sha256(seed) pub = privtopub(priv) if priv_byte >= 128: priv_byte -= 128 #pybitcointools bug priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte) if password: priv_wif = bip38_encrypt(priv_wif, password) compressed_pub = encode_pubkey(pub, 'hex_compressed') ret = { 'public': { 'hex_uncompressed': pub, 'hex': compressed_pub, 'address': pubtoaddr(compressed_pub, pub_byte) }, 'private': { 'wif': priv_wif } } if not password: # only these are valid when no bip38 password is supplied ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte) ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte) ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte) return ret
def pubkey_to_bech32_address(pubkey, prefix=BECH32_BITCOIN_PREFIX): if isinstance(pubkey, (list, tuple)): pubkey = encode_pubkey(pubkey, 'bin') if len(pubkey) in [66, 130]: pubkey = binascii.unhexlify(pubkey) pubkey_hash = hash160(pubkey) return bech32encode('0014' + pubkey_hash, prefix=prefix) raise ValueError()
def test_raw(): vrs1 = b_ecdsa_raw_sign(msg32, priv) assert isinstance(vrs1, tuple) assert len(vrs1) == 3 vrs3 = c_ecdsa_sign_raw(msg32, priv) p1 = b_ecdsa_raw_recover(msg32, vrs1) p3 = c_ecdsa_recover_raw(msg32, vrs1) p4 = c_ecdsa_recover_raw(msg32, vrs3) p5 = b_ecdsa_raw_recover(msg32, vrs3) vrs2 = lr.ecdsa_sign_raw(msg32, priv) p9 = b_ecdsa_raw_recover(msg32, vrs2) p10 = c_ecdsa_recover_raw(msg32, vrs2) p7 = lr.ecdsa_recover_raw(msg32, vrs2) vrs4 = lc.ecdsa_sign_compact(msg32, priv) p8 = lr.ecdsa_recover_raw(msg32, vrs1) # Ensure that recovered pub key is the same assert encode_pubkey(p1, 'bin') == pub assert p4 == pub assert p7 == pub assert p8 == pub assert encode_pubkey(p8, 'bin') == pub assert p10 == pub assert encode_pubkey(p5, 'bin') == pub # check wrong pub wrong_vrs = c_ecdsa_sign_raw(msg32, 'x' * 32) wrong_vrs2 = lr.ecdsa_sign_raw(msg32, 'x' * 32) p2 = c_ecdsa_recover_raw(msg32, wrong_vrs) p3 = lr.ecdsa_recover_raw(msg32, wrong_vrs2) assert encode_pubkey(p2, 'bin') != pub assert encode_pubkey(p3, 'bin') != pub # verify assert lr.ecdsa_verify_raw(msg32, vrs2, p7) assert lc.ecdsa_verify_compact(msg32, vrs4, p7) # check wrong pub sig_vrs2 = c_ecdsa_sign_raw(msg32, 'x' * 32) p2 = c_ecdsa_recover_raw(msg32, sig_vrs2) assert p2 != pub # check wrong sig false_sig_vrs = sig_vrs2 assert not c_ecdsa_verify_raw(msg32, false_sig_vrs, pub) assert not lr.ecdsa_verify_raw(msg32, false_sig_vrs, pub)
def pubkey2adr(pub_hex, network=5): pub_bin = bitcoin.encode_pubkey(pub_hex, "bin_compressed") PKH = bitcoin.bin_hash160(pub_bin) # script = "\0" + PKH # address_bin = bitcoin.bin_hash160(script) address = bitcoin.bin_to_b58check(PKH, 0) #assert bitcoin.p2sh_scriptaddr(script,network) == address return address
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 generate_key(): #generate a random private key valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N #print ('Private Key (hex) is: ' + private_key) #print ('private Key (decimal) is: ' + str(decoded_private_key)) #convert private key to WIF format wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') #print('Private Key (WIF) is: ' + wif_encoded_private_key) # Add sufix '01' to indicate a compressed private Key compressed_private_key = private_key + '01' #print ('Private Key Compressed (hex) is: ' + compressed_private_key) # generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') #print ('Private Key (WIF-compressed) is: ' + wif_compressed_private_key) # Multiply de EC generator G with the priveate key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) #print ('Public Key (x,y) coordinates are: ' + str(public_key)) # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') #print ('Public Key (hex) is: ' + hex_encoded_public_key) # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key if public_key_y % 2 == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) #print ('Compressed Public Key is: ' + hex_compressed_public_key) # Generate bitcoin address from public Key #print ('Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(public_key)) # Generate compressedd bitcoin address from compressed public key #print ('Compressed Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(hex_compressed_public_key)) compressed_address_base58check = bitcoin.pubkey_to_address( hex_compressed_public_key) kson = { "wif1": wif_encoded_private_key, "wif": wif_compressed_private_key, "key": compressed_address_base58check } return kson
def get_sig_message(m, vks): '''The full message is a sha256 hash of the message string concatenated with the compressed binary format of all of the verification keys.''' full_message = m for loop in vks: for p in vks[loop]: full_message += btc.encode_pubkey(p, 'bin_compressed') return sha256(full_message).digest()
def sign(data: bytes, private_key_seed_ascii: str, hash_function=bitcoin.bin_sha256): """Sign data using Ethereum private key. :param private_key_seed_ascii: Private key seed as ASCII string """ msghash = hash_function(data) priv = utils.sha3(private_key_seed_ascii) pub = bitcoin.privtopub(priv) # Based on ethereum/tesrt_contracts.py test_ecrecover pk = PrivateKey(priv, raw=True) signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(msghash, raw=True)) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) # Enforce non-tightly-packed arguments for signing # (0x00 left pad) # https://github.com/ethereum/web3.py/issues/466 v = utils.safe_ord(signature[64]) + 27 r_bytes = signature[0:32] r_bytes = pad_left(r_bytes, 32, b"\0") r = big_endian_to_int(r_bytes) s_bytes = signature[32:64] s_bytes = pad_left(s_bytes, 32, b"\0") s = big_endian_to_int(s_bytes) # Make sure we use bytes data and zero padding stays # good across different systems r_hex = binascii.hexlify(r_bytes).decode("ascii") s_hex = binascii.hexlify(s_bytes).decode("ascii") # Convert to Etheruem address format addr = utils.big_endian_to_int( utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) # Return various bits about signing so it's easier to debug return { "signature": signature, "v": v, "r": r, "s": s, "r_bytes": r_bytes, "s_bytes": s_bytes, "r_hex": "0x" + r_hex, "s_hex": "0x" + s_hex, "address_bitcoin": addr, "address_ethereum": get_ethereum_address_from_private_key(priv), "public_key": pub, "hash": msghash, "payload": binascii.hexlify(bytes([v] + list(r_bytes) + list(s_bytes, ))) }
def get_sig_message(m, vks): '''The full message is a sha256 hash of the message string concatenated with the compressed binary format of all of the verification keys.''' full_message = m for loop in vks: for p in vks[loop]: full_message += btc.encode_pubkey(p,'bin_compressed') return sha256(full_message).digest()
def pkvkey2adrw(pvkey, network=5): pub_hex = bitcoin.privtopub(pvkey) pub_bin = bitcoin.encode_pubkey(pub_hex, "bin_compressed") PKH = bitcoin.bin_hash160(pub_bin) script = "\0\x14" + PKH address_bin = bitcoin.bin_hash160(script) address = bitcoin.bin_to_b58check(address_bin, network) assert bitcoin.p2sh_scriptaddr(script, network) == address return address
def demo_private_to_public(decoded_private_key): # 计算公钥坐标 K = k * G public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) # 计算公钥 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') # 计算压缩公钥 # if public_key[1] % 2 == 0: # 两种方式均可 compressed_prefix = '02' if public_key[1] & 1 == 0 else '03' # 转十六也可用 bitcoin_core.encode(xxx, 16) hex_compressed_public_key = compressed_prefix + hex(public_key[0])[2:] return public_key, hex_encoded_public_key, compressed_prefix, hex_compressed_public_key
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 pubkey_to_address(self, pubkey, magicbyte=0, magicbyte_length=1): """ 根据pubkey生成地址 """ if isinstance(pubkey, (list, tuple)): pubkey = bitcoin.encode_pubkey(pubkey, 'bin') if len(pubkey) in [66, 130]: return self.bin_to_b58check(bitcoin.bin_hash160(bitcoin.binascii.unhexlify(pubkey)), magicbyte=magicbyte, magicbyte_length=magicbyte_length) return self.bin_to_b58check(bitcoin.bin_hash160(pubkey), magicbyte=magicbyte, magicbyte_length=magicbyte_length)
def eth_privtoaddr(priv) -> str: """Generate Ethereum address from a private key. God, it was hard to find how this happens. https://github.com/ethereum/pyethsaletool/blob/master/pyethsaletool.py#L111 :return: 0x prefixed hex string """ pub = bitcoin.encode_pubkey(bitcoin.privtopub(priv), 'bin_electrum') return "0x" + binascii.hexlify(sha3(pub)[12:]).decode("ascii")
def getAddressesFromXPUB(xpub, i=10): addressList = [] pub0 = bitcoin.bip32_ckd(xpub, 0) for i in range (0, i): publicKey = bitcoin.bip32_ckd(pub0, i) hexKey = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(publicKey), 'hex_compressed') address_fromPub = bitcoin.pubtoaddr(hexKey) addressList.append(address_fromPub) return addressList
def recover_sender(self): if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28 \ or self.r == 0 or self.s == 0: raise InvalidSignature() rlpdata = rlp.encode(self, self.__class__.exclude(['v', 'r', 's'])) rawhash = sha3(rlpdata) pub = ecdsa_recover_raw(rawhash, (self.v, self.r, self.s)) if pub is False or pub == (0, 0): raise InvalidSignature() pub = encode_pubkey(pub, 'bin') return sha3(pub[1:])[-20:]
def borr_hash(m, pubkey, i, j, is_pubkey=True): '''A Sha256 hash of data in the standard 'borromean' format. Note that 'pubkey' is the value kG as according to kG = sG - eP. i,j : the indices to a specific vertex in the graph. m - the message to be hashed. Returns - the hash. ''' #little hack assuming sizes < 256 p = btc.encode_pubkey(pubkey, 'bin_compressed') if is_pubkey else pubkey x = p + m + '\x00' * 3 + chr(i) + '\x00' * 3 + chr(j) return sha256(x).digest()
def recover_sender(self): if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28 \ or self.r == 0 or self.s == 0: raise InvalidSignature() rlpdata = rlp.encode(self, self.__class__.exclude(['v', 'r', 's'])) rawhash = sha3(rlpdata) pub = ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)) if pub is False or pub == (0, 0): raise InvalidSignature() pub = encode_pubkey(pub, 'bin') return sha3(pub[1:])[-20:]
def borr_hash(m, pubkey, i, j, is_pubkey=True): '''A Sha256 hash of data in the standard 'borromean' format. Note that 'pubkey' is the value kG as according to kG = sG - eP. i,j : the indices to a specific vertex in the graph. m - the message to be hashed. Returns - the hash. ''' #little hack assuming sizes < 256 p = btc.encode_pubkey(pubkey,'bin_compressed') if is_pubkey else pubkey x = p + m +'\x00'*3 + chr(i) + '\x00'*3 + chr(j) return sha256(x).digest()
def get_ethereum_address_from_private_key(private_key_seed_ascii: str) -> str: """Generate Ethereum address from a private key. https://github.com/ethereum/pyethsaletool/blob/master/pyethsaletool.py#L111 :param private_key: Any string as a seed :return: 0x prefixed hex string """ priv = utils.sha3(private_key_seed_ascii) pub = bitcoin.encode_pubkey(bitcoin.privtopub(priv), 'bin_electrum') return "0x" + binascii.hexlify(sha3(pub)[12:]).decode("ascii")
def test_ecrecover(self): priv = b.sha256('some big long brainwallet password') pub = b.privtopub(priv) msghash = b.sha256('the quick brown fox jumps over the lazy dog') V, R, S = b.ecdsa_raw_sign(msghash, priv) assert b.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:] assert utils.privtoaddr(priv) == addr result = self.c.test_ecrecover(utils.big_endian_to_int(msghash.decode('hex')), V, R, S) assert result == utils.big_endian_to_int(addr)
def bip38_decrypt(encrypted_privkey, passphrase, wif=False): """ BIP0038 non-ec-multiply decryption. Returns hex privkey. """ passphrase = normalize('NFC', unicode(passphrase)) if is_py2: passphrase = passphrase.encode('utf8') d = unhexlify(changebase(encrypted_privkey, 58, 16, 86)) d = d[2:] flagbyte = d[0:1] d = d[1:] # respect flagbyte, return correct pair if flagbyte == b'\xc0': compressed = False if flagbyte == b'\xe0': compressed = True addresshash = d[0:4] d = d[4:-4] key = scrypt.hash(passphrase,addresshash, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] encryptedhalf1 = d[0:16] encryptedhalf2 = d[16:32] aes = AES.new(derivedhalf2) decryptedhalf2 = aes.decrypt(encryptedhalf2) decryptedhalf1 = aes.decrypt(encryptedhalf1) priv = decryptedhalf1 + decryptedhalf2 priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16))) pub = privtopub(priv) if compressed: pub = encode_pubkey(pub,'hex_compressed') addr = pubtoaddr(pub) if is_py2: ascii_key = addr else: ascii_key = bytes(addr,'ascii') if sha256(sha256(ascii_key).digest()).digest()[0:4] != addresshash: raise Exception('Bip38 password decrypt failed: Wrong password?') else: formatt = 'wif' if wif else 'hex' if compressed: return encode_privkey(priv, formatt + '_compressed') else: return encode_privkey(priv, formatt)
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 test_raw(): vrs1 = b_ecdsa_raw_sign(msg32, priv) assert isinstance(vrs1, tuple) assert len(vrs1) == 3 vrs3 = c_ecdsa_sign_raw(msg32, priv) p1 = b_ecdsa_raw_recover(msg32, vrs1) p3 = c_ecdsa_recover_raw(msg32, vrs1) p4 = c_ecdsa_recover_raw(msg32, vrs3) p5 = b_ecdsa_raw_recover(msg32, vrs3) # Ensure that recovered pub key is the same assert encode_pubkey(p1, 'bin') == pub assert p3 == pub assert p4 == pub assert encode_pubkey(p5, 'bin') == pub # check wrong pub wrong_vrs = c_ecdsa_sign_raw(msg32, 'x' * 32) p2 = c_ecdsa_recover_raw(msg32, wrong_vrs) assert encode_pubkey(p2, 'bin') != pub # verify p6 = encode_pubkey(p3, 'bin_electrum') assert c_ecdsa_verify_raw(msg32, vrs1, p6) p7 = encode_pubkey(p6, 'bin') assert c_ecdsa_verify_raw(msg32, vrs1, p7) assert c_ecdsa_verify_raw(msg32, vrs1, p3) # check wrong pub sig_vrs2 = c_ecdsa_sign_raw(msg32, 'x' * 32) p2 = c_ecdsa_recover_raw(msg32, sig_vrs2) assert p2 != pub # check wrong sig false_sig_vrs = sig_vrs2 assert not c_ecdsa_verify_raw(msg32, false_sig_vrs, pub)
def sender(self): if not self._sender: # Determine sender if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28: raise InvalidTransaction("Invalid signature values!") log.debug('recovering sender') rlpdata = rlp.encode(self, UnsignedTransaction) rawhash = utils.sha3(rlpdata) pub = encode_pubkey(ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin') self._sender = utils.sha3(pub[1:])[-20:] assert self.sender == self._sender else: self._sender = 0 return self._sender
def test_ecrecover(): s = tester.state() c = s.abi_contract(ecrecover_code) priv = encode_hex(utils.sha3('some big long brainwallet password')) pub = bitcoin.privtopub(priv) msghash = encode_hex(utils.sha3('the quick brown fox jumps over the lazy dog')) V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr result = c.test_ecrecover(utils.big_endian_to_int(decode_hex(msghash)), V, R, S) assert result == addr
def proc_ecrecover(ext, msg): print 'ecrecover proc', msg.gas OP_GAS = 500 gas_cost = OP_GAS if msg.gas < gas_cost: return 0, 0, [] b = [0] * 32 msg.data.extract_copy(b, 0, 0, 32) h = ''.join([chr(x) for x in b]) v = msg.data.extract32(32) r = msg.data.extract32(64) s = msg.data.extract32(96) if r >= bitcoin.N or s >= bitcoin.P or v < 27 or v > 28: return 1, msg.gas - 500, [0] * 32 pub = bitcoin.encode_pubkey(bitcoin.ecdsa_raw_recover(h, (v, r, s)), 'bin') o = [0] * 12 + [ord(x) for x in utils.sha3(pub[1:])[-20:]] return 1, msg.gas - gas_cost, o
def parse(cls, data): if re.match('^[0-9a-fA-F]*$', data): data = data.decode('hex') o = rlp.decode(data) tx = cls(decode_int(o[0]), decode_int(o[1]), decode_int(o[2]), decode_int(o[3]), o[4].encode('hex'), o[5], decode_int(o[6]), decode_int(o[7]), decode_int(o[8])) rawhash = sha3(rlp.encode(tx.serialize(False))) pub = encode_pubkey( ecdsa_raw_recover(rawhash, (tx.v, tx.r, tx.s)), 'bin') tx.sender = sha3(pub[1:])[-20:].encode('hex') return tx
def extract_ecdsa_signer(msg_hash, signature): msg_hash_bytes = decode_hex(msg_hash) if msg_hash.startswith(b'0x') else msg_hash signature_bytes = decode_hex(signature) if signature.startswith(b'0x') else signature pk = PublicKey(flags=ALL_FLAGS) rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) pk.public_key = pk.ecdsa_recover( msg_hash_bytes, pk.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ), raw=True, ) pk_serialized = pk.serialize(compressed=False) address = add_0x_prefix(sha3(encode_pubkey(pk_serialized, 'bin')[1:])[-40:]) return address
def _do_recover_address(self, msg, sig): ''' Given ahex-encoded hash string and a signature string (as returned from sign_data() or eth_sign()) Return a string containing the address that signed it. ''' errmsg = None errcode = EthSigDelegate.SUCCESS addr_str = None try: v,r,s = utils.sig_to_vrs(sig) Q = ecdsa_recover_raw(msg, (v,r,s)) pub = encode_pubkey(Q, 'bin') addr = sha3(pub[1:])[-20:] addr_str = '0x{0}'.format(addr.encode('hex')) except Exception as ex: errcode = EthSigDelegate.OTHER_ERROR errmsg = str(ex) return (addr_str, errcode, errmsg)
def check_signature(req): signature = "0x" + req.sign contract = "0x" + req.contract client = req.client dest = req.dest t = req.t.secs end = req.end.secs if client in dictc: if not (dictc[client] < t.req.secs): return False dictc[client] = t.req.secs msg = contract + client + dest + str(t) + str(end) web3 = Web3(RPCProvider(host="127.0.0.1", port="8545")) web3.config.defaultAccount = '0xa28779d29c49fd57d0fc4130e5ebec07c2c79ef5' abi = '[{"constant":false,"inputs":[],"name":"kill","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"owns","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"type":"function"},{"inputs":[{"name":"_greeting","type":"string"}],"type":"constructor"}]' contracto = web3.eth.contract(abi) inst = contracto.at('0xbc8c629cd7477fd580b8f9e8da49e5aad364b769') if (int(t) > int(rospy.get_rostime().secs)): diff = t - int(rospy.get_rostime().secs) else: diff = int(rospy.get_rostime().secs) - t if (diff > 600): return False print "msg: " + msg + " sign: " + signature + " contract: " + contract hash_msg = utils.sha3(msg).encode('hex') r = long(signature[0:66], 16) s = long('0x' + signature[66:130], 16) v = long('0x' + signature[130:132], 16) if not (v == 27 and v == 28): v += 27 address_from_hash = bitcoin.ecdsa_raw_recover( hash_msg.decode('hex'), (v, r, s)) public_key = bitcoin.encode_pubkey(address_from_hash, 'bin') if ('0x' + utils.sha3(public_key[1:]).encode('hex')[24:64] == inst.owns()): return True else: return False
def sender(self): if not self._sender: # Determine sender if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28 or self.r == 0 or self.s == 0: raise InvalidTransaction("Invalid signature values!") log.debug('recovering sender') rlpdata = rlp.encode(self, UnsignedTransaction) rawhash = utils.sha3(rlpdata) pub = ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)) if pub is False: raise InvalidTransaction("Invalid signature values (x^3+7 is non-residue)") if pub == (0, 0): raise InvalidTransaction("Invalid signature (zero privkey cannot sign)") pub = encode_pubkey(pub, 'bin') self._sender = utils.sha3(pub[1:])[-20:] assert self.sender == self._sender else: self._sender = 0 return self._sender