Ejemplo n.º 1
0
def generate_sin(master_key):
    """Generates a type 2 'Secure Identity Number' using the bip32 master public key"""
    prefix = 0x0F
    sin_type = 0x02
    # Convert master key to hex if necessary
    try:
        master_key = unhexlify(master_key)
    except:
        pass

    # Step 1 (SHA-256 of public key)
    step_1 = sha256(master_key.encode('utf-8')).hexdigest()
    # Step 2 (RIPEMD-160 of Step 1)
    step_2 = ripemd160(unhexlify(step_1))
    # Step 3 (Prefix + SIN_Version + Step 2)
    step_3 = '{0:02X}{1:02X}{2}'.format(prefix, sin_type, step_2)
    # Step 4 (Double SHA-256 of Step 3)
    step_4_1 = unhexlify(step_3)
    step_4_2 = sha256(step_4_1).hexdigest()
    step_4_3 = unhexlify(step_4_2)
    step_4 = sha256(step_4_3).hexdigest()
    # Step 5 (Checksum), first 8 characters
    step_5 = step_4[0:8]
    # Step 6 (Step 5 + Step 3)
    step_6 = step_3 + step_5
    # Base58-encode to receive final SIN
    sin = base58.encode(unhexlify(step_6))

    return sin
Ejemplo n.º 2
0
def deriveAddress(privateKey, compressed, blockChain):
    """
    Turn a private key into an address.
    privateKey must be in binary format.
    """
    privKey = CECKey()
    privKey.set_secretbytes(privateKey)
    privKey.set_compressed(compressed)
    publicKey = privKey.get_pubkey()
    hash1 = hashlib.sha256(publicKey).digest()

    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(hash1)
    ripe = ripemd160.digest()

    if blockChain == 'bitcoin':
        ripeWithNetworkPrefix = b'\x00' + ripe
    elif blockChain.startswith('testnet'):
        ripeWithNetworkPrefix = b'\x6F' + ripe
    else:
        raise Exception("'blockChain' parameter is not set correctly")

    checksum = hashlib.sha256(
        hashlib.sha256(ripeWithNetworkPrefix).digest()).digest()[:4]
    binaryBitcoinAddress = ripeWithNetworkPrefix + checksum
    numberOfZeroBytesOnBinaryBitcoinAddress = 0
    while binaryBitcoinAddress[0:1] == b'\x00':  # while the first byte is null
        numberOfZeroBytesOnBinaryBitcoinAddress += 1
        binaryBitcoinAddress = binaryBitcoinAddress[
            1:]  # take off the first byte
    base58encoded = encode(binaryBitcoinAddress)  # encode into base58
    return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def wif_from_key(key):
    p = k.prikey
    assert len(p) == 32
    p = '\x80' + p #+ '\x01'
    h = Hash(p)
    chk = h[:4]
    return base58.encode(p+chk)
Ejemplo n.º 4
0
    def reply_with_list_of_known_workers(self, message):

        fr = base58.encode(message['from'])

        addr = '/p2p-circuit/ipfs/' + fr

        # print("sending list of known workers to " + addr)

        # First: adding worker that made request to my list of known workers (just in case i don't have it)
        try:
            self.api.swarm_connect(addr)
        except:
            ""
            # print("Failed to reconnect in the opposite direciton to:" + addr)

        # fetch list of openmined workers i know about
        workers = self.worker.get_openmined_nodes()

        # encode list of openmined workers i know about
        workers_json = json.dumps(workers)

        # get callback channel for sending messages directly to whomever requested the list of om workers i know about
        callback_channel = channels.list_workers_callback(fr)

        # print(f'Sending List: {callback_channel} {workers_json}')

        # send encoded list of openmined workers i know about to the individual who requested it
        self.worker.publish(callback_channel, workers_json)
Ejemplo n.º 5
0
def wif_from_key(key):
    p = k.prikey
    assert len(p) == 32
    p = '\x80' + p  #+ '\x01'
    h = Hash(p)
    chk = h[:4]
    return base58.encode(p + chk)
