def createOrder(self, amount, currency=config.DEFAULT_CURRENCY, item_number=None, order_id=None, gen_new = None): '''The main order creation method to which the api call is routed''' if gen_new is None: gen_new = config.GEN_NEW #timestamp = time.time() #Try ret btc_price = str(ticker.getPriceInBTC(amount, currency=currency)) #if error: return error #special_digits are 0 on gen_new, we add them to the db but ignore them for the order, and return exact_amount: False with self.locks['order']: receiving_address, special_digits = self.getPaymentAddress(gen_new) if not receiving_address: return "failed to obtain payment address stuff" if not gen_new: btc_price = btc_price.__str__() + ('0000' + str(special_digits))[-4:] #Hash an order_id as base58 - because if someone needs to reference it the bitcoin standard is the most readable #Note that the pycoin to_long method reads bytes as big endian. if not order_id: order_id = b2a_base58(sha1(json.dumps({'price': str(btc_price), 'address': str(receiving_address), 'special_digits': str(special_digits)}).encode('utf-8')).digest()) timeleft = config.ORDER_LIFE err= self.db.addOrder({'order_id': order_id, 'native_price': amount, 'native_currency': currency, 'btc_price': btc_price, 'special_digits':special_digits, 'keypath': str(self.wallet.keypath), 'item_number': item_number, 'receiving_address':receiving_address, 'max_life': config.ORDER_LIFE}) if err: return {'error': str(err)} return {'amount': btc_price, 'receiving_address': receiving_address, 'order_id': order_id, 'timeleft': timeleft, 'exact_amount': not gen_new}
def main(): parser = argparse.ArgumentParser(description="Bitcoin utilities. WARNING: obsolete. Use ku instead.") parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true') parser.add_argument('-1', "--hash160", help='show as hash 160', action='store_true') parser.add_argument('-v', "--verbose", help='dump all information available', action='store_true') parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true') parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true') parser.add_argument('item', help='a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address', nargs="+") args = parser.parse_args() for c in args.item: # figure out what it is: # - secret exponent # - WIF # - X/Y public key (base 10 or hex) # - sec # - hash160 # - Bitcoin address secret_exponent = parse_as_private_key(c) if secret_exponent: public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent) print("secret exponent: %d" % secret_exponent) print(" hex: %x" % secret_exponent) print("WIF: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True)) print(" uncompressed: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False)) else: public_pair = parse_as_public_pair(c) if public_pair: bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False) bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True) print("public pair x: %d" % public_pair[0]) print("public pair y: %d" % public_pair[1]) print(" x as hex: %x" % public_pair[0]) print(" y as hex: %x" % public_pair[1]) print("y parity: %s" % "odd" if (public_pair[1] & 1) else "even") print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True))) s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False)) print(" uncompressed: %s\\\n %s" % (s[:66], s[66:])) hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True) hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False) myeccpoint = encoding.public_pair_to_sec(public_pair, compressed=True) myhash = encoding.ripemd160( myeccpoint ).digest( ) print("BTSX PubKey: %s" % BTS_ADDRESS_PREFIX + encoding.b2a_base58(myeccpoint + myhash[ :4 ])) else: hash160 = parse_as_address(c) hash160_unc = None if not hash160: sys.stderr.write("can't decode input %s\n" % c) sys.exit(1) print("hash160: %s" % b2h(hash160)) if hash160_unc: print(" uncompressed: %s" % b2h(hash160_unc)) print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160)) if hash160_unc: print(" uncompressed: %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
def createOrder(self, amount, currency=config.DEFAULT_CURRENCY, item_number=None, order_id=None, gen_new=None): '''The main order creation method to which the api call is routed''' if gen_new is None: gen_new = config.GEN_NEW #timestamp = time.time() #Try ret btc_price = str(ticker.getPriceInBTC(amount, currency=currency)) #if error: return error #special_digits are 0 on gen_new, we add them to the db but ignore them for the order, and return exact_amount: False with self.locks['order']: receiving_address, special_digits = self.getPaymentAddress(gen_new) if not receiving_address: return "failed to obtain payment address stuff" if not gen_new: btc_price = btc_price.__str__() + ('0000' + str(special_digits))[-4:] #Hash an order_id as base58 - because if someone needs to reference it the bitcoin standard is the most readable #Note that the pycoin to_long method reads bytes as big endian. if not order_id: order_id = b2a_base58( sha1( json.dumps({ 'price': str(btc_price), 'address': str(receiving_address), 'special_digits': str(special_digits) }).encode('utf-8')).digest()) timeleft = config.ORDER_LIFE err = self.db.addOrder({ 'order_id': order_id, 'native_price': amount, 'native_currency': currency, 'btc_price': btc_price, 'special_digits': special_digits, 'keypath': str(self.wallet.keypath), 'item_number': item_number, 'receiving_address': receiving_address, 'max_life': config.ORDER_LIFE }) if err: return {'error': str(err)} return { 'amount': btc_price, 'receiving_address': receiving_address, 'order_id': order_id, 'timeleft': timeleft, 'exact_amount': not gen_new }
assert(my_key.sec_as_hex() == bitcoin.core.b2x(my_key.sec())) print("Public key hash160: ", b2h(my_key.hash160())) print(" uncompressed: ", b2h(my_key.hash160(use_uncompressed=True))) #print("Bitcoin Address : ", my_key.address()) addr_compressed = encoding.public_pair_to_bitcoin_address(public_key, True, my_addr_prefix) addr_uncompressed = encoding.public_pair_to_bitcoin_address(public_key, False, my_addr_prefix) print("Bitcoin Address: ", addr_compressed) print(" uncompressed: ", addr_uncompressed) assert(encoding.is_valid_bitcoin_address(addr_compressed, my_addr_prefix)) assert(encoding.is_valid_bitcoin_address(addr_uncompressed, my_addr_prefix)) assert(my_key.address() == addr_compressed) pubkey_bytes = encoding.public_pair_to_sec(public_key, True); assert(my_key.sec_as_hex() == b2h(pubkey_bytes)) pubkey_bytes = encoding.public_pair_to_sec(public_key, False); assert(my_key.sec_as_hex(use_uncompressed=True) == b2h(pubkey_bytes)) print() #CBitcoinAddress.from_bytes(bitcoin.core.serialize.Hash160(my_key.address()), 111) btc_addr = CBitcoinAddress.from_bytes(bitcoin.base58.decode(my_key.address()), bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']) print("Bitcoin Address hex: ", hexlify(btc_addr.to_bytes())) assert(bitcoin.base58.encode(btc_addr.to_bytes()) == addr_compressed) pubkey_b58 = encoding.b2a_base58(pubkey_bytes) #CBitcoinAddress.from_scriptPubKey(pubkey_b58)
def do_test(as_text, as_bin): self.assertEqual(as_bin, encoding.a2b_base58(as_text)) self.assertEqual(as_text, encoding.b2a_base58(as_bin))
def get_color_hash(self): """Returns the hash used in color addresses. """ return b2a_base58(self.get_hash_string().decode('hex')[:10])
def generatePrivPubAddressData(): privPubAddressData = {} #--------------------------[ ECDSA ]------------------------------# # Creating the gPoint (also known as G, in the formula P = k * G) gPoint = secp.generator_secp256k1 # Randomize a string of n random bytes for getting the Secret Exponent (also known as k, in the formula P = k * G) rand = codecs.encode(os.urandom(32), 'hex').decode() secretExponent = int('0x' + rand, 0) #secretExponent = 10 # Uses 10 for test, to see that everything matches up! # Calculate the public key (point) (also known as the P, in the formula P = k * G) publicKeyPoint = secretExponent * gPoint #-----------------------------------------------------------------# #-------------------------[ PRIVATE KEY ]-------------------------# secretExponentHexified = '%064x' % secretExponent # 80 = mainnet, 01 = compressed public key should be generated data = '80' + secretExponentHexified + '01' # 4 bytes, 8 hex checkSum = getDoubleSha256(data)[:8] data = data + checkSum wif = encoding.b2a_base58(binascii.unhexlify(data)) #-----------------------------------------------------------------# #-------------------------[ PUBLIC KEY ]--------------------------# # This encoding is standardized by SEC, Standards for Efficient Cryptography Group (SECG). # Uncompressed public key has the prefix 0x04 x = '%064x' % publicKeyPoint.x() y = '%064x' % publicKeyPoint.y() uncompressedPublicKey = '04' + x + y #print('Public key, uncompressed', uncompressedPublicKey) # Compressed public key has the prefix 02 if y is even, 03 if y is odd compressedPublicKey = ('02' if publicKeyPoint.y() % 2 == 0 else '03') + x #print('Public key, compressed', compressedPublicKey) #-----------------------------------------------------------------# #-------------------------[ BITCOIN ADDRESS ]---------------------# # Add the version byte 00 and get the hash160 of the publicKey from the uncompressed publicKey uncompressedH160WithVersion = '00' + getHash160(uncompressedPublicKey) # Add 4 bytes checkSum from double sha256 encyption checkSum = getDoubleSha256(uncompressedH160WithVersion)[:8] uncompressedH160WithVersion = uncompressedH160WithVersion + checkSum # Convert to base58 bitCoinAddressUncompressed = encoding.b2a_base58(binascii.unhexlify(uncompressedH160WithVersion)) #print('Bitcoin address (uncomp):', bitCoinAddressUncompressed) # Add the version byte 00 and gets the hash160 of the publicKey from the compressed publicKey compressedH160WithVersion = '00' + getHash160(compressedPublicKey) # Add 4 bytes checkSum from double sha256 encyption checkSum = getDoubleSha256(compressedH160WithVersion)[:8] compressedH160WithVersion = compressedH160WithVersion + checkSum # Convert to base58 bitCoinAddressCompressed = encoding.b2a_base58(binascii.unhexlify(compressedH160WithVersion)) privPubAddressData = (secretExponent, secretExponentHexified, wif, uncompressedPublicKey, compressedPublicKey, bitCoinAddressUncompressed, bitCoinAddressCompressed) return privPubAddressData
def address_pretty(self): return b2a_base58(self.address)
def validate_address(address_bytes): _assert(type(address_bytes) == bytes, 'Address: type must be bytes') _assert(len(address_bytes) == 25, 'Address: len != 25') v_hash160 = a2b_hashed_base58(b2a_base58(address_bytes)) _assert(v_hash160 == address_bytes[0:21], 'Address: version + hash160 does not match')
for i3 in '6': # sure for i4 in '123456789': # NOT sure for i6 in '123456789': # NOT sure for i7 in '123456789': # NOT sure # make candidate private key key = k1 + i1 + k2 + i2 + k3 + i3 + k4 + i4 + k5 + i3 + k6 + i6 + k7 + i7 + k8 print('Trying {}...\t'.format(key), end='') # the private key encoded in base58 contains also a checksum at the end to check validity # when a candidate key is made by concatenation as above it will most likely not be valid # so we correct the checksum and compression byte of the candidate key data = a2b_base58(key) data, the_hash = data[:-4], data[-4:] data = data[:-1] + b'\01' fixed_key = b2a_base58(data + double_sha256(data)[:4]) # calculate the P2SH SegWit address for this private key k = Key.from_text(fixed_key) p2sh = p2sh_address(k) print('{}\t'.format(p2sh), end='') # compare with the published public key if p2sh[0:7] == '37CSnmm': print('Bingo!') exit(0) else: i = 0 stars = '' while p2sh[i] == '37CSnmm'[i]: stars += '*'