def validate(self): if len(self.request.address) == 111: return self.validate_extended(checksum_algo='blake256') try: decoded_address = base58check.b58decode(self.request.address) except ValueError: return False # decoded address has to be 26 bytes long if len(decoded_address) != 26: return False # original one has to start with D,T,S or R if not self.request.address.startswith((b'D', b'T', b'S', b'R')): return False expected_checksum = decoded_address[-4:] version_bytes = int.from_bytes(decoded_address[:2], byteorder='big') if self.network == '': return False checksum = blake256.blake_hash( blake256.blake_hash(decoded_address[:-4]))[:4] # double blake256 checksum needs to be equal with the expected checksum if checksum != expected_checksum: return False return True
def _is_address_valid(self, address): """Checks is an address string is valid""" digits_58_pattern = r'[^123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]' # check for invalid characters if re.search(digits_58_pattern, address): return False # check for length (26-35 characters) # TODO: need to confirm the possible length! if len(address) < 26 or len(address) > 35: return False # get data, network_prefix and checksum data_checksum = b58decode(address.encode('utf-8')) data = data_checksum[:-4] network_prefix = data_checksum[:1] checksum = data_checksum[-4:] # check correct network (depending on address type) if self.get_type() == P2PKH_ADDRESS: if network_prefix != NETWORK_P2PKH_PREFIXES[get_network()]: return False elif self.get_type() == P2SH_ADDRESS: if network_prefix != NETWORK_P2SH_PREFIXES[get_network()]: return False # check address' checksum data_hash = hashlib.sha256(hashlib.sha256(data).digest()).digest() if data_hash[0:4] != checksum: return False return True
def wif_to_private_key(wif): output = base58check.b58decode(wif) output = output[ 1: -5] # drop first network type byte, last 4 bytes checksum, 5-th from the end means that priv key is compressed return encode_hex(output)[0].decode()
def setPrivKey(self, wifCompressedKey): try: key = base58check.b58decode(wifCompressedKey)[1:-5].hex() except ValueError: key = wifCompressedKey self.secret = int(key, 16) self.point = self.secret * self.generator
def get_magic_byte(address): decode_hex = codecs.getdecoder("hex_codec") encode_hex = codecs.getencoder("hex_codec") output = base58check.b58decode(address) output = encode_hex(output)[0].decode() return int(output[0:2], 16)
def address_type(self): """Return address type derived from network version bytes.""" if len(self.request.address) == 0: return '' try: abytes = base58check.b58decode(self.request.address, **self.request.extras) except ValueError: return '' for name, networks in self.request.currency.address_types.items(): for netw in networks: if netw != 0: # count the prefix length in bytes prefixlen = math.ceil( math.floor((math.log(netw) / math.log(2)) + 1) / 8) else: prefixlen = 1 address_prefix = [x for x in bytearray(abytes[:prefixlen])] if prefixtodec(address_prefix) == netw: return name if len(self.request.currency.address_types.items()) == 0: return 'address' else: return ''
def send_cs(api, src_priv, src_pub, dst_pub): wallet = api.WalletTransactionsCountGet(base58check.b58decode(src_pub)) lastInnerId = bytearray( (wallet.lastTransactionInnerId + 1).to_bytes(6, 'little')) tr = Transaction() tr.id = int.from_bytes(lastInnerId, byteorder='little', signed=False) tr.source = base58check.b58decode(src_pub) tr.target = base58check.b58decode(dst_pub) # Amount tr.amount = Amount() tr.amount.integral = 0 tr.amount.fraction = random.randint(100000000000000000, 750000000000000000) # random number # Balance tr.balance = Amount() tr.balance.integral = 0 tr.balance.fraction = 0 tr.currency = 1 # Fee tr.fee = AmountCommission() tr.fee.commission = 19128 serial_transaction = pack( '=6s32s32slqhbb', #'=' - without alignment lastInnerId, #6s - 6 byte InnerID (char[] C Type) tr.source, #32s - 32 byte source public key (char[] C Type) tr.target, #32s - 32 byte target pyblic key (char[] C Type) tr.amount.integral, #i - 4 byte integer(int C Type) tr.amount.fraction, #q - 8 byte integer(long long C Type) tr.fee.commission, #h - 2 byte integer (short C Type) tr.currency, #b - 1 byte integer (signed char C Type) 0) #b - 1 byte userfield_num #Calculate signing keydata = base58check.b58decode(src_priv) #Создаем объект ed25519 signing_key = ed25519.SigningKey(keydata) #Получаем цифровую подпись msg sign = signing_key.sign(serial_transaction) tr.signature = sign print('send money:' + serial_transaction.hex()) #Run TransactionFlow() res = api.TransactionFlow(tr) print(res.status.message) return res
def from_xpub( xpub: str, xpub_type: Optional[XpubType] = None, path: Optional[str] = None, ) -> 'HDKey': """ Instantiate an HDKey from an xpub. Populates all possible fields Args: xpub (str): the xpub path (str): the path if it's known. useful for calling derive_path Returns: (HDKey): the key object May raise: - XPUBError if there is a problem with decoding the xpub """ xpub_bytes = b58decode(xpub) if len(xpub_bytes) < 78: raise XPUBError(f'Given XPUB {xpub} is too small') try: pubkey = PublicKey(xpub_bytes[45:78]) except ValueError as e: raise XPUBError(str(e)) from e result = _parse_prefix(xpub_bytes[0:4]) if not result.is_public: raise XPUBError('Given xpub is an extended private key') if result.network != 'mainnet': raise XPUBError('Given xpub is not for the bitcoin mainnet') hint = result.hint if xpub_type is not None and xpub_type.matches_prefix( xpub[0:4]) is False: # the given type does not match the prefix, re-encode with correct pref new_xpub = bytearray() new_xpub.extend(xpub_type.prefix_bytes()) new_xpub.extend(xpub_bytes[4:]) new_xpub_bytes = new_xpub hint = xpub_type.prefix() xpub = b58encode(bytes(new_xpub_bytes)).decode('ascii') return HDKey( path=path, network=result.network, depth=xpub_bytes[4], parent_fingerprint=xpub_bytes[5:9], index=int.from_bytes(xpub_bytes[9:13], byteorder='big'), parent=None, chain_code=xpub_bytes[13:45], fingerprint=hash160(pubkey.format(COMPRESSED_PUBKEY))[:4], xpriv=None, xpub=xpub, privkey=None, pubkey=pubkey, hint=hint, )
def network(self): """Return network derived from network version bytes.""" abytes = base58check.b58decode(self.request.address, **self.request.extras) nbyte = abytes[0] for name, networks in self.request.currency.networks.items(): if nbyte in networks: return name
def b58_key_to_hex(b58_key: str) -> str: """Translate a tezos b58check key encoding to a hex string. Params: b58_sig (str): tezos b58check encoding of a key Returns: str: hex string of key """ # we get rid of prefix and final checksum return base58check.b58decode(b58_key).hex()[8:-8]
def wif_to_private_key(wif): decode_hex = codecs.getdecoder("hex_codec") encode_hex = codecs.getencoder("hex_codec") output = base58check.b58decode(wif) #print(output) output = output[ 1: -5] # drop first network type byte, last 4 bytes checksum, 5-th from the end means that priv key is compressed #print(output) return encode_hex(output)[0].decode()
def b58_sig_to_hex(b58_sig: str) -> str: """Translate a tezos b58check signature encoding to a hex string. Params: b58_sig (str): tezos b58check encoding of a signature Returns: str: hex string of signature """ # we get rid of prefix and final checksum return base58check.b58decode(b58_sig).hex()[10:-8]
def _address_to_hash160(self, address): """Converts an address to it's hash160 equivalent Base58CheckDecode the address and remove network_prefix and checksum. """ addr_encoded = address.encode('utf-8') data_checksum = b58decode(addr_encoded) network_prefix = data_checksum[:1] data = data_checksum[1:-4] #checksum = data_checksum[-4:] return hexlify(data).decode('utf-8')
def is_valid_address(address): decode_hex = codecs.getdecoder("hex_codec") encode_hex = codecs.getencoder("hex_codec") output = base58check.b58decode(address) output = encode_hex(output)[0].decode() checksum = output[-8:] extended_ripmd160 = output[:-8] output = decode_hex(extended_ripmd160)[0] output = sha256(sha256(output).digest()).hexdigest()[0:8] return checksum == output
def validate(self): """Validate the address.""" if 25 > len(self.request.address) > 35: return False abytes = base58check.b58decode(self.request.address, **self.request.extras) if not abytes[0] in self.request.networks: return False checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4] if abytes[-4:] != checksum: return False return self.request.address == base58check.b58encode( abytes, **self.request.extras)
def check_availability(address): if not 26 <= len(address) <= 35 \ or not (address[0] == '1' or address[0] == '3'): print("Sender's/recipient's address isn't valid") return 0 try: decoded = hexlify(b58decode(address)) except: print("Addresses encoding isn't valid: " + address) return 0 c1 = sha256( sha256(unhexlify( decoded[:-8].decode("utf-8") )).digest() ).hexdigest() checksum = str( c1 )[:8] if checksum != decoded.decode("utf-8")[-8:]: print("Addresses checksum isn't valid: " + checksum + " != " + decoded.decode("utf-8")[-8:]) return 0 return 1
def verify_address(address): output = base58check.b58decode(address) output = encode_hex(output)[0].decode() print(output) if len(output) != 50: raise Exception('Invalid address length exception') checksum = output[-8:] extended_ripemd160 = output[:-8] output = decode_hex(extended_ripemd160)[0] output = sha256(sha256(output).digest()).hexdigest()[0:8] if checksum != output: raise Exception('Invalid checksum') return True
def validate(self): # groestlcoin address is 34 bytes long if len(self.request.address) != 34: return False try: decoded = base58check.b58decode(self.request.address) except ValueError: return False hash_str = decoded[0:21] checksum = groestlcoin_hash2.groestl_hash(hash_str)[:4] expected_checksum = decoded[21:] if checksum != expected_checksum: return False return True
def validate(self): try: decoded_address = base58check.b58decode(self.request.address) except ValueError: return False if self.network == '': return False decoded_address = cbor.loads(decoded_address) tagged_address = decoded_address[0] expected_checksum = decoded_address[1] checksum = crc32(tagged_address.value) if checksum != expected_checksum: return False return True
def validate(self, address): if not isinstance(address, str): self._fail(address, 'Address must be a string') if not 25 <= len(address) <= 35: self._fail(address, 'Address length must be between 25 and 35 characters') if not all(char in default_alphabet for char in address): self._fail(address, 'Address has invalid characters') abytes = base58check.b58decode(address) checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4] if abytes[-4:] != checksum: self._checksum_fail(address) return Base58CheckValidationResult(self, address, abytes[0])
def is_valid_btc_address(value: str) -> bool: """Validates a bitcoin address for the mainnet Code is taken from: https://github.com/joeblackwaslike/coinaddr/blob/ae35c7ae550a687d9a7c2e0cb090d52edbb29cb5/coinaddr/validation.py#L67-L87 """ if 25 > len(value) > 35: return False abytes = base58check.b58decode(value) if not abytes[0] in (0x00, 0x05): return False checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4] if abytes[-4:] != checksum: return False return value == base58check.b58encode(abytes).decode()
def _make_child_xpub(self, child_pubkey: PublicKey, index: int, chain_code: bytes) -> str: """ Makes a child xpub based on the current key and the child key info. Args: child_pubkey (bytes): the child pubkey index (int): the child index chain_code (bytes): the child chain code Returns (str): the child xpub """ xpub = bytearray() xpub.extend(b58decode(cast(str, self.xpub))[0:4]) # prefix xpub.extend([cast(int, self.depth) + 1]) # depth xpub.extend(self.fingerprint) # fingerprint xpub.extend(index.to_bytes(4, byteorder='big')) # index xpub.extend(chain_code) # chain_code xpub.extend(child_pubkey.format(COMPRESSED_PUBKEY)) # pubkey (comp) return b58encode(bytes(xpub)).decode('ascii')
def from_xpub(xpub: str, path: Optional[str] = None) -> 'HDKey': """ Instantiate an HDKey from an xpub. Populates all possible fields Args: xpub (str): the xpub path (str): the path if it's known. useful for calling derive_path Returns: (HDKey): the key object May raise: - XPUBError if there is a problem with decoding the xpub """ xpub_bytes = b58decode(xpub) if len(xpub_bytes) < 78: raise XPUBError(f'Given XPUB {xpub} is too small') try: pubkey = PublicKey(xpub_bytes[45:78]) except ValueError as e: raise XPUBError(str(e)) from e result = _parse_prefix(xpub_bytes[0:4]) if not result.is_public: raise XPUBError('Given xpub is an extended private key') return HDKey( path=path, network=result.network, depth=xpub_bytes[4], parent_fingerprint=xpub_bytes[5:9], index=int.from_bytes(xpub_bytes[9:13], byteorder='big'), parent=None, chain_code=xpub_bytes[13:45], fingerprint=hash160(pubkey.format(COMPRESSED_PUBKEY))[:4], xpriv=None, xpub=xpub, privkey=None, pubkey=pubkey, hint=result.hint, )
def _from_wif(self, wif): """Creates key from WIFC or WIF format key Check to_wif for the detailed process. From WIF is the reverse. Raises ------ ValueError if the checksum is wrong or if the WIF/WIFC is not from the configured network. """ wif_utf = wif.encode('utf-8') # decode base58check get key bytes plus checksum data_bytes = b58decode(wif_utf) key_bytes = data_bytes[:-4] checksum = data_bytes[-4:] # verify key with checksum data_hash = hashlib.sha256(hashlib.sha256(key_bytes).digest()).digest() if not checksum == data_hash[0:4]: raise ValueError('Checksum is wrong. Possible mistype?') # get network prefix and check with current setup network_prefix = key_bytes[:1] if NETWORK_WIF_PREFIXES[get_network()] != network_prefix: raise ValueError('Using the wrong network!') # remove network prefix key_bytes = key_bytes[1:] # check length of bytes and if > 32 then compressed # use this to instantite an ecdsa key if len(key_bytes) > 32: self.key = SigningKey.from_string(key_bytes[:-1], curve=SECP256k1) else: self.key = SigningKey.from_string(key_bytes, curve=SECP256k1)
def validate(self): """extended keys have their own validation""" if len(self.request.address) == 111: return self.validate_extended() """Validate the address.""" if 25 > len(self.request.address) > 35: return False try: abytes = base58check.b58decode(self.request.address, **self.request.extras) except ValueError: return False if self.network == '': return False checksum = sha256(sha256(abytes[:-4]).digest()).digest()[:4] if abytes[-4:] != checksum: return False return self.request.address == base58check.b58encode( abytes, **self.request.extras)
def _child_from_xpub(self, index: int, child_xpub: str) -> 'HDKey': """ Returns a new HDKey object based on the current object and the new child xpub. Don't call this directly, it's for child derivation. Args: index (int): the index of the child child_xpub (str): the child's xpub Returns HDKey: the new child object """ path: Optional[str] if self.path is not None: path = '{}/{}'.format(self.path, str(index)) else: path = None xpub_bytes = b58decode(child_xpub) pubkey = xpub_bytes[45:78] result = _parse_prefix(xpub_bytes[0:4]) if not result.is_public: raise XPUBError('Given xpub is an extended private key') return HDKey( path=path, network=result.network, depth=xpub_bytes[4], parent_fingerprint=xpub_bytes[5:9], index=int.from_bytes(xpub_bytes[9:13], byteorder='big'), parent=self, chain_code=xpub_bytes[13:45], fingerprint=hash160(pubkey)[:4], xpriv=None, xpub=child_xpub, privkey=None, pubkey=PublicKey(pubkey), hint=result.hint, )
def address_to_hex(address): output = encode_hex(base58check.b58decode(address))[0] return output[2:-8].decode() # drop magic byte and checksum
import base58check import hashlib from pycoin import key wallet = '1HammaXcmybjPK4yLJxWkCrYQHd3fyLcU7' # WIP key with random last 8 symbols wip_fake = '5JRd42nU1gL5wuDRgVRRTCdHRAhiF1tpuGfy2nm3YtN11111111' # Convert fake WIP key to the real secret key with checksum wipd_fake = base58check.b58decode(wip_fake) # Trim last 6 bytes (2 last bytes from secret key + checksum) wipd_fake_starting = wipd_fake[:-6] print(f'WIP fake : {wip_fake}') print(f'WIPd full : {wipd_fake.hex().upper()}') print(f'WIPd trim : {wipd_fake_starting.hex().upper()}\n') # Generate list of random bytes 00..FF bb = [bytes([b]) for b in range(256)] c = -1 exit(0) for i in bb: for j in bb: c += 1 # Add 2 random bytes to the secret key starting wipd_test = wipd_fake_starting + i + j # Calc SHA256(WIPd) h = hashlib.sha256() h.update(wipd_test)
def get_magic_byte(address): output = base58check.b58decode(address) output = encode_hex(output)[0].decode() return int(output[0:2], 16)
def getPubKeyHash(address): return base58check.b58decode(address)[1:-4].hex()