Ejemplo n.º 6
0
    def listen_to_channel_impl(self,
                               channel,
                               handle_message,
                               init_function=None,
                               ignore_from_self=False):
        """
        Do not call directly.  Use listen_to_channel or listen_to_channel_sync instead.
        """

        first_proc = True

        if channel not in self.subscribed_list:
            print(f"SUBSCRIBING TO {channel}")
            new_messages = self.api.pubsub_sub(topic=channel, stream=True)
            self.subscribed_list.append(channel)
        else:
            print(f"ALREADY SUBSCRIBED TO {channel}")
            return

        for m in new_messages:
            if init_function is not None and first_proc:
                init_function()
                first_proc = False

            message = self.decode_message(m)
            if message is not None:
                fr = base58.encode(message['from'])

                if not ignore_from_self or fr != self.id:
                    out = handle_message(message)
                    if (out is not None):
                        return out
                else:
                    print("ignored message from self")
Ejemplo n.º 7
0
    def listen_to_channel_impl(self,
                               channel,
                               handle_message,
                               init_function=None,
                               ignore_from_self=False):
        """
        Do not call directly.  Use listen_to_channel or listen_to_channel_sync instead.
        """

        first_proc = True

        if channel not in self.subscribed_list:

            # print(f"SUBSCRIBING TO {channel}")
            new_messages = self.api.pubsub_sub(topic=channel, stream=True)
            self.subscribed_list.append(channel)

        else:
            print(f"ALREADY SUBSCRIBED TO {channel}")
            return

        for m in new_messages:
            if init_function is not None and first_proc:
                init_function()
                first_proc = False

            message = self.decode_message(m)
            if message is not None:
                fr = utils.derive_id(self.node_type,
                                     base58.encode(message['from']))
                if fr == self.id and ignore_from_self:
                    print('ignored message from self')
                    return None

                return handle_message(message)
Ejemplo n.º 8
0
    def listen_to_channel_impl(self,
                               channel,
                               handle_message,
                               init_function=None,
                               ignore_from_self=False):
        """
        Do not call directly.  Use listen_to_channel or listen_to_channel_sync instead.
        """

        first_proc = True

        if channel not in self.subscribed_list:
            new_messages = self.api.pubsub_sub(topic=channel, stream=True)
            self.subscribed_list.append(channel)

        else:
            return

        # new_messages is a generator which will keep yield new messages until
        # you return from the loop. If you do return from the loop, we will no
        # longer be subscribed.
        for m in new_messages:
            if init_function is not None and first_proc:
                init_function()
                first_proc = False

            message = self.decode_message(m)
            if message is not None:
                fr = base58.encode(message['from'])
                if not ignore_from_self or fr != self.id:
                    out = handle_message(message)
                    if out is not None:
                        return out
                else:
                    print('ignore mssage from self')
Ejemplo n.º 9
0
def OPsPerLink(link):
    try:
        bs = mini_node.BitcoinSocket(link)
        if bs.conn_ref or not bs.connect():
            raise Exception  # to be added to timeouts list
        print(threading.current_thread().name,"waiting for ack: ", link)
        bs.listen_until_acked()
        print(threading.current_thread().name,"sending inv: ", link)
        txHash = bs.send_transaction()
        print(threading.current_thread().name,"finished: ", link)
    except Exception as e:
        strE = str(e)
        if ("BitcoinSocket issue " + strE) not in errorSet:
            errorSet.append("BitcoinSocket issue " + strE)
        print("An error occured", link)
        print(threading.current_thread().name,"finished: ", link)
        # print(e, "An error occured", link)
        print(errorSet)
        timeouts.append(link)
        return

    for x in range(0,5):
        try:
            r = requests.get('https://api.blockcypher.com/v1/btc/main/txs/' + base58.encode(txHash))
            if r.status_code == 200:
                break
        except Exception as e:
            strE = str(e)
            if ("request issue here " + strE) not in errorSet:
                errorSet.append("request issue here " + strE)
            print("request error" + str(e) + base58.encode(txHash))
            print(errorSet)
            # print("retrying api call for the ",x+1,"th time")
            time.sleep(2)
            r = "still exception after 5 API calls"
    transJSON = r.json()
    if r == "still exception after 5 API calls" or r.status_code == 404:
        notInDB.append(link)
    elif r != "still exception after 5 API calls":
        if 'receive_count' in transJSON:
            if r.json()['receive_count'] == 0:
                inDBZeroCount.append(link)
            elif r.json()['receive_count'] > 0:
                inDBMoreThanOneCount.append(link)
    print(errorSet)
    # bs.listen_forever()
    return
    def address(self):
        """Returns the base58 encoded representation of this address"""
        if self._address is None:
            version = b'\x00' if self.type == "normal" else b'\x05'
            checksum = double_sha256(version + self.hash)

            self._address = base58.encode(version + self.hash + checksum[:4])
        return self._address
