helper_bitcoin.py.bak
1 """ 2 Calculates bitcoin and testnet address from pubkey 3 """ 4 5 import hashlib 6 7 from debug import logger 8 from pyelliptic import arithmetic 9 10 11 def calculateBitcoinAddressFromPubkey(pubkey): 12 """Calculate bitcoin address from given pubkey (65 bytes long hex string)""" 13 if len(pubkey) != 65: 14 logger.error('Could not calculate Bitcoin address from pubkey because' 15 ' function was passed a pubkey that was' 16 ' %i bytes long rather than 65.', len(pubkey)) 17 return "error" 18 ripe = hashlib.new('ripemd160') 19 sha = hashlib.new('sha256') 20 sha.update(pubkey) 21 ripe.update(sha.digest()) 22 ripeWithProdnetPrefix = '\x00' + ripe.digest() 23 24 checksum = hashlib.sha256(hashlib.sha256( 25 ripeWithProdnetPrefix).digest()).digest()[:4] 26 binaryBitcoinAddress = ripeWithProdnetPrefix + checksum 27 numberOfZeroBytesOnBinaryBitcoinAddress = 0 28 while binaryBitcoinAddress[0] == '\x00': 29 numberOfZeroBytesOnBinaryBitcoinAddress += 1 30 binaryBitcoinAddress = binaryBitcoinAddress[1:] 31 base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) 32 return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded 33 34 35 def calculateTestnetAddressFromPubkey(pubkey): 36 """This function expects that pubkey begin with the testnet prefix""" 37 if len(pubkey) != 65: 38 logger.error('Could not calculate Bitcoin address from pubkey because' 39 ' function was passed a pubkey that was' 40 ' %i bytes long rather than 65.', len(pubkey)) 41 return "error" 42 ripe = hashlib.new('ripemd160') 43 sha = hashlib.new('sha256') 44 sha.update(pubkey) 45 ripe.update(sha.digest()) 46 ripeWithProdnetPrefix = '\x6F' + ripe.digest() 47 48 checksum = hashlib.sha256(hashlib.sha256( 49 ripeWithProdnetPrefix).digest()).digest()[:4] 50 binaryBitcoinAddress = ripeWithProdnetPrefix + checksum 51 numberOfZeroBytesOnBinaryBitcoinAddress = 0 52 while binaryBitcoinAddress[0] == '\x00': 53 numberOfZeroBytesOnBinaryBitcoinAddress += 1 54 binaryBitcoinAddress = binaryBitcoinAddress[1:] 55 base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) 56 return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded