def _calculate_hash(self, filename, **kwargs): """ Calculates the hash of the file and the hash of the file + metadata (passed in ``kwargs``). Args: filename (str): Name of the file testnet (bool): testnet flag. Defaults to False **kwargs: Additional metadata to be encoded with the file. Only the values are used to compute the hash. Values are ordered using their keys, so that the computation of the hash is consistent. As an example, given:: File('filename', title='piece title', artist='artist') the values ``('artist', 'piece title')`` would be used in that order for the computation of the hash. """ with open(filename, 'rb') as f: file_hash = hashlib.md5(f.read()).hexdigest() if kwargs: data = str( [urepr(kwargs[k]) for k in sorted(kwargs)] + [file_hash]) else: data = file_hash address_piece_with_metadata = str( bin_to_b58check(bin_hash160(data.encode()), magicbyte=self._magicbyte) ) address_piece = str(bin_to_b58check(bin_hash160(file_hash.encode()), magicbyte=self._magicbyte)) return address_piece, address_piece_with_metadata
def test_wif_privkeys_invalid(setup_keys): #first try to create wif privkey from key of wrong length bad_privs = ['\x01\x02'*17] #some silly private key but > 33 bytes #next try to create wif with correct length but wrong compression byte bad_privs.append('\x07'*32 + '\x02') for priv in bad_privs: with pytest.raises(Exception) as e_info: fake_wif = btc.wif_compressed_privkey(binascii.hexlify(priv)) #Create a wif with wrong length bad_wif1 = btc.bin_to_b58check('\x01\x02'*34, 128) #Create a wif with wrong compression byte bad_wif2 = btc.bin_to_b58check('\x07'*33, 128) for bw in [bad_wif1, bad_wif2]: with pytest.raises(Exception) as e_info: fake_priv = btc.from_wif_privkey(bw) #Some invalid b58 from bitcoin repo; #none of these are valid as any kind of key or address with open("test/base58_keys_invalid.json", "r") as f: json_data = f.read() invalid_key_list = json.loads(json_data) for k in invalid_key_list: bad_key = k[0] for netval in ["mainnet", "testnet"]: jm_single().config.set("BLOCKCHAIN", "network", netval) #if using py.test -s ; sanity check to see what's actually being tested print 'testing this key: ' + bad_key if "decode_privkey" in dir(btc): try: bad_key_format = btc.get_privkey_format(bad_key) print 'has correct format: ' + bad_key_format except: pass #should throw exception with pytest.raises(Exception) as e_info: if "decode_privkey" in dir(btc): from_wif_key = btc.decode_privkey(bad_key) else: from_wif_key = btc.from_wif_compressed_privkey( bad_key, btc.get_version_byte(bad_key)) #in case the b58 check encoding is valid, we should #also check if the leading version byte is in the #expected set, and throw an error if not. if chr(btc.get_version_byte(bad_key)) not in '\x80\xef': raise Exception("Invalid version byte") #the bitcoin library should throw #if the compression byte is not there (test not needed #for secp256k1 branch since the wif_compressed function checks) if "decode_privkey" in dir(btc): if "compressed" in btc.get_privkey_format(bad_key) and \ btc.b58check_to_bin(x)[-1] != '\x01': raise Exception("Invalid compression byte")
def test_wif_privkeys_invalid(setup_keys): #first try to create wif privkey from key of wrong length bad_privs = ['\x01\x02' * 17] #some silly private key but > 33 bytes #next try to create wif with correct length but wrong compression byte bad_privs.append('\x07' * 32 + '\x02') for priv in bad_privs: with pytest.raises(Exception) as e_info: fake_wif = btc.wif_compressed_privkey(binascii.hexlify(priv)) #Create a wif with wrong length bad_wif1 = btc.bin_to_b58check('\x01\x02' * 34, 128) #Create a wif with wrong compression byte bad_wif2 = btc.bin_to_b58check('\x07' * 33, 128) for bw in [bad_wif1, bad_wif2]: with pytest.raises(Exception) as e_info: fake_priv = btc.from_wif_privkey(bw) #Some invalid b58 from bitcoin repo; #none of these are valid as any kind of key or address with open("test/base58_keys_invalid.json", "r") as f: json_data = f.read() invalid_key_list = json.loads(json_data) for k in invalid_key_list: bad_key = k[0] for netval in ["mainnet", "testnet"]: jm_single().config.set("BLOCKCHAIN", "network", netval) #if using py.test -s ; sanity check to see what's actually being tested print 'testing this key: ' + bad_key if "decode_privkey" in dir(btc): try: bad_key_format = btc.get_privkey_format(bad_key) print 'has correct format: ' + bad_key_format except: pass #should throw exception with pytest.raises(Exception) as e_info: if "decode_privkey" in dir(btc): from_wif_key = btc.decode_privkey(bad_key) else: from_wif_key = btc.from_wif_compressed_privkey( bad_key, btc.get_version_byte(bad_key)) #in case the b58 check encoding is valid, we should #also check if the leading version byte is in the #expected set, and throw an error if not. if chr(btc.get_version_byte(bad_key)) not in '\x80\xef': raise Exception("Invalid version byte") #the bitcoin library should throw #if the compression byte is not there (test not needed #for secp256k1 branch since the wif_compressed function checks) if "decode_privkey" in dir(btc): if "compressed" in btc.get_privkey_format(bad_key) and \ btc.b58check_to_bin(x)[-1] != '\x01': raise Exception("Invalid compression byte")
def pubkey_to_address(pubKey: str, magic_byte = 0) -> str: pubKeyBytes = binascii.unhexlify(pubKey) sha256val = hashlib.sha256(pubKeyBytes).digest() ripemd160val = hashlib.new('ripemd160', sha256val).digest() print (binascii.hexlify(sha256val)) print (binascii.hexlify(ripemd160val)) print (magic_byte) return bitcoin.bin_to_b58check(ripemd160val, magic_byte)
def script_to_address(script, vbyte=0): ''' Like script_to_address but supports altcoins Copied 2015-10-02 from https://github.com/mflaxman/pybitcointools/blob/faf56c53148989ea390238c3c4541a6ae1d601f5/bitcoin/transaction.py#L224-L236 ''' if re.match('^[0-9a-fA-F]*$', script): script = binascii.unhexlify(script) if script[:3] == b'\x76\xa9\x14' and script[-2:] == b'\x88\xac' and len(script) == 25: return bin_to_b58check(script[3:-2], vbyte) # pubkey hash addresses else: if vbyte in [111, 196]: # Testnet scripthash_byte = 196 else: scripthash_byte = vbyte # BIP0016 scripthash addresses return bin_to_b58check(script[2:-1], scripthash_byte)
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 get_keys(mnemonic, email, password): salt = unicodedata.normalize( "NFKD", (email + password).decode("utf8")).encode("utf8") seed = bitcoin.mnemonic_to_seed(mnemonic, salt) pk, sk = pysodium.crypto_sign_seed_keypair(seed[0:32]) pkh = blake2b(pk, 20).digest() pkhb58 = bitcoin.bin_to_b58check(pkh, magicbyte=434591) return (sk, pk, pkh, pkhb58)
def _calculate_hash(self, filename, **kwargs): """ Calculates the hash of the file and the hash of the file + metadata (passed on the keywargs) """ # hash to address with open(filename, 'rb') as f: file_hash = hashlib.md5(f.read()).hexdigest() if kwargs: data = str([unicode(value) for value in kwargs.itervalues()] + [file_hash]) else: data = file_hash address_piece_with_metadata = unicode(bitcoin.bin_to_b58check(bitcoin.bin_hash160(data), magicbyte=self._magicbyte)) address_piece = unicode(bitcoin.bin_to_b58check(bitcoin.bin_hash160(file_hash), magicbyte=self._magicbyte)) return address_piece, address_piece_with_metadata
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 script_to_address(script, vbyte=0): ''' Like script_to_address but supports altcoins Copied 2015-10-02 from https://github.com/mflaxman/pybitcointools/blob/faf56c53148989ea390238c3c4541a6ae1d601f5/bitcoin/transaction.py#L224-L236 ''' if re.match('^[0-9a-fA-F]*$', script): script = binascii.unhexlify(script) if script[:3] == b'\x76\xa9\x14' and script[-2:] == b'\x88\xac' and len( script) == 25: return bin_to_b58check(script[3:-2], vbyte) # pubkey hash addresses else: if vbyte in [111, 196]: # Testnet scripthash_byte = 196 else: scripthash_byte = vbyte # BIP0016 scripthash addresses return bin_to_b58check(script[2:-1], scripthash_byte)
def genesis_commitments(wallets, blind): commitments = [] for pkh_b58, amount in wallets.iteritems(): # Public key hash corresponding to this Tezos address. pkh = bitcoin.b58check_to_bin(pkh_b58)[2:] hpkh_b58 = bitcoin.bin_to_b58check((pkh[:10] + '\000' * 10), magicbyte=434591) # The redemption code is unique to the public key hash and deterministically # constructed using a secret blinding value. secret = secret_code(pkh, blind) # The redemption code is used to blind the pkh blinded_pkh = blake2b(pkh, 20, key=secret).digest() commitment = { 'half_pkh': hpkh_b58, 'blinded_pkh': bitcoin.bin_to_b58check(blinded_pkh, magicbyte=16921055), 'amount': amount } commitments.append(commitment) return commitments
def make_dummy_wallets(n, blind): # Not a realistic shape, but for an alphanet faucet it's better to # have less variance. amounts = np.random.pareto(10.0, n) amounts = amounts / sum(amounts) * 760e6 wallets = {} secret_seeds = {} for i in range(0, n): seed = blake2b(str(i), 32, key=blind).digest() pk, sk = pysodium.crypto_sign_seed_keypair(seed) pkh = blake2b(pk, 20).digest() pkh_b58 = bitcoin.bin_to_b58check(pkh, magicbyte=434591) amount = tez_to_int(amounts[i]) wallets[pkh_b58] = amount secret = secret_code(pkh, blind) secret_seeds[pkh_b58] = (bitcoin.bin_to_b58check(seed, magicbyte=219101703), amount, binascii.hexlify(secret)) return wallets, secret_seeds
def create_pair(b58_magic_byte, address_magic_byte, seed=None): """Function create private key and address""" if seed is None: seed = KeyGenerator.random_seed() hash = sha256(seed) private_key = int(hash, base=16) private_key_wif = bin_to_b58check(encode(private_key, 256, 32), b58_magic_byte) address = privkey_to_address(private_key, address_magic_byte) return private_key_wif, address
def gen_address_for_data(data): print("Hashing data: " + str(data)) # https://gist.github.com/patricklodder/b27fb3e91c0566272976#file-gistfile1-py-L390 # RIPEMD160(SHA256(data)) fingerprint = bin_hash160(data.encode()) print("Data fingerprint: " + str(fingerprint.encode('hex'))) address = str(bin_to_b58check(fingerprint), magicbyte=_magicbyte) print("Final address: " + str(address)) return address
def gen_address_for_data(data): print("Hashing data: "+str(data)) # https://gist.github.com/patricklodder/b27fb3e91c0566272976#file-gistfile1-py-L390 # RIPEMD160(SHA256(data)) fingerprint = bin_hash160(data.encode()) print("Data fingerprint: "+str(fingerprint.encode('hex'))) address = str(bin_to_b58check(fingerprint), magicbyte=_magicbyte) print("Final address: "+str(address)) return address
def __init__(self, hexdata): if not all(c in string.hexdigits for c in hexdata): raise('Invalid signature request: not all hex digits') self.payload = hexdata data = bytes.fromhex(hexdata) self.chainid = bitcoin.bin_to_b58check(data[1:5], magicbyte=CHAIN_ID) if data[0] == 0x01: # Emmy block self.type = "Baking" self.level = get_be_int(data[5:]) self.round = 0 elif data[0] == 0x02: # Emmy endorsement self.type = "Endorsement" self.level = get_be_int(data[-4:]) self.round = 0 elif data[0] == 0x11: # Tenderbake block self.type = "Baking" self.level = get_be_int(data[5:]) fitness_sz = get_be_int(data[83:]) offset = 87 + fitness_sz - 4 self.round = get_be_int(data[offset:]) elif data[0] == 0x12: # Tenderbake preendorsement self.type = "Preendorsement" self.level = get_be_int(data[40:]) self.round = get_be_int(data[44:]) elif data[0] == 0x13: # Tenderbake endorsement self.type = "Endorsement" self.level = get_be_int(data[40:]) self.round = get_be_int(data[44:]) else: self.type = "Unknown operation" self.logstr = f"{self.chainid} {self.type}" if self.level != None: self.logstr += f" at {self.level}/{self.round}"
def check(password, email, mnemonic, address, iters=2048): salt = unicodedata.normalize("NFKD", (email + password)).encode("utf8") seed = pbkdf2_hmac(hash_name='sha512', password=mnemonic, salt=b"mnemonic" + salt, iterations=iters) pk, sk = pysodium.crypto_sign_seed_keypair(seed[0:32]) pkh = blake2b(pk, 20).digest() decrypted_address = bitcoin.bin_to_b58check(pkh, magicbyte=434591) if address == decrypted_address: found_it = "True" print("found it ") print("Your password is: ", password) with open("password.lst", 'a') as z: z.write((password) + '\n') z.close() else: found_it = "False" return (found_it, password)
import unicodedata import sys import bitcoin import pysodium from pyblake2 import blake2b from hashlib import sha256 import binascii if __name__ == '__main__': mnemonic = ' '.join( bitcoin.mnemonic.entropy_to_words(pysodium.randombytes(32))) seed = bitcoin.mnemonic_to_seed(mnemonic)[:32] pk, sk = pysodium.crypto_sign_seed_keypair(seed) pkh = bitcoin.bin_to_b58check(blake2b(pk, 20).digest(), magicbyte=434591) secret_key = bitcoin.bin_to_b58check(seed, magicbyte=219101703) print "mnemonic: %s" % mnemonic print "secret seed: %s" % secret_key print "public key hash: %s" % pkh
def tezos_pkh(digest): return bitcoin.bin_to_b58check(digest, magicbyte=434591)
password = sys.argv[17] salt = unicodedata.normalize( "NFKD", (email + password).decode("utf8")).encode("utf8") try: seed = bitcoin.mnemonic_to_seed(mnemonic, salt) except: print("Invalid mnemonic") exit(1) pk, sk = pysodium.crypto_sign_seed_keypair(seed[0:32]) pkh = blake2b(pk, 20).digest() print "public key hash: ", tezos_pkh(pkh) elif len(sys.argv) == 2: tz_input = sys.argv[1] assert (tz_input == bitcoin.bin_to_b58check( bitcoin.b58check_to_bin(tz_input)[2:], magicbyte=434591)) try: pkh = bitcoin.b58check_to_bin(tz_input)[2:] except: print "Invalid public key hash" else: print("""Usage: python keychecker.py garage absurd steak ... email password or python keychecker.py tz1YoUrPuBlicKeYhaSh""") exit(1) print "Ethereum data: ", ethereum_data(pkh) print "Bitcoin address: ", bitcoin_address(pkh)
def tezos_pkh(pkh): return bitcoin.bin_to_b58check(pkh.digest(), magicbyte=434591)
def asciidec(val): word = [] while val > 0: word.append(val % 256) val /= 256 return word[-1::-1] if __name__ == '__main__': prefix = sys.argv[1] length = int(sys.argv[2]) target = b58dec(prefix) shift = 8 * (length + 4) for m in range(1, 1000): lo = target * 58**m lo = (lo >> shift) + (0 if lo == ((lo >> shift) << shift) else 1) hi = (target + 1) * 58**m - (1 << shift) + 1 hi = hi >> shift if hi >= lo: # test for bt in '\x00\xff': s = bitcoin.bin_to_b58check(bt * length, magicbyte=lo) assert s.startswith(prefix) assert len(s) == m + len(prefix) print m + len(prefix), lo, asciidec(lo) exit(0)
def b58encode_signature(sig): return bitcoin.bin_to_b58check(sig, magicbyte=RemoteSigner.P256_SIGNATURE)
def public_key_to_address(publicKey: str, magic_byte=0) -> str: publicKeyBytes = binascii.unhexlify(publicKey) sha256hash = hashlib.sha256(publicKeyBytes).digest() ripemd160hash = hashlib.new('ripemd160', sha256hash).digest() return bitcoin.bin_to_b58check(ripemd160hash, magic_byte)
def get_chain_id(self): chainid = bytes.fromhex(self.payload[2:10]) return bitcoin.bin_to_b58check(chainid, magicbyte=RemoteSigner.CHAIN_ID)
import bitcoin from src.sigreq import SignatureReq from src.validatesigner import ValidateSigner from src.signer import Signer from src.chainratchet import MockChainRatchet def eatwhite(str): return re.sub(r"\s+", "", str) # results in p2sig prefix when encoded with base58 (p2sig(98)): P256_SIG= struct.unpack('>L', b'\x36\xF0\x2C\x34')[0] RAW_SIGNED_BLOCK = b'0123456789012345678901' SIGNED_BLOCK = bitcoin.bin_to_b58check(RAW_SIGNED_BLOCK, magicbyte=P256_SIG) # # Here's a quick invalid block that we'll make sure that we don't process: INVALID_PREAMBLE = eatwhite(""" 030000000000000002012c866bd675ad11475ea608dea4d9d166801f1725b2076363 63d55508aa07ba6f000000005b17b90d04683625c2445a4e9564bf710c5528fd99a7 d150d2a2a323bc22ff9e2710da4f6d00000011000000010000000008000000000000 000289b5a4e5e20c56512c64967dfa72e67c39166d5c48ad6884693c7d192e105c3b 00058f7b73557941607800""") # # Here we provide a list of valid blocks over which we shall iterate: # They are each a tuple of the expected results: # (type, chainid, level, round)
def load_wallet(wallet_file, get_password_fn): """load and if necessary decrypt a bitcoinj wallet file :param wallet_file: an open bitcoinj wallet file :type wallet_file: file :param get_password_fn: a callback returning a password that's called iff one is required :type get_password_fn: function :return: the Wallet protobuf message or None if no password was entered when required :rtype: wallet_pb2.Wallet """ wallet_file.seek(0) magic_bytes = wallet_file.read(12) wallet_file.seek(0, os.SEEK_END) wallet_size = wallet_file.tell() wallet_file.seek(0) if magic_bytes[2:6] != b"org." and wallet_size % 16 == 0: import pylibscrypt takes_long = not pylibscrypt._done # if a binary library wasn't found, this'll take a while ciphertext = wallet_file.read() assert len(ciphertext) % 16 == 0 password = get_password_fn(takes_long) if not password: return None # Derive the encryption key salt = '\x35\x51\x03\x80\x75\xa3\xb0\xc5' key = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32) # Decrypt the wallet ( v0.5.0+ ) try: plaintext = aes256_cbc_decrypt(ciphertext[16:], key, ciphertext[:16]) if plaintext[2:6] != b"org.": raise ValueError('incorrect password') except ValueError as e: if e.args[0] == 'incorrect password': # Decrypt the wallet ( < v0.5.0 ) iv = '\xa3\x44\x39\x1f\x53\x83\x11\xb3\x29\x54\x86\x16\xc4\x89\x72\x3e' plaintext = aes256_cbc_decrypt(ciphertext, key, iv) global multibit_hd_password multibit_hd_password = password # Else it's not whole-file encrypted else: password = None plaintext = wallet_file.read() # Parse the wallet protobuf pb_wallet = wallet_pb2.Wallet() try: pb_wallet.ParseFromString(plaintext) except Exception as e: msg = 'not a wallet file: ' + str(e) if password: msg = "incorrect password (or " + msg + ")" raise ValueError(msg) f = open('parsed_wallet.txt','w') f.write(pb_wallet.__str__()) f.close() foundAddr = [] for trans in pb_wallet.transaction: if trans.pool == 4: print("--------------------------------------------------------------------------------") print("TXID: " + binascii.hexlify(trans.hash)) for out in trans.transaction_output: print("") faddr = bitcoin.bin_to_b58check(bitcoin.deserialize_script(out.script_bytes)[2]) print("Addr: " + faddr) foundAddr.append(faddr) print("Amt: " + str(out.value * 0.00000001) + " BTC") print("") print("--------------------------------------------------------------------------------") seed = None sys.stdout.write('Finding Seed....') salt = pb_wallet.encryption_parameters.salt dkey = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32) for wkey in pb_wallet.key: if wkey.type == 3: seed = aes256_cbc_decrypt(wkey.encrypted_deterministic_seed.encrypted_private_key, dkey, wkey.encrypted_deterministic_seed.initialisation_vector) break if not seed: print("No DETERMINISTIC_MNEMONIC seed found!") return None else: print("Done!") xprv = bitcoin.bip32_master_key(seed) xprvReceive = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),0) #m/0'/0 xprvChange = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),1) #m/0'/1 rcvAddr = [] chgAddr = [] rcvPrivKey = [] chgPrivKey = [] sys.stdout.write("Generating Addresses/Keys.") for x in range(0,1000): if x % 10 == 0: sys.stdout.write(".") childprivReceive = bitcoin.bip32_ckd(xprvReceive, x) childprivChange = bitcoin.bip32_ckd(xprvChange, x) pkeyReceive = bitcoin.bip32_extract_key(childprivReceive) pkeyChange = bitcoin.bip32_extract_key(childprivChange) #addressReceive = privtoaddr(pkeyReceive) #addressChange = privtoaddr(pkeyChange) rcvAddr.append(bitcoin.privtoaddr(pkeyReceive)) chgAddr.append(bitcoin.privtoaddr(pkeyChange)) rcvPrivKey.append(bitcoin.encode_privkey(pkeyReceive, 'wif_compressed')) chgPrivKey.append(bitcoin.encode_privkey(pkeyChange, 'wif_compressed')) print("Done!") print("--------------------------------------------------------------------------------") for addy in foundAddr: if addy in rcvAddr: print("") print("Found Address: " + addy) print("PrivateKey: " + rcvPrivKey[rcvAddr.index(addy)]) elif addy in chgAddr: print("") print("Found Change Address: " + addy) print("PrivateKey: " + chgPrivKey[chgAddr.index(addy)]) else: print("") print("Address not found: " + addy) print("") print("--------------------------------------------------------------------------------") return pb_wallet
def b58encode_signature(sig, magicbyte): return bitcoin.bin_to_b58check(sig, magicbyte=magicbyte)