Ejemplo n.º 11
0
    def address(self):
        """Returns the base58 encoded representation of this address"""
        if self._address is None:
            version = b'\x00' if self.type == "normal" else b'\x05'
            checksum = double_sha256(version + self.hash)

            self._address = base58.encode(version + self.hash + checksum[:4])
        return self._address
Ejemplo n.º 12
0
    def get_address(self, version_bytes=[b'\x00', b'\x05']):
        """Returns the base58 encoded representation of this address"""
        if self._address is None:
            version = version_bytes[0] if self.type == "normal" else version_bytes[1]
            checksum = double_sha256(version + self.hash)

            self._address = base58.encode(version + self.hash + checksum[:4])
        return self._address
Ejemplo n.º 13
0
def computeBitcoinAddress(pubkey, using_testnet):
    hash256 = hashlib.sha256(pubkey).digest()
    hasher160 = hashlib.new('ripemd160')
    hasher160.update(hash256)
    hash160 = hasher160.digest()
    addr_raw = get_version_byte(using_testnet) + hash160
    addr_raw_checksum = addr_raw + ripemd_bc_checksum(addr_raw)
    addr = base58.encode(addr_raw_checksum).encode('utf8')
    return addr
Ejemplo n.º 14
0
    def list_models(self, message):
        task = message['data']
        fr = base58.encode(message['from'])

        if fr == self.id:
            return

        my_best = utils.best_model_for_task(task)
        if my_best is not None:
            self.send_model(task, my_best)
Ejemplo n.º 15
0
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 
Ejemplo n.º 16
0
    def found_task(self, message):
        fr = base58.encode(message['from'])

        tasks = json.loads(message['data'])
        for task in tasks:
            # utils.store_task(task['name'], task['address'])
            name = task['name']
            addr = task['address']

            hbox = widgets.HBox([widgets.Label(name), widgets.Label(addr)])
            self.all_tasks.children += (hbox, )
Ejemplo n.º 17
0
def encode_address(hash160, network):
    if network == "mainnet":
        version = 5
    elif network == "testnet":
        version = 196
    else:
        raise ValueError("Unknown network")

    data = bytes([version]) + hash160
    checksum = Hash(data)[0:4]
    return encode(data + checksum)
Ejemplo n.º 18
0
def encode_address(hash160, network):
    if network == "mainnet":
        version = 5
    elif network == "testnet":
        version = 196
    else:
        raise ValueError("Unknown network")

    data = bytes([version]) + hash160
    checksum = Hash(data)[0:4]
    return encode(data + checksum)
    def address(self):
        """Returns the base58 encoded representation of this address"""
        if self._address is None:
            if self.type == 'normal':
                version = self.blockchain_type.p2pkh_addr_version
            else:
                version = self.blockchain_type.p2sh_addr_version
            checksum = double_sha256(version + self.hash)

            self._address = base58.encode(version + self.hash + checksum[:4])
        return self._address
Ejemplo n.º 20
0
def _to_base58_string(prefixed_key: bytes):
    """
    Convert prefixed_key bytes into Fs/FA strings with a checksum

    :param prefixed_key: the Factoid private key or Factoid address prefixed with the appropriate bytes
    :return: a Factoid private key string or Factoid address
    """
    prefix = prefixed_key[:PREFIX_LENGTH]
    assert prefix == FactoidAddress.PREFIX or prefix == FactoidPrivateKey.PREFIX, "Invalid key prefix."
    temp_hash = sha256(prefixed_key[:BODY_LENGTH]).digest()
    checksum = sha256(temp_hash).digest()[:CHECKSUM_LENGTH]
    return base58.encode(prefixed_key + checksum)
Ejemplo n.º 21
0
def _to_base58_string(prefixed_key: bytes):
    """
    Convert prefixed_key bytes into Es/EC strings with a checksum

    :param prefixed_key: the EC private key or EC address prefixed with the appropriate bytes
    :return: a EC private key string or EC address
    """
    prefix = prefixed_key[:PREFIX_LENGTH]
    assert prefix == ECAddress.PREFIX or prefix == ECPrivateKey.PREFIX, 'Invalid key prefix.'
    temp_hash = sha256(prefixed_key[:BODY_LENGTH]).digest()
    checksum = sha256(temp_hash).digest()[:CHECKSUM_LENGTH]
    return base58.encode(prefixed_key + checksum)
