def subscribe_address(self, address, callback): """ Listen on an address for transactions. Since we can't validate unconfirmed txs we will only callback if the tx is announced by a majority of our peers or included in a block. """ def on_peer_announce(txhash): if self.subscriptions[txhash]["announced"] < self.subscriptions[ txhash]["ann_threshold"] and self.subscriptions[txhash][ "confirmations"] == 0: self.subscriptions[txhash]["announced"] += 1 if self.subscriptions[txhash][ "announced"] >= self.subscriptions[txhash][ "ann_threshold"]: callback(self.subscriptions[txhash]["tx"], self.subscriptions[txhash]["in_blocks"], self.subscriptions[txhash]["confirmations"]) self.subscriptions[txhash][ "last_confirmation"] = self.subscriptions[txhash][ "confirmations"] elif self.subscriptions[txhash][ "confirmations"] > self.subscriptions[txhash][ "last_confirmation"]: self.subscriptions[txhash][ "last_confirmation"] = self.subscriptions[txhash][ "confirmations"] callback(self.subscriptions[txhash]["tx"], self.subscriptions[txhash]["in_blocks"], self.subscriptions[txhash]["confirmations"]) self.subscriptions[address] = (len(self.peers) / 2, on_peer_announce) self.bloom_filter.insert(base58.decode(address)[1:21]) for peer in self.peers: if peer.protocol is not None: peer.protocol.load_filter()
def address_to_public_key_hash(address): binary_address = decode(address) # remove the 4 checksum bytes extended_address = binary_address[:-4] # remove version byte: 0x00 for Main Network hash160_address = extended_address[1:] return hash160_address
def address_to_public_key_hash_hex(address): binary_address = decode(address) # remove the 4 checksum bytes extended_address = binary_address[:-4] # remove version byte: 0x00 for Main Network hash160_address = extended_address[1:] public_key_hash_hex = str(binascii.hexlify(hash160_address)) return public_key_hash_hex
def address(address): pubkey_hash = base58.decode(address) # Strip off the version and checksum, database doesn't store them pubkey_hash = pubkey_hash[1:-4] outputs = (m.Output.query.options(db.joinedload('spent_tx'), db.joinedload('origin_tx')). filter_by(dest_address=pubkey_hash)) return render_template('address.html', outputs=outputs, address=address)
def address(address): pubkey_hash = base58.decode(address) # Strip off the version and checksum, database doesn't store them pubkey_hash = pubkey_hash[1:-4] outputs = (m.Output.query.options( db.joinedload('spent_tx'), db.joinedload('origin_tx')).filter_by(dest_address=pubkey_hash)) return render_template('address.html', outputs=outputs, address=address)
def decode_data(self): msg = str(self.encoded_edit.toPlainText()) if not msg: self.error('No data was input.') try: payload = base58.decode(msg) self.payload_edit.setPlainText(payload.encode('hex')) except Exception as e: self.error(str(e))
def unsubscribe_address(self, address): """ Unsubscribe to an address. Will update the bloom filter to reflect its state before the address was inserted. """ if address in self.subscriptions: self.bloom_filter.remove(base58.decode(address)[1:21]) for peer in self.peers: peer.protocol.load_filter() del self.subscriptions[address]
def from_str(s): """Takes a str and outputs an addr""" sanitized = apply_char_map(s) num = int(hexlify(decode(s)), 16) out = make_addr(num) out = encode(b'\x00' + out.to_bytes(24, 'big')) return out
def unsubscribe_address(self, address): """ Unsubscribe to an address. Will update the bloom filter to reflect its state before the address was inserted. """ if address in self.subscriptions: self.bloom_filter.remove(base58.decode(address)[1:21]) for peer in self.peers: if peer.protocol is not None: peer.protocol.load_filter() del self.subscriptions[address]
def format_query_str(cls, query_str): """ Takes a string, convert it to an object which can be used to query the Address class & returns it. Otherwise it returns False. """ try: pubkey_hash = base58.decode(query_str) except base58.InvalidBase58Error: return False else: # Strip off the version and checksum, database doesn't store them return pubkey_hash[1:-4]
def __init__(self, seed_bytes=None, key_string=None): assert (seed_bytes and not key_string) or (not seed_bytes and key_string), \ "Only provide one of seed_bytes or key_string, not both" if key_string: if not ECPrivateKey.is_valid(key_string): raise BadKeyStringError() decoded = base58.decode(key_string) seed_bytes = decoded[PREFIX_LENGTH:BODY_LENGTH] assert isinstance(seed_bytes, bytes) assert len(seed_bytes) == 32 self.__signer = ed25519.SigningKey(seed_bytes)
def hearWhispers(txid, access): rawtx = access.getrawtransaction(txid) decodedtx = access.decoderawtransaction(rawtx) vouts = decodedtx['vout'] whispers = [] for vout in vouts: address = vout['scriptPubKey']['addresses'][0] whisper = base58.decode(address)[1:-4] whispers.append(whisper) return whispers
def __init__(self, key_bytes=None, key_string=None): assert (key_bytes and not key_string) or (not key_bytes and key_string), \ "Only provide one of key_bytes or key_string, not both" if key_string: if not ECAddress.is_valid(key_string): raise BadKeyStringError() decoded = base58.decode(key_string) key_bytes = decoded[PREFIX_LENGTH:BODY_LENGTH] assert isinstance(key_bytes, bytes) assert len(key_bytes) == 32 self.__verifier = ed25519.VerifyingKey(key_bytes)
def decode(cls, string): """ Given a base-58 encoded object, decodes it and deserializes it, returning a new object containing the deserialized information Args: string (str): base-58 encoded string Returns: cls: a new object filled with the values that the string contained Raises: ValueError: if can't be decoded """ return cls.deserialize(base58.decode(string))
def validate(bitcoin_address): """Takes a string and returns true or false""" clen = len(bitcoin_address) if clen < 27 or clen > 35: # XXX or 34? return False try: bcbytes = decode(bitcoin_address) except InvalidBase58Error: return False if len(bcbytes) != 25: return False if not bcbytes[0] in [0, 111, 42]: return False # Compare checksum checksum = sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] if bcbytes[-4:] != checksum: return False # Encoded bytestring should be equal to the original address # For example '14oLvT2' has a valid checksum, but is not a valid btc address return bitcoin_address == encode(bcbytes)
def is_valid(cls, key_string: str): """ :param key_string: the EC private key string to be checked :return: `True` if `key_string` is a valid EC private key string in Es format, `False` otherwise """ if not isinstance(key_string, str): return False try: decoded = base58.decode(key_string) except base58.InvalidBase58Error: return False if len(decoded) != TOTAL_LENGTH or decoded[:PREFIX_LENGTH] != ECPrivateKey.PREFIX: return False checksum_claimed = decoded[BODY_LENGTH:] temp_hash = sha256(decoded[:BODY_LENGTH]).digest() checksum_actual = sha256(temp_hash).digest()[:CHECKSUM_LENGTH] return checksum_actual == checksum_claimed
def subscribe_address(self, address, callback): """ Listen on an address for transactions. Since we can't validate unconfirmed txs we will only callback if the tx is announced by a majority of our peers. """ def on_peer_announce(txhash): if self.subscriptions[txhash]["announced"] < self.subscriptions[txhash]["ann_threshold"]: self.subscriptions[txhash]["announced"] += 1 if self.subscriptions[txhash]["announced"] >= self.subscriptions[txhash]["ann_threshold"]: callback(self.subscriptions[txhash]["tx"], self.subscriptions[txhash]["confirmations"]) self.subscriptions[txhash]["last_confirmation"] = self.subscriptions[txhash]["confirmations"] elif self.subscriptions[txhash]["confirmations"] > self.subscriptions[txhash]["last_confirmation"]: self.subscriptions[txhash]["last_confirmation"] = self.subscriptions[txhash]["confirmations"] callback(self.subscriptions[txhash]["tx"], self.subscriptions[txhash]["in_blocks"], self.subscriptions[txhash]["confirmations"]) self.subscriptions[address] = (len(self.peers)/2, on_peer_announce) self.bloom_filter.insert(base58.decode(address)[1:21]) for peer in self.peers: peer.protocol.load_filter()
def is_valid(cls, address: str): """ :param address: the EC address string to be checked :return: `True` if `address` is a valid EC Address string in EC format, `False` otherwise """ if not isinstance(address, str): return False try: decoded = base58.decode(address) except base58.InvalidBase58Error: return False if len(decoded) != TOTAL_LENGTH or decoded[:PREFIX_LENGTH] != ECAddress.PREFIX: return False checksum_claimed = decoded[BODY_LENGTH:] temp_hash = sha256(decoded[:BODY_LENGTH]).digest() checksum_actual = sha256(temp_hash).digest()[:CHECKSUM_LENGTH] return checksum_actual == checksum_claimed
def __init__(self, key_bytes=None, key_string=None): # Check that we only get one of the two params if not ((key_bytes and not key_string) or (not key_bytes and key_string)): raise InvalidParamsError( "Only provide one of seed bytes or key_string, not both.") # Set default to lowest key level. self.key_level = 4 if key_string: if not ServerIDPublicKey.is_valid(key_string): raise BadKeyStringError self.key_level = int(key_string[2]) decoded = base58.decode(key_string) key_bytes = decoded[PREFIX_LENGTH:BODY_LENGTH] if not isinstance(key_bytes, bytes) and len(key_bytes) == 32: raise BadKeyBytesError self.__verifier = ed25519.VerifyingKey(key_bytes)
def __init__(self, key_bytes=None, rcd_hash=None, address_string=None): """Tries to initialize a FactoidAddress using the key_bytes, then the rcd_hash, then the address string.""" assert key_bytes or address_string or rcd_hash, "Must provide key_bytes, address_string, or rcd_hash" self._verifier = None self.rcd_hash = None if key_bytes is not None: assert isinstance(key_bytes, bytes) assert len(key_bytes) == 32 self._verifier = ed25519.VerifyingKey(key_bytes) temp_hash = sha256(b"\x01" + key_bytes).digest() self.rcd_hash = sha256(temp_hash).digest() if rcd_hash is not None: if type(rcd_hash) not in {bytes, bytearray} or len(rcd_hash) != 32: raise ValueError("rcd_hash must be bytes object of length 32") self.rcd_hash = rcd_hash elif address_string is not None: if not FactoidAddress.is_valid(address_string): raise BadKeyStringError() decoded = base58.decode(address_string) self.rcd_hash = decoded[PREFIX_LENGTH:BODY_LENGTH]
def __init__(self, seed_bytes=None, key_string=None): # Check that we only get one of the two params if not ((seed_bytes and not key_string) or (not seed_bytes and key_string)): raise InvalidParamsError( "Only provide one of seed bytes or key_string, not both.") # Default to lowest key level. self.key_level = 4 if key_string: if not ServerIDPrivateKey.is_valid(key_string): raise BadKeyStringError # Get level from third character self.key_level = int(key_string[2]) decoded = base58.decode(key_string) seed_bytes = decoded[PREFIX_LENGTH:BODY_LENGTH] if not isinstance(seed_bytes, bytes) and len(seed_bytes) == 32: raise BadKeyBytesError self.__signer = ed25519.SigningKey(seed_bytes)
def is_valid(cls, pub_key: str): """ :param pub_key: the ServerID public key to be checked :return: `True` if `pub_key` is a valid ServerID public key in string format; `False` otherwise """ if not isinstance(pub_key, str): return False try: decoded = base58.decode(pub_key) except base58.InvalidBase58Error: return False if len( decoded ) != TOTAL_LENGTH or decoded[: PREFIX_LENGTH] not in ServerIDPublicKey.PREFIXES: return False checksum_claimed = decoded[BODY_LENGTH:] temp_hash = sha256(decoded[:BODY_LENGTH]).digest() checksum_actual = sha256(temp_hash).digest()[:CHECKSUM_LENGTH] return checksum_actual == checksum_claimed
def validate_address(self, addr): addrbytes = base58.decode(addr) return addrbytes[-4:] == sha256(sha256(addrbytes[:-4]).digest()).digest()[:4]
def test_empty_decode(self): data = decode("1") self.assertEqual(data, b"\0")
def test_leadingz_decode(self): data = decode("11StV1DL6CwTryKyV") self.assertEqual(data, b"\0\0hello world")
def test_simple_decode(self): data = decode("StV1DL6CwTryKyV") self.assertEqual(data, b"hello world")
dict: test cases, containing a real address, and the supposed network and type """ # Testing if __name__ == "__main__": # Test all addresses types and check if guesses are OK print("Testing Addresses module") # Loop and test for case in CASES: # Initialize test case address_str, net, address_type, others = case print(" Testing Address %s" % (address_str)) print(" -> Net: %s, Type: %s" % (net.name, address_type.name)) # Some variables address_bytes = base58.decode(address_str) # Test decoding and deserializing address_obj = Address.decode(address_str) print(" -> Decode test: ", end="") if address_obj.type == address_type and address_obj.network == net: print("pass") else: raise ValueError("failed. Network or type invalid: %s / %s" % (address_obj.net, address_obj.type)) print(" -> Guessed byte-prefix: %s" % address_obj.prefix.hex()) # Test encoding and serializing address_prefix = address_obj.prefix address_value = address_bytes[len(address_prefix):] print(" -> Encode test: ", end="") address_obj = Address(addr_prefix=address_prefix, value=address_value) address_encoded = address_obj.encode()
) #This is the delay to be used for the redeem script and to be actually used for our output P2SH_from_address = sys.argv[ 3] #This is the address where we should get the funds from P2PKH_to_address = sys.argv[ 4] #This is the address where we will send the funds to #We will work on testnet SelectParams('testnet') #Based on its length we should know if the received key is a priv or pub key. #Priv key is either 51 or 52 hex long. Compressed pubkey is 66 hex long, uncompressed:130 if len(seckey) < 53: #here comes a code that creates a public key based on the received private key #we decode_hex_priv = b2x( decode(seckey)) #Remove Base58 encoding and turn byte sting into hex raw_priv = decode_hex_priv[ 2:66] # remove network byte and compression+checksum flags if len( decode_hex_priv ) == 76: #this is a compressed key (network_id+key+comp_flag+checksum seckey_pub = CKey(x(raw_priv)).pub key_received = "compressed private key" else: seckey_pub = CKey(x(raw_priv), compressed=False ).pub #when uncompressed pub key is uncompressed too key_received = "uncompressed private key" else: if len(seckey) < 130: key_received = "compressed public key" else: key_received = "uncompressed public key" seckey_pub = x(
def extract(address): """Returns original form of bitcoin address payload.""" return base58.decode(address)[1:-4]
def test_bitcoin_wallet_address_correct(): address = Bitcoin.get_wallet().address assert address.startswith('1') assert encode(decode(address)) == address
def decodeWalletImportFormat(walletImportFormatString, blockChain): """ Returns a tuple: (privKey, compressed) where `privKey` is the private key in binary format and `compressed` is a bool indicating whether or not the corresponding public key is compressed This function currently supports bitcoin mainnet and testnet. """ fullString = decode(walletImportFormatString) privkey = fullString[:-4] if fullString[-4:] != hashlib.sha256( hashlib.sha256(privkey).digest()).digest()[:4]: raise Exception( "When trying to decode one of your private keys, the wallet-import-format checksum was wrong." ) #checksum passed. # If you aren't very familiar with Wallet import format then this is going to be pretty confusing # https://en.bitcoin.it/wiki/Wallet_import_format if blockChain == 'bitcoin': if privkey[0:1] != b'\x80': # If the first byte isn't hex 80 raise Exception( "When trying to decode one of your private keys, the checksum passed but the key doesn\'t begin with hex 80. You are using the 'bitcoin' blockChain. Perhaps you meant to use testnet?" ) # The first character must be a 5 for uncompressed keys OR K or L for compressed keys if walletImportFormatString[0] == "5": compressed = False elif walletImportFormatString[0] in ["K", "L"]: compressed = True # We need to drop the last byte which should be \x01 if privkey[33:34] != b'\x01': raise Exception( "Your decoded compressed WIF key did not end with a \x01 byte." ) privkey = privkey[:-1] else: raise Exception( "In mainnet mode, the private key must start with 5, K, or L. Or it must be in Hex." ) return (privkey[1:], compressed) elif blockChain.startswith('testnet'): if privkey[0:1] != b'\xEF': raise Exception( "When trying to decode one of your private keys, the checksum passed but the key doesn\'t begin with hex EF. You are using a 'testnet' blockChain. Perhaps you meant to use the 'bitcoin' blockChain?" ) if walletImportFormatString[0] == "9": compressed = False elif walletImportFormatString[0] == "c": compressed = True # We need to drop the last byte which should be \x01 if privkey[33:34] != b'\x01': raise Exception( "Your decoded compressed WIF key did not end with a \x01 byte." ) privkey = privkey[:-1] else: raise Exception( "In testnet mode, the private key must start with 9 or c. Or it must be in Hex." ) return (privkey[1:], compressed) else: raise Exception("'blockChain' argument is not set properly.")
def address_to_raw_tx_data(a): assert len(a) == 34 a_hex = base58.decode(a).hex() return push_data(a_hex) + a_hex