def decodeWalletImportFormat(WIFstring): # pylint: disable=inconsistent-return-statements """ Convert private key from base58 that's used in the config file to 8-bit binary string """ fullString = arithmetic.changebase(WIFstring, 58, 256) privkey = fullString[:-4] if fullString[-4:] != \ hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]: logger.critical( 'Major problem! When trying to decode one of your' ' private keys, the checksum failed. Here are the first' ' 6 characters of the PRIVATE key: %s', str(WIFstring)[:6]) os._exit(0) # pylint: disable=protected-access # return "" elif privkey[0] == '\x80': # checksum passed return privkey[1:] logger.critical( 'Major problem! When trying to decode one of your private keys,' ' the checksum passed but the key doesn\'t begin with hex 80.' ' Here is the PRIVATE key: %s', WIFstring) os._exit(0) # pylint: disable=protected-access
def makeCryptor(privkey): private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20' + private_key pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-32:] cryptor = pyelliptic.ECC(curve='secp256k1',privkey=privkey_bin,pubkey=pubkey_bin) return cryptor
def get_address(seed): h = hashlib.new('SHA256') h.update(seed) privateExponent = h.digest().encode('hex') print 'Private exponent: ', privateExponent print 'Wallet import format: ', private_exponent_to_WIF(privateExponent) # 0 Private ECDSA Key - 256 bits # print 'Now let us convert them to public keys by doing an elliptic curve point multiplication.' # 1 Public publicEncryptionKey = arithmetic.privtopub(privateExponent) # print 'publicEncryptionKey =', publicEncryptionKey publicEncryptionKeyBinary = arithmetic.changebase(publicEncryptionKey, 16, 256, minlen=64) ripe = hashlib.new('ripemd160') sha = hashlib.new('SHA256') # 2 Sha-256 of 1 sha.update(publicEncryptionKeyBinary) # print 'Sha-256: ', sha.digest().encode('hex') # 3 RIPEMD of 2 ripe.update(sha.digest()) # 4 add network bytes network_bytes = 00 # print 'Ripe digest that we will encode in the address:', # ripe.digest().encode('hex') returnedAddress = encodeAddress(network_bytes, ripe.digest()) print 'Encoded BTC address:', returnedAddress # Checksum does not validate return returnedAddress
def calculateBitcoinAddressFromPubkey(pubkey): if len(pubkey) != 65: print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') sha.update(pubkey) ripe.update(sha.digest()) ripeWithProdnetPrefix = '\x00' + ripe.digest() checksum = hashlib.sha256(hashlib.sha256( ripeWithProdnetPrefix).digest()).digest()[:4] binaryBitcoinAddress = ripeWithProdnetPrefix + checksum numberOfZeroBytesOnBinaryBitcoinAddress = 0 while binaryBitcoinAddress[0] == '\x00': numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def decodeWalletImportFormat(WIFstring): fullString = arithmetic.changebase(WIFstring, 58, 256) privkey = fullString[:-4] if fullString[-4:] != \ hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]: logger.critical( 'Major problem! When trying to decode one of your' ' private keys, the checksum failed. Here are the first' ' 6 characters of the PRIVATE key: %s', str(WIFstring)[:6]) os._exit(0) # return "" elif privkey[0] == '\x80': # checksum passed return privkey[1:] logger.critical( 'Major problem! When trying to decode one of your private keys,' ' the checksum passed but the key doesn\'t begin with hex 80.' ' Here is the PRIVATE key: %s', WIFstring) os._exit(0)
def calculateBitcoinAddressFromPubkey(pubkey): if len(pubkey) != 65: print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len( pubkey), 'bytes long rather than 65.' return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') sha.update(pubkey) ripe.update(sha.digest()) ripeWithProdnetPrefix = '\x00' + ripe.digest() checksum = hashlib.sha256( hashlib.sha256(ripeWithProdnetPrefix).digest()).digest()[:4] binaryBitcoinAddress = ripeWithProdnetPrefix + checksum numberOfZeroBytesOnBinaryBitcoinAddress = 0 while binaryBitcoinAddress[0] == '\x00': numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def getAddress(self, testnet, content): """ Compute (deterministically) a Bitcoin address from the provided content. Set the testnet boolean to True to compute a testnet address """ ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') sha.update(content) ripe.update(sha.digest()) netPrefix = '\x6F' if testnet else '\x00' ripeWithPrefix = "%s%s" % (netPrefix, ripe.digest()) checksum = hashlib.sha256( hashlib.sha256(ripeWithPrefix).digest()).digest()[:4] binaryBitcoinAddress = ripeWithPrefix + checksum numberOfZeroBytesOnBinaryBitcoinAddress = 0 while binaryBitcoinAddress[0] == '\x00': numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def getAddress(self, testnet, content): """ Compute (deterministically) a Bitcoin address from the provided content. Set the testnet boolean to True to compute a testnet address """ ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') sha.update(content) ripe.update(sha.digest()) netPrefix = '\x6F' if testnet else '\x00' ripeWithPrefix = "%s%s" % ( netPrefix, ripe.digest() ) checksum = hashlib.sha256(hashlib.sha256( ripeWithPrefix).digest()).digest()[:4] binaryBitcoinAddress = ripeWithPrefix + checksum numberOfZeroBytesOnBinaryBitcoinAddress = 0 while binaryBitcoinAddress[0] == '\x00': numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def calculateTestnetAddressFromPubkey(pubkey): """This function expects that pubkey begin with the testnet prefix""" if len(pubkey) != 65: logger.error( 'Could not calculate Bitcoin address from pubkey because' ' function was passed a pubkey that was' ' %i bytes long rather than 65.', len(pubkey)) return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') sha.update(pubkey) ripe.update(sha.digest()) ripeWithProdnetPrefix = '\x6F' + ripe.digest() checksum = hashlib.sha256( hashlib.sha256(ripeWithProdnetPrefix).digest()).digest()[:4] binaryBitcoinAddress = ripeWithProdnetPrefix + checksum numberOfZeroBytesOnBinaryBitcoinAddress = 0 while binaryBitcoinAddress[0] == '\x00': numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def privToPub(privkey): """Converts hex private key into hex public key""" private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) return hexlify(public_key)
def hexToPubkey(pubkey): """Convert a pubkey from hex to binary""" pubkey_raw = a.changebase(pubkey[2:], 16, 256, minlen=64) pubkey_bin = '\x02\xca\x00 ' + pubkey_raw[:32] + '\x00 ' + pubkey_raw[32:] return pubkey_bin
if __name__ == "__main__": print 'Let us make an address from scratch. Suppose we generate two random 32 byte values and call the first one the signing key and the second one the encryption key:' privateSigningKey = '93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665' privateEncryptionKey = '4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a' print 'privateSigningKey =', privateSigningKey print 'privateEncryptionKey =', privateEncryptionKey print 'Now let us convert them to public keys by doing an elliptic curve point multiplication.' publicSigningKey = arithmetic.privtopub(privateSigningKey) publicEncryptionKey = arithmetic.privtopub(privateEncryptionKey) print 'publicSigningKey =', publicSigningKey print 'publicEncryptionKey =', publicEncryptionKey print 'Notice that they both begin with the \\x04 which specifies the encoding type. This prefix is not send over the wire. You must strip if off before you send your public key across the wire, and you must add it back when you receive a public key.' publicSigningKeyBinary = arithmetic.changebase(publicSigningKey,16,256,minlen=64) publicEncryptionKeyBinary = arithmetic.changebase(publicEncryptionKey,16,256,minlen=64) ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update(publicSigningKeyBinary+publicEncryptionKeyBinary) ripe.update(sha.digest()) addressVersionNumber = 2 streamNumber = 1 print 'Ripe digest that we will encode in the address:', ripe.digest().encode('hex') returnedAddress = encodeAddress(addressVersionNumber,streamNumber,ripe.digest()) print 'Encoded address:', returnedAddress status,addressVersionNumber,streamNumber,data = decodeAddress(returnedAddress) print '\nAfter decoding address:' print 'Status:', status
def hexToPubkey(pubkey): pubkey_raw = a.changebase(pubkey[2:],16,256,minlen=64) pubkey_bin = '\x02\xca\x00 '+pubkey_raw[:32]+'\x00 '+pubkey_raw[32:] return pubkey_bin
def makeCryptor(privkey): privkey_bin = '\x02\xca\x00 '+a.changebase(privkey,16,256,minlen=32) pubkey = a.changebase(a.privtopub(privkey),16,256,minlen=65)[1:] pubkey_bin = '\x02\xca\x00 '+pubkey[:32]+'\x00 '+pubkey[32:] cryptor = pyelliptic.ECC(curve='secp256k1',privkey=privkey_bin,pubkey=pubkey_bin) return cryptor
def thread_main(): global found_one prefix = args[0] deterministicNonce = 0 startTime = time.time() while found_one != True: #We generate addresses based off of a secure random string plus an integer nonce. deterministicNall = base64.b64encode(os.urandom(options.bytes)) address = "" while found_one != True: #This next section is a little bit strange. We're going to generate keys over and over until we #find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them #into a Bitmessage address, we won't store the \x00 or \x00\x00 bytes thus making the address shorter. signingKeyNonce = 0 encryptionKeyNonce = 1 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 deterministicPassphrase = deterministicNall + str( deterministicNonce) while found_one != True: #find a keypair pair whose hash starts with \x00 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] potentialPubSigningKey = pointMult(potentialPrivSigningKey) potentialPubEncryptionKey = pointMult( potentialPrivEncryptionKey) signingKeyNonce += 2 encryptionKeyNonce += 2 ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update(potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) #print 'potential ripe.digest', ripe.digest().encode('hex') if options.eighteenByteRipe: if ripe.digest()[:2] == '\x00\x00': break else: if ripe.digest()[:1] == '\x00': break address = encodeAddress(4, options.streamNumber, ripe.digest()) privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256( hashlib.sha256(privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + potentialPrivEncryptionKey checksum = hashlib.sha256( hashlib.sha256(privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) deterministicNonce += 1 if options.insensitive: if (address[:len(prefix)].lower() == prefix.lower()): print "[" + address + "]" print "privsigningkey = " + privSigningKeyWIF print "privencryptionkey = " + privEncryptionKeyWIF found_one = True if not options.quiet: print "Generated " + str( deterministicNonce) + " addresses in " + str( time.time() - startTime) + " seconds." break else: if (address[:len(prefix)] == prefix): print "[" + address + "]" print "privsigningkey = " + privSigningKeyWIF print "privencryptionkey = " + privEncryptionKeyWIF found_one = True if not options.quiet: print "Generated " + str( deterministicNonce) + " addresses in " + str( time.time() - startTime) + " seconds." break if not options.keep: break
else: try: privkey = Key.from_text(secret) except encoding.EncodingError: pass # Define vars automatically from privkey (could be manually, if you had the values) privkey_uncompressed = '%x' % privkey.secret_exponent() pubkey_uncompressed = hexlify(privkey.sec(use_uncompressed=True)) ## # Prepare pubkey for encrypting ## pubkey_bin_tmp = arithmetic.changebase(pubkey_uncompressed[2:], 16, 256, minlen=64) pubkey_bin = '\x02\xca\x00 ' + pubkey_bin_tmp[:32] + '\x00 ' + pubkey_bin_tmp[ 32:] # Optionally you can use unhexlify, but need to add '\x20' after '\x00' #pubkey_bin_tmp = unhexlify(pubkey_uncompressed) #pubkey_bin = '\x02\xca\x00\x20' + pubkey_bin_tmp[1:-32] + '\x00\x20' + pubkey_bin_tmp[-32:] ## # Prepare private key for decrypting ## # Private Key to Bin privkey_bin = '\x02\xca\x00\x20' + arithmetic.changebase( privkey_uncompressed, 16, 256, minlen=32)
def privToPub(privkey): private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) return hexlify(public_key)
def run(self): while state.shutdown == 0: queueValue = queues.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 live = True if queueValue[0] == 'createChan': command, addressVersionNumber, streamNumber, label, \ deterministicPassphrase, live = queueValue eighteenByteRipe = False numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif queueValue[0] == 'joinChan': command, chanAddress, label, deterministicPassphrase, \ live = queueValue eighteenByteRipe = False addressVersionNumber = decodeAddress(chanAddress)[1] streamNumber = decodeAddress(chanAddress)[2] numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif len(queueValue) == 7: command, addressVersionNumber, streamNumber, label, \ numberOfAddressesToMake, deterministicPassphrase, \ eighteenByteRipe = queueValue try: numberOfNullBytesDemandedOnFrontOfRipeHash = \ BMConfigParser().getint( 'bitmessagesettings', 'numberofnullbytesonaddress' ) except: if eighteenByteRipe: numberOfNullBytesDemandedOnFrontOfRipeHash = 2 else: # the default numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif len(queueValue) == 9: command, addressVersionNumber, streamNumber, label, \ numberOfAddressesToMake, deterministicPassphrase, \ eighteenByteRipe, nonceTrialsPerByte, \ payloadLengthExtraBytes = queueValue try: numberOfNullBytesDemandedOnFrontOfRipeHash = \ BMConfigParser().getint( 'bitmessagesettings', 'numberofnullbytesonaddress' ) except: if eighteenByteRipe: numberOfNullBytesDemandedOnFrontOfRipeHash = 2 else: # the default numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif queueValue[0] == 'stopThread': break else: logger.error( 'Programming error: A structure with the wrong number' ' of values was passed into the addressGeneratorQueue.' ' Here is the queueValue: %r\n', queueValue) if addressVersionNumber < 3 or addressVersionNumber > 4: logger.error( 'Program error: For some reason the address generator' ' queue has been given a request to create at least' ' one version %s address which it cannot do.\n', addressVersionNumber) if nonceTrialsPerByte == 0: nonceTrialsPerByte = BMConfigParser().getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') if nonceTrialsPerByte < \ defaults.networkDefaultProofOfWorkNonceTrialsPerByte: nonceTrialsPerByte = \ defaults.networkDefaultProofOfWorkNonceTrialsPerByte if payloadLengthExtraBytes == 0: payloadLengthExtraBytes = BMConfigParser().getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') if payloadLengthExtraBytes < \ defaults.networkDefaultPayloadLengthExtraBytes: payloadLengthExtraBytes = \ defaults.networkDefaultPayloadLengthExtraBytes if command == 'createRandomAddress': queues.UISignalQueue.put( ('updateStatusBar', tr._translate("MainWindow", "Generating one new address"))) # This next section is a little bit strange. We're going # to generate keys over and over until we find one # that starts with either \x00 or \x00\x00. Then when # we pack them into a Bitmessage address, we won't store # the \x00 or \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) sha = hashlib.new('sha512') sha.update(potentialPubSigningKey + potentialPubEncryptionKey) ripe = RIPEMD160Hash(sha.digest()).digest() if (ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash): break logger.info('Generated address with ripe digest: %s', hexlify(ripe)) try: logger.info( 'Address generator calculated %s addresses at %s' ' addresses per second before finding one with' ' the correct ripe-prefix.', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime)) except ZeroDivisionError: # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe) # An excellent way for us to store our keys # is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256( hashlib.sha256(privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + potentialPrivEncryptionKey checksum = hashlib.sha256( hashlib.sha256(privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) BMConfigParser().add_section(address) BMConfigParser().set(address, 'label', label) BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'decoy', 'false') BMConfigParser().set(address, 'noncetrialsperbyte', str(nonceTrialsPerByte)) BMConfigParser().set(address, 'payloadlengthextrabytes', str(payloadLengthExtraBytes)) BMConfigParser().set(address, 'privsigningkey', privSigningKeyWIF) BMConfigParser().set(address, 'privencryptionkey', privEncryptionKeyWIF) BMConfigParser().save() # The API and the join and create Chan functionality # both need information back from the address generator. queues.apiAddressGeneratorReturnQueue.put(address) queues.UISignalQueue.put( ('updateStatusBar', tr._translate( "MainWindow", "Done generating address. Doing work necessary" " to broadcast it..."))) queues.UISignalQueue.put( ('writeNewAddressToTable', (label, address, streamNumber))) shared.reloadMyAddressHashes() if addressVersionNumber == 3: queues.workerQueue.put(('sendOutOrStoreMyV3Pubkey', ripe)) elif addressVersionNumber == 4: queues.workerQueue.put( ('sendOutOrStoreMyV4Pubkey', address)) elif command == 'createDeterministicAddresses' \ or command == 'getDeterministicAddress' \ or command == 'createChan' or command == 'joinChan': if len(deterministicPassphrase) == 0: logger.warning( 'You are creating deterministic' ' address(es) using a blank passphrase.' ' Bitmessage will do it but it is rather stupid.') if command == 'createDeterministicAddresses': queues.UISignalQueue.put( ('updateStatusBar', tr._translate("MainWindow", "Generating %1 new addresses.").arg( str(numberOfAddressesToMake)))) signingKeyNonce = 0 encryptionKeyNonce = 1 # We fill out this list no matter what although we only # need it if we end up passing the info to the API. listOfNewAddressesToSendOutThroughTheAPI = [] for _ in range(numberOfAddressesToMake): # This next section is a little bit strange. We're # going to generate keys over and over until we find # one that has a RIPEMD hash that starts with either # \x00 or \x00\x00. Then when we pack them into a # Bitmessage address, we won't store the \x00 or # \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) signingKeyNonce += 2 encryptionKeyNonce += 2 sha = hashlib.new('sha512') sha.update(potentialPubSigningKey + potentialPubEncryptionKey) ripe = RIPEMD160Hash(sha.digest()).digest() if (ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash): break logger.info('Generated address with ripe digest: %s', hexlify(ripe)) try: logger.info( 'Address generator calculated %s addresses' ' at %s addresses per second before finding' ' one with the correct ripe-prefix.', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime)) except ZeroDivisionError: # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe) saveAddressToDisk = True # If we are joining an existing chan, let us check # to make sure it matches the provided Bitmessage address if command == 'joinChan': if address != chanAddress: listOfNewAddressesToSendOutThroughTheAPI.append( 'chan name does not match address') saveAddressToDisk = False if command == 'getDeterministicAddress': saveAddressToDisk = False if saveAddressToDisk and live: # An excellent way for us to store our keys is # in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256( hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + \ potentialPrivEncryptionKey checksum = hashlib.sha256( hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) try: BMConfigParser().add_section(address) addressAlreadyExists = False except: addressAlreadyExists = True if addressAlreadyExists: logger.info( '%s already exists. Not adding it again.', address) queues.UISignalQueue.put( ('updateStatusBar', tr._translate( "MainWindow", "%1 is already in 'Your Identities'." " Not adding it again.").arg(address))) else: logger.debug('label: %s', label) BMConfigParser().set(address, 'label', label) BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'decoy', 'false') if command == 'joinChan' \ or command == 'createChan': BMConfigParser().set(address, 'chan', 'true') BMConfigParser().set(address, 'noncetrialsperbyte', str(nonceTrialsPerByte)) BMConfigParser().set(address, 'payloadlengthextrabytes', str(payloadLengthExtraBytes)) BMConfigParser().set(address, 'privSigningKey', privSigningKeyWIF) BMConfigParser().set(address, 'privEncryptionKey', privEncryptionKeyWIF) BMConfigParser().save() queues.UISignalQueue.put( ('writeNewAddressToTable', (label, address, str(streamNumber)))) listOfNewAddressesToSendOutThroughTheAPI.append( address) shared.myECCryptorObjects[ripe] = \ highlevelcrypto.makeCryptor( hexlify(potentialPrivEncryptionKey)) shared.myAddressesByHash[ripe] = address tag = hashlib.sha512( hashlib.sha512( encodeVarint(addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:] shared.myAddressesByTag[tag] = address if addressVersionNumber == 3: # If this is a chan address, # the worker thread won't send out # the pubkey over the network. queues.workerQueue.put( ('sendOutOrStoreMyV3Pubkey', ripe)) elif addressVersionNumber == 4: queues.workerQueue.put( ('sendOutOrStoreMyV4Pubkey', address)) queues.UISignalQueue.put( ('updateStatusBar', tr._translate("MainWindow", "Done generating address"))) elif saveAddressToDisk and not live \ and not BMConfigParser().has_section(address): listOfNewAddressesToSendOutThroughTheAPI.append( address) # Done generating addresses. if command == 'createDeterministicAddresses' \ or command == 'joinChan' or command == 'createChan': queues.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) elif command == 'getDeterministicAddress': queues.apiAddressGeneratorReturnQueue.put(address) else: raise Exception( "Error in the addressGenerator thread. Thread was" + " given a command it could not understand: " + command) queues.addressGeneratorQueue.task_done()
def run(self): while True: queueValue = shared.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 if queueValue[0] == 'createChan': command, addressVersionNumber, streamNumber, label, deterministicPassphrase = queueValue eighteenByteRipe = False numberOfAddressesToMake = 1 elif queueValue[0] == 'joinChan': command, chanAddress, label, deterministicPassphrase = queueValue eighteenByteRipe = False addressVersionNumber = decodeAddress(chanAddress)[1] streamNumber = decodeAddress(chanAddress)[2] numberOfAddressesToMake = 1 elif len(queueValue) == 7: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue elif len(queueValue) == 9: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue else: sys.stderr.write( 'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % repr(queueValue)) if addressVersionNumber < 3 or addressVersionNumber > 3: sys.stderr.write( 'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber) if nonceTrialsPerByte == 0: nonceTrialsPerByte = shared.config.getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte if payloadLengthExtraBytes == 0: payloadLengthExtraBytes = shared.config.getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes if addressVersionNumber == 3: # currently the only one supported. if command == 'createRandomAddress': shared.UISignalQueue.put(( 'updateStatusBar', tr.translateText("MainWindow", "Generating one new address"))) # This next section is a little bit strange. We're going to generate keys over and over until we # find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address, # we won't store the \x00 or \x00\x00 bytes thus making the # address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) potentialPubSigningKey = pointMult(potentialPrivSigningKey) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPubEncryptionKey = pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', # potentialPubEncryptionKey.encode('hex') ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) # print 'potential ripe.digest', # ripe.digest().encode('hex') if eighteenByteRipe: if ripe.digest()[:2] == '\x00\x00': break else: if ripe.digest()[:1] == '\x00': break print 'Generated address with ripe digest:', ripe.digest().encode('hex') print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.' address = encodeAddress(3, streamNumber, ripe.digest()) # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) # print 'privSigningKeyWIF',privSigningKeyWIF privEncryptionKey = '\x80' + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) # print 'privEncryptionKeyWIF',privEncryptionKeyWIF shared.config.add_section(address) shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( payloadLengthExtraBytes)) shared.config.set( address, 'privSigningKey', privSigningKeyWIF) shared.config.set( address, 'privEncryptionKey', privEncryptionKeyWIF) with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) # The API and the join and create Chan functionality # both need information back from the address generator. shared.apiAddressGeneratorReturnQueue.put(address) shared.UISignalQueue.put(( 'updateStatusBar', tr.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) shared.UISignalQueue.put(('writeNewAddressToTable', ( label, address, streamNumber))) shared.reloadMyAddressHashes() shared.workerQueue.put(( 'sendOutOrStoreMyV3Pubkey', ripe.digest())) elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress' or command == 'createChan' or command == 'joinChan': if len(deterministicPassphrase) == 0: sys.stderr.write( 'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.') if command == 'createDeterministicAddresses': statusbar = 'Generating ' + str( numberOfAddressesToMake) + ' new addresses.' shared.UISignalQueue.put(( 'updateStatusBar', statusbar)) signingKeyNonce = 0 encryptionKeyNonce = 1 listOfNewAddressesToSendOutThroughTheAPI = [ ] # We fill out this list no matter what although we only need it if we end up passing the info to the API. for i in range(numberOfAddressesToMake): # This next section is a little bit strange. We're going to generate keys over and over until we # find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them # into a Bitmessage address, we won't store the \x00 or # \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] potentialPubSigningKey = pointMult( potentialPrivSigningKey) potentialPubEncryptionKey = pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', # potentialPubEncryptionKey.encode('hex') signingKeyNonce += 2 encryptionKeyNonce += 2 ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) # print 'potential ripe.digest', # ripe.digest().encode('hex') if eighteenByteRipe: if ripe.digest()[:2] == '\x00\x00': break else: if ripe.digest()[:1] == '\x00': break print 'ripe.digest', ripe.digest().encode('hex') print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.' address = encodeAddress(3, streamNumber, ripe.digest()) saveAddressToDisk = True # If we are joining an existing chan, let us check to make sure it matches the provided Bitmessage address if command == 'joinChan': if address != chanAddress: shared.apiAddressGeneratorReturnQueue.put('chan name does not match address') saveAddressToDisk = False if command == 'getDeterministicAddress': saveAddressToDisk = False if saveAddressToDisk: # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + \ potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) addressAlreadyExists = False try: shared.config.add_section(address) except: print address, 'already exists. Not adding it again.' addressAlreadyExists = True if not addressAlreadyExists: print 'label:', label shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') if command == 'joinChan' or command == 'createChan': shared.config.set(address, 'chan', 'true') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( payloadLengthExtraBytes)) shared.config.set( address, 'privSigningKey', privSigningKeyWIF) shared.config.set( address, 'privEncryptionKey', privEncryptionKeyWIF) with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) shared.UISignalQueue.put(('writeNewAddressToTable', ( label, address, str(streamNumber)))) listOfNewAddressesToSendOutThroughTheAPI.append( address) shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( potentialPrivEncryptionKey.encode('hex')) shared.myAddressesByHash[ ripe.digest()] = address shared.workerQueue.put(( 'sendOutOrStoreMyV3Pubkey', ripe.digest())) # If this is a chan address, # the worker thread won't send out the pubkey over the network. # Done generating addresses. if command == 'createDeterministicAddresses' or command == 'joinChan' or command == 'createChan': shared.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) shared.UISignalQueue.put(( 'updateStatusBar', tr.translateText("MainWindow", "Done generating address"))) # shared.reloadMyAddressHashes() elif command == 'getDeterministicAddress': shared.apiAddressGeneratorReturnQueue.put(address) #todo: return things to the API if createChan or joinChan assuming saveAddressToDisk else: raise Exception( "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command)
def run(self): while shared.shutdown == 0: queueValue = shared.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 if queueValue[0] == 'createChan': command, addressVersionNumber, streamNumber, label, deterministicPassphrase = queueValue eighteenByteRipe = False numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif queueValue[0] == 'joinChan': command, chanAddress, label, deterministicPassphrase = queueValue eighteenByteRipe = False addressVersionNumber = decodeAddress(chanAddress)[1] streamNumber = decodeAddress(chanAddress)[2] numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif len(queueValue) == 7: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue try: numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint( 'bitmessagesettings', 'numberofnullbytesonaddress') except: if eighteenByteRipe: numberOfNullBytesDemandedOnFrontOfRipeHash = 2 else: numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # The default elif len(queueValue) == 9: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue try: numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint( 'bitmessagesettings', 'numberofnullbytesonaddress') except: if eighteenByteRipe: numberOfNullBytesDemandedOnFrontOfRipeHash = 2 else: numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # The default elif queueValue[0] == 'stopThread': break else: sys.stderr.write('Programming error: A structure with the wrong ' + 'number of values was passed into the addressGeneratorQueue. ' + 'Here is the queueValue: %s\n' % repr(queueValue)) if addressVersionNumber < 3 or addressVersionNumber > 4: sys.stderr.write( 'Program error: For some reason the address generator queue has ' + 'been given a request to create at least one version %s address ' + 'which it cannot do.\n' % addressVersionNumber) if nonceTrialsPerByte == 0: nonceTrialsPerByte = shared.config.getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte if payloadLengthExtraBytes == 0: payloadLengthExtraBytes = shared.config.getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes if command == 'createRandomAddress': shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "Generating one new address"))) # This next section is a little bit strange. We're going to generate keys over and over until we # find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address, # we won't store the \x00 or \x00\x00 bytes thus making the # address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) potentialPubSigningKey = highlevelcrypto.pointMult(potentialPrivSigningKey) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash: break logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest())) try: logger.info('Address generator calculated %s addresses at %s addresses per second before finding one with the correct ripe-prefix.' % (numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime))) except ZeroDivisionError: # The user must have a pretty fast computer. time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest()) # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) shared.config.add_section(address) shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( payloadLengthExtraBytes)) shared.config.set( address, 'privSigningKey', privSigningKeyWIF) shared.config.set( address, 'privEncryptionKey', privEncryptionKeyWIF) shared.writeKeysFile() # The API and the join and create Chan functionality # both need information back from the address generator. shared.apiAddressGeneratorReturnQueue.put(address) shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) shared.UISignalQueue.put(('writeNewAddressToTable', (label, address, streamNumber))) shared.reloadMyAddressHashes() if addressVersionNumber == 3: shared.workerQueue.put(( 'sendOutOrStoreMyV3Pubkey', ripe.digest())) elif addressVersionNumber == 4: shared.workerQueue.put(( 'sendOutOrStoreMyV4Pubkey', address)) elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress' or command == 'createChan' or command == 'joinChan': if len(deterministicPassphrase) == 0: sys.stderr.write('[WARN]: You are creating deterministic address(es) ' + 'using a blank passphrase. Bitmessage will do it ' + 'but it is rather stupid.') if command == 'createDeterministicAddresses': shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "Generating %1 new addresses.").arg(str(numberOfAddressesToMake)))) signingKeyNonce = 0 encryptionKeyNonce = 1 # We fill out this list no matter what although we only need it if we end up passing the info to the API. listOfNewAddressesToSendOutThroughTheAPI = [] for i in range(numberOfAddressesToMake): # This next section is a little bit strange. We're going to generate keys over and over until we # find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them # into a Bitmessage address, we won't store the \x00 or # \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey) signingKeyNonce += 2 encryptionKeyNonce += 2 ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash: break logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest())) try: logger.info('Address generator calculated %s addresses at %s addresses per second before finding one with the correct ripe-prefix.' % (numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime))) except ZeroDivisionError: # The user must have a pretty fast computer. time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest()) saveAddressToDisk = True # If we are joining an existing chan, let us check to make sure it matches the provided Bitmessage address if command == 'joinChan': if address != chanAddress: shared.apiAddressGeneratorReturnQueue.put('chan name does not match address') saveAddressToDisk = False if command == 'getDeterministicAddress': saveAddressToDisk = False if saveAddressToDisk: # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + \ potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) try: shared.config.add_section(address) addressAlreadyExists = False except: addressAlreadyExists = True if addressAlreadyExists: logger.info('%s already exists. Not adding it again.' % address) shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "%1 is already in 'Your Identities'. Not adding it again.").arg(address))) else: logger.debug('label: %s' % label) shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') if command == 'joinChan' or command == 'createChan': shared.config.set(address, 'chan', 'true') shared.config.set(address, 'noncetrialsperbyte', str(nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str(payloadLengthExtraBytes)) shared.config.set(address, 'privSigningKey', privSigningKeyWIF) shared.config.set(address, 'privEncryptionKey', privEncryptionKeyWIF) shared.writeKeysFile() shared.UISignalQueue.put(('writeNewAddressToTable', (label, address, str(streamNumber)))) listOfNewAddressesToSendOutThroughTheAPI.append(address) shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( hexlify(potentialPrivEncryptionKey)) shared.myAddressesByHash[ripe.digest()] = address tag = hashlib.sha512(hashlib.sha512(encodeVarint( addressVersionNumber) + encodeVarint(streamNumber) + ripe.digest()).digest()).digest()[32:] shared.myAddressesByTag[tag] = address if addressVersionNumber == 3: # If this is a chan address, # the worker thread won't send out the pubkey over the network. shared.workerQueue.put(('sendOutOrStoreMyV3Pubkey', ripe.digest())) elif addressVersionNumber == 4: shared.workerQueue.put(('sendOutOrStoreMyV4Pubkey', address)) shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "Done generating address"))) # Done generating addresses. if command == 'createDeterministicAddresses' or command == 'joinChan' or command == 'createChan': shared.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) elif command == 'getDeterministicAddress': shared.apiAddressGeneratorReturnQueue.put(address) else: raise Exception("Error in the addressGenerator thread. " + "Thread was given a command it could not understand: " + command) shared.addressGeneratorQueue.task_done()
def privToPub(privkey): private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) return public_key.encode('hex')
def run(self): while True: queueValue = shared.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 if len(queueValue) == 7: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue elif len(queueValue) == 9: command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue else: sys.stderr.write( 'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % queueValue) if addressVersionNumber < 3 or addressVersionNumber > 3: sys.stderr.write( 'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber) if nonceTrialsPerByte == 0: nonceTrialsPerByte = shared.config.getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte if payloadLengthExtraBytes == 0: payloadLengthExtraBytes = shared.config.getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes if addressVersionNumber == 3: # currently the only one supported. if command == 'createRandomAddress': shared.UISignalQueue.put(( 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Generating one new address"))) # This next section is a little bit strange. We're going to generate keys over and over until we # find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address, # we won't store the \x00 or \x00\x00 bytes thus making the # address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) potentialPubSigningKey = pointMult(potentialPrivSigningKey) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPubEncryptionKey = pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', # potentialPubEncryptionKey.encode('hex') ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) # print 'potential ripe.digest', # ripe.digest().encode('hex') if eighteenByteRipe: if ripe.digest()[:2] == '\x00\x00': break else: if ripe.digest()[:1] == '\x00': break print 'Generated address with ripe digest:', ripe.digest().encode('hex') print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.' address = encodeAddress(3, streamNumber, ripe.digest()) # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) # print 'privSigningKeyWIF',privSigningKeyWIF privEncryptionKey = '\x80' + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) # print 'privEncryptionKeyWIF',privEncryptionKeyWIF shared.config.add_section(address) shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( payloadLengthExtraBytes)) shared.config.set( address, 'privSigningKey', privSigningKeyWIF) shared.config.set( address, 'privEncryptionKey', privEncryptionKeyWIF) with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) # It may be the case that this address is being generated # as a result of a call to the API. Let us put the result # in the necessary queue. bitmessagemain.apiAddressGeneratorReturnQueue.put(address) shared.UISignalQueue.put(( 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it..."))) shared.UISignalQueue.put(('writeNewAddressToTable', ( label, address, streamNumber))) shared.reloadMyAddressHashes() shared.workerQueue.put(( 'doPOWForMyV3Pubkey', ripe.digest())) elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress': if len(deterministicPassphrase) == 0: sys.stderr.write( 'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.') if command == 'createDeterministicAddresses': statusbar = 'Generating ' + str( numberOfAddressesToMake) + ' new addresses.' shared.UISignalQueue.put(( 'updateStatusBar', statusbar)) signingKeyNonce = 0 encryptionKeyNonce = 1 listOfNewAddressesToSendOutThroughTheAPI = [ ] # We fill out this list no matter what although we only need it if we end up passing the info to the API. for i in range(numberOfAddressesToMake): # This next section is a little bit strange. We're going to generate keys over and over until we # find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them # into a Bitmessage address, we won't store the \x00 or # \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] potentialPubSigningKey = pointMult( potentialPrivSigningKey) potentialPubEncryptionKey = pointMult( potentialPrivEncryptionKey) # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubEncryptionKey', # potentialPubEncryptionKey.encode('hex') signingKeyNonce += 2 encryptionKeyNonce += 2 ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update( potentialPubSigningKey + potentialPubEncryptionKey) ripe.update(sha.digest()) # print 'potential ripe.digest', # ripe.digest().encode('hex') if eighteenByteRipe: if ripe.digest()[:2] == '\x00\x00': break else: if ripe.digest()[:1] == '\x00': break print 'ripe.digest', ripe.digest().encode('hex') print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.' address = encodeAddress(3, streamNumber, ripe.digest()) if command == 'createDeterministicAddresses': # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = '\x80' + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) privEncryptionKey = '\x80' + \ potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58) try: shared.config.add_section(address) print 'label:', label shared.config.set(address, 'label', label) shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'noncetrialsperbyte', str( nonceTrialsPerByte)) shared.config.set(address, 'payloadlengthextrabytes', str( payloadLengthExtraBytes)) shared.config.set( address, 'privSigningKey', privSigningKeyWIF) shared.config.set( address, 'privEncryptionKey', privEncryptionKeyWIF) with open(shared.appdata + 'keys.dat', 'wb') as configfile: shared.config.write(configfile) shared.UISignalQueue.put(('writeNewAddressToTable', ( label, address, str(streamNumber)))) listOfNewAddressesToSendOutThroughTheAPI.append( address) # if eighteenByteRipe: # shared.reloadMyAddressHashes()#This is # necessary here (rather than just at the end) # because otherwise if the human generates a # large number of new addresses and uses one # before they are done generating, the program # will receive a getpubkey message and will # ignore it. shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor( potentialPrivEncryptionKey.encode('hex')) shared.myAddressesByHash[ ripe.digest()] = address shared.workerQueue.put(( 'doPOWForMyV3Pubkey', ripe.digest())) except: print address, 'already exists. Not adding it again.' # Done generating addresses. if command == 'createDeterministicAddresses': # It may be the case that this address is being # generated as a result of a call to the API. Let us # put the result in the necessary queue. bitmessagemain.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) shared.UISignalQueue.put(( 'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address"))) # shared.reloadMyAddressHashes() elif command == 'getDeterministicAddress': bitmessagemain.apiAddressGeneratorReturnQueue.put(address) else: raise Exception( "Error in the addressGenerator thread. Thread was given a command it could not understand: " + command)
if __name__ == "__main__": print 'Let us make an address from scratch. Suppose we generate two random 32 byte values and call the first one the signing key and the second one the encryption key:' privateSigningKey = '93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665' privateEncryptionKey = '4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a' print 'privateSigningKey =', privateSigningKey print 'privateEncryptionKey =', privateEncryptionKey print 'Now let us convert them to public keys by doing an elliptic curve point multiplication.' publicSigningKey = arithmetic.privtopub(privateSigningKey) publicEncryptionKey = arithmetic.privtopub(privateEncryptionKey) print 'publicSigningKey =', publicSigningKey print 'publicEncryptionKey =', publicEncryptionKey print 'Notice that they both begin with the \\x04 which specifies the encoding type. This prefix is not send over the wire. You must strip if off before you send your public key across the wire, and you must add it back when you receive a public key.' publicSigningKeyBinary = arithmetic.changebase(publicSigningKey, 16, 256, minlen=64) publicEncryptionKeyBinary = arithmetic.changebase(publicEncryptionKey, 16, 256, minlen=64) ripe = hashlib.new('ripemd160') sha = hashlib.new('sha512') sha.update(publicSigningKeyBinary + publicEncryptionKeyBinary) ripe.update(sha.digest()) addressVersionNumber = 2 streamNumber = 1 print 'Ripe digest that we will encode in the address:', hexlify( ripe.digest())
privkey = Key.from_sec(unhexlify(secret)) else: try: privkey = Key.from_text(secret) except encoding.EncodingError: pass # Define vars automatically from privkey (could be manually, if you had the values) privkey_uncompressed = '%x' % privkey.secret_exponent() pubkey_uncompressed = hexlify(privkey.sec(use_uncompressed=True)) ## # Prepare pubkey for encrypting ## pubkey_bin_tmp = arithmetic.changebase(pubkey_uncompressed[2:], 16, 256, minlen=64) pubkey_bin = '\x02\xca\x00 '+ pubkey_bin_tmp[:32] + '\x00 ' + pubkey_bin_tmp[32:] # Optionally you can use unhexlify, but need to add '\x20' after '\x00' #pubkey_bin_tmp = unhexlify(pubkey_uncompressed) #pubkey_bin = '\x02\xca\x00\x20' + pubkey_bin_tmp[1:-32] + '\x00\x20' + pubkey_bin_tmp[-32:] ## # Prepare private key for decrypting ## # Private Key to Bin privkey_bin = '\x02\xca\x00\x20' + arithmetic.changebase(privkey_uncompressed, 16, 256, minlen=32) # Optionally you can use unhexlify #privkey_bin = '\x02\xca\x00\x20' + unhexlify(privkey_uncompressed)