Ejemplo n.º 22
0
    def encode_data(self):
        payload = str(self.payload_edit.toPlainText())
        if not payload:
            self.error('No data was input.')

        if is_hex(payload):
            payload = format_hex_string(payload, with_prefix=False).decode('hex')

        try:
            msg = base58.encode(payload)
            self.encoded_edit.setPlainText(msg)
        except Exception as e:
            self.error(str(e))
Ejemplo n.º 23
0
def public_key_hex_to_address(public_key_hex):
    public_key_bytearray = bytearray.fromhex(public_key_hex)
    # Perform SHA-256 and RIPEMD-160 hashing on public key
    hash160_address = myhash160(public_key_bytearray)
    # add version byte: 0x00 for Main Network
    extended_address = '\x00' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    address = encode(binary_address)
    return address
Ejemplo n.º 24
0
def public_key_hex_to_address(public_key_hex):
    public_key_bytearray = bytearray.fromhex(public_key_hex)
    # Perform SHA-256 and RIPEMD-160 hashing on public key
    hash160_address = myhash160(public_key_bytearray)
    # add version byte: 0x00 for Main Network
    extended_address = '\x00' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    address = encode(binary_address)
    return address
Ejemplo n.º 25
0
def _to_base58_string(prefixed_key: bytes):
    """
    Convert prefixed_key bytes into sk1/id strings with a checksum.

    :param prefixed_key: the sk1 private key or id public key prefixed with the appropriate bytes
    :return: a sk1 private key string or id public key string
    """
    prefix = prefixed_key[:PREFIX_LENGTH]
    if not (prefix in ServerIDPublicKey.PREFIXES
            or prefix in ServerIDPrivateKey.PREFIXES):
        raise InvalidPrefixError
    temp_hash = sha256(prefixed_key[:BODY_LENGTH]).digest()
    checksum = sha256(temp_hash).digest()[:CHECKSUM_LENGTH]
    return base58.encode(prefixed_key + checksum)
Ejemplo n.º 26
0
def squeeze(data):
	"""Forms a valid bitcoin address around the given data bytes by
	postfixing them after the version byte, hashing this combination, 
	postfixing that hash, and base58 encoding the resulting string.
	"""
	if len(data) != BYTES_IN_PAYLOAD:
		raise BaseException('invalid payload length: %d - should be %d' % (len(data), BYTES_IN_PAYLOAD))
	if bitcoin.core.coreparams.NAME == 'mainnet':
		data = chr(0) + data
	elif bitcoin.core.coreparams.NAME == 'testnet':
		data = chr(111) + data 
	else:
		raise 'invalid network mode'
	data += bitcoin.core.Hash(data)[0:4]
	return base58.encode(data)
Ejemplo n.º 27
0
    def list_tasks(self, message):
        fr = base58.encode(message['from'])

        if not os.path.exists(f"{Path.home()}/.openmined/tasks.json"):
            return

        with open(f"{Path.home()}/.openmined/tasks.json", "r") as task_list:
            string_list = task_list.read()
            tasks = json.loads(string_list)
            # for t in tasks:
                # self.listen_for_models(t['name'])

        callback_channel = channels.list_tasks_callback(fr)
        print(f'?!?!?!?!?! {callback_channel} {string_list}')
        self.publish(callback_channel, string_list)
Ejemplo n.º 28
0
def addresses_to_vault_address(address, master_address, timeout, maxfees):
    vault_script = create_vault_script(address, master_address, timeout, maxfees)
    hash160_address = myhash160(vault_script)
    # add version byte: 0x08 for vault address
    extended_address = '\x08' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4.
    # This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    # encode in base-58 format
    vault_address = encode(binary_address)
    return str(vault_address)
Ejemplo n.º 29
0
def speakWhispers(whispers):
    addresses = []
    for whisper in whispers:
        version = B'\x00'
        data = version + whisper

        first_pass = sha256(data).digest()
        second_pass = sha256(first_pass).digest()
        checksum = second_pass[:4]

        cat = data + checksum
        address = base58.encode(cat)

        addresses.append(address)

    return addresses
Ejemplo n.º 30
0
def addresses_to_vault_address(address, master_address, timeout, maxfees):
    vault_script = create_vault_script(address, master_address, timeout,
                                       maxfees)
    hash160_address = myhash160(vault_script)
    # add version byte: 0x08 for vault address
    extended_address = '\x08' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4.
    # This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    # encode in base-58 format
    vault_address = encode(binary_address)
    return str(vault_address)
Ejemplo n.º 31
0
def speakWhispers(whispers):
    addresses = []
    for whisper in whispers:
        version = B'\x00'
        data = version + whisper

        first_pass = sha256(data).digest()
        second_pass = sha256(first_pass).digest()
        checksum = second_pass[:4]

        cat = data + checksum
        address = base58.encode(cat)

        addresses.append(address)

    return addresses
Ejemplo n.º 32
0
    def address(self):
        """Returns the encoded representation of this address.
        If SegWit, it's encoded using bech32, otherwise using base58
        """
        if self._address is None:
            if self.type != "bech32":
                version = b'\x00' if self.type == "normal" else b'\x05'
                checksum = double_sha256(version + self.hash)

                self._address = base58.encode(version + self.hash +
                                              checksum[:4])
            else:
                bech_encoded = CBech32Data.from_bytes(self._segwit_version,
                                                      self._hash)
                self._address = str(bech_encoded)
        return self._address
Ejemplo n.º 33
0
    def list_models(self, message):
        """
        for a given task - return the models you know to perform the best for that task.
        """

        task = message['data']
        fr = base58.encode(message['from'])

        print(f'listing models {fr} {self.id}')

        if fr == self.id:
            return

        my_best = utils.best_model_for_task(task)
        if my_best is not None:
            self.send_model(task, my_best)
Ejemplo n.º 34
0
Archivo: tree.py Proyecto: vbawa/Grid
    def list_tasks(self, message):
        """
        Tell the network about all of the tasks you know about.
        """
        fr = base58.encode(message['from'])

        # Tasks are stored in a tasks.json file.
        if not os.path.exists(f"{Path.home()}/.openmined/tasks.json"):
            return

        with open(f"{Path.home()}/.openmined/tasks.json", "r") as task_list:
            string_list = task_list.read()

        # Don't broadcast the known tasks to the entire network.  Someone will
        # Ask the network for known tasks, and you respond to them directly.
        callback_channel = channels.list_tasks_callback(fr)
        self.publish(callback_channel, string_list)
Ejemplo n.º 35
0
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)
Ejemplo n.º 36
0
Archivo: tree.py Proyecto: hung084/Grid
    def discovered_tasks(self, tasks):
        """
        people publish new tasks to the network which get processed by this method
        a task is a json object which has a data directory  - and that data gets processed by an
        adapter which is also sent over the wire.
        """

        print(f'{Fore.WHITE}{Back.BLACK} TASKS {Style.RESET_ALL}')
        print(f'From\t\t\t\tName\t\t\t\tAddress')
        print(
            '=================================================================='
        )

        data = json.loads(tasks['data'])
        fr = base58.encode(tasks['from'])

        for task in data:
            name = task['name']
            addr = task['address']

            print(f'{fr}\t{name}\t{addr}')

            t = self.api.get_json(addr)
            if 'data_dir' in t.keys():
                data_dir = t['data_dir']
                if os.path.exists(f'data/{data_dir}'):
                    self.listen_for_models(name)
                    utils.store_task(name, addr)
                else:
                    print(
                        f"DON'T HAVE DATA FOR {name} DATA DIRECTORY: {data_dir}"
                    )
            elif 'adapter' in t.keys():
                self.listen_for_models(name)
                utils.store_task(name, addr)

                self.load_adapter(t['adapter'])
            # 04/20/2018: Check for dataset
            elif 'dataset' in t.keys():
                self.listen_for_models(name)
                utils.store_task(name, addr)
Ejemplo n.º 37
0
def pending_tx_output_script_to_address(script):
    version = binascii.unhexlify('00')
    if script[-2:] == binascii.unhexlify("88AC"):
        version = binascii.unhexlify('00')
    elif script[:1] == binascii.unhexlify("76"):
        version = binascii.unhexlify('08')
    else:
        raise Exception("Error unknown scritpt: ", binascii.hexlify(script))

    # fix this into a single complete module
    hash160_address = binascii.unhexlify(output_script_to_public_key_hash(script))
    # add version byte: 0x00 for Main Network
    extended_address = version + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address
    binary_address = extended_address + checksum
    # encode in base 58 format
    address = encode(binary_address)
    return address
Ejemplo n.º 38
0
def getnewaddress():
    # Generate public and private keys
    key = Key()
    key.generate()
    key.set_compressed(True)
    private_key = key.get_privkey()
    public_key = key.get_pubkey()
    private_key_hex = private_key.encode('hex')
    public_key_hex = public_key.encode('hex')
    public_key_bytearray = bytearray.fromhex(public_key_hex)
    # Perform SHA-256 and RIPEMD-160 hashing on public key
    hash160_address = myhash160(public_key_bytearray)
    # add version byte: 0x00 for Main Network
    extended_address = '\x00' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    # Convert the result from a byte string into a base58 string using Base58Check encoding.
    address = encode(binary_address)
    return public_key, private_key, address
Ejemplo n.º 39
0
    def discovered_tasks(self, tasks):
        print(f'{Fore.WHITE}{Back.BLACK} TASKS {Style.RESET_ALL}')
        print(f'From\t\t\t\tName\t\t\t\tAddress')
        print('==================================================================')

        data = json.loads(tasks['data'])
        fr = base58.encode(tasks['from'])

        for task in data:
            name = task['name']
            addr = task['address']

            print(f'{fr}\t{name}\t{addr}')

            data_dir = self.api.get_json(addr)['data_dir']

            # TODO should only listen on task channels that which i have data for

            if os.path.exists(f'data/{data_dir}'):
                self.listen_for_models(name)
                utils.store_task(name, addr)
            else:
                print(f"DON'T HAVE DATA FOR {name} DATA DIRECTORY: {data_dir}")
Ejemplo n.º 40
0
def pending_tx_output_script_to_address(script):
    version = binascii.unhexlify('00')
    if script[-2:] == binascii.unhexlify("88AC"):
        version = binascii.unhexlify('00')
    elif script[:1] == binascii.unhexlify("76"):
        version = binascii.unhexlify('08')
    else:
        raise Exception("Error unknown scritpt: ", binascii.hexlify(script))

    # fix this into a single complete module
    hash160_address = binascii.unhexlify(
        output_script_to_public_key_hash(script))
    # add version byte: 0x00 for Main Network
    extended_address = version + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address
    binary_address = extended_address + checksum
    # encode in base 58 format
    address = encode(binary_address)
    return address
Ejemplo n.º 41
0
def getnewaddress():
    # Generate public and private keys
    key = Key()
    key.generate()
    key.set_compressed(True)
    private_key = key.get_privkey()
    public_key = key.get_pubkey()
    private_key_hex = private_key.encode('hex')
    public_key_hex = public_key.encode('hex')
    public_key_bytearray = bytearray.fromhex(public_key_hex)
    # Perform SHA-256 and RIPEMD-160 hashing on public key
    hash160_address = myhash160(public_key_bytearray)
    # add version byte: 0x00 for Main Network
    extended_address = '\x00' + hash160_address
    # generate double SHA-256 hash of extended address
    hash_address = myhash(extended_address)
    # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    checksum = hash_address[:4]
    # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address.
    binary_address = extended_address + checksum
    # Convert the result from a byte string into a base58 string using Base58Check encoding.
    address = encode(binary_address)
    return public_key, private_key, address
Ejemplo n.º 42
0
def get_address(public_key: str) -> str:
    """Get address based on the public key"""
    return base58.encode(public_key)
Ejemplo n.º 43
0
def base58_check_encode(s, version=b'\x00'):
	vs = version + s
	check = dsha256(vs)[:4]
	return base58.encode(vs + check)
def address_from_key(key):
    p = k.get_pubkey()
    pkh = '\x00' + Hash160(p)
    #print 'pkh', pkh
    chk = Hash(pkh)[:4]
    return base58.encode(pkh+chk)
Ejemplo n.º 45
0
 def signatures(self, value):
     names = sorted(self.private_keys.keys())
     #return dict((name, self.sign(name, value)) for name in names)
     s = ((name, base58.encode(self.sign(name, value))) for name in names)
     return dict(s)
Ejemplo n.º 46
0
 def signatures(self, value):
     names = sorted(self.private_keys.keys())
     return {name: base58.encode(self.sign(name, value)) for name in names}
Ejemplo n.º 47
0
hash160_address = MyHash160(public_key)

# add version byte: 0x00 for Main Network
extended_address = '\x00' + hash160_address

# generate double SHA-256 hash of extended address
hash_address = MyHash(extended_address)

# Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
checksum = hash_address[:4]

# Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address.
binary_address = extended_address + checksum

# Convert the result from a byte string into a base58 string using Base58Check encoding.
address = encode(binary_address)
print address


"""
How to create Bitcoin Address

0 - Having a private ECDSA key

   18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725
1 - Take the corresponding public key generated with it (65 bytes, 1 byte 0x04, 32 bytes corresponding to X coordinate, 32 bytes corresponding to Y coordinate)

   0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
2 - Perform SHA-256 hashing on the public key

   600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408