How to use the base58.b58decode function in base58

To help you get started, we’ve selected a few base58 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wavesplatform / nanos-app-waves / python / ledger-waves.py View on Github external
# from: 3PDCeakWckRvK5vVeJnCy1R2rE1utBcJMwt
        # to: 3PMpANFyKGBwzvv1UVk2KdN23fJZ8sXSVEK
        # attachment: privet
        # fee: 0.001
        # fee asset: WAVES
        some_transfer_bytes = build_transfer_bytes('4ovEU8YpbHTurwzw8CDZaCD7m6LpyMTC4nrJcgDHb4Jh',
                                                   pw.Address('3PMpANFyKGBwzvv1UVk2KdN23fJZ8sXSVEK'),
                                                   pw.Asset('9gqcTyupiDWuogWhKv8G3EMwjMaobkw9Lpys4EY2F62t'), 1,
                                                   'privet', timestamp = 1526477921829)
        input = raw_input(colors.fg.lightblue + "Please input message to sign (for example \"" + base58.b58encode(
            str(some_transfer_bytes)) + "\")> " + colors.reset)
        if len(input) == 0:
            binary_data += some_transfer_bytes
            print(colors.fg.lightgrey + "tx bytes:   " + base58.b58encode(str(some_transfer_bytes)))
        else:
            binary_data += base58.b58decode(input)
            print(colors.fg.lightgrey + "tx bytes:   " + base58.b58encode(str(input)))
        signature = None
        while (True):
            try:
                offset = 0
                while offset != len(binary_data):
                    if (len(binary_data) - offset) > CHUNK_SIZE:
                        chunk = binary_data[offset: offset + CHUNK_SIZE]
                    else:
                        chunk = binary_data[offset:]
                    if (offset + len(chunk)) == len(binary_data):
                        p1 = 0x80
                    else:
                        p1 = 0x00

                    if (offset == 0):
github PyWaves / PyWaves / address.py View on Github external
def reissueAsset(self, Asset, quantity, reissuable=False, txFee=pywaves.DEFAULT_TX_FEE):
        timestamp = int(time.time() * 1000)
        sData = b'\5' + \
                base58.b58decode(self.publicKey) + \
                base58.b58decode(Asset.assetId) + \
                struct.pack(">Q", quantity) + \
                (b'\1' if reissuable else b'\0') + \
                struct.pack(">Q",txFee) + \
                struct.pack(">Q", timestamp)
        signature = crypto.sign(self.privateKey, sData)
        data = json.dumps({
            "senderPublicKey": self.publicKey,
            "assetId": Asset.assetId,
            "quantity": quantity,
            "timestamp": timestamp,
            "reissuable": reissuable,
            "fee": txFee,
            "signature": signature
        })
        req = pywaves.wrapper('/assets/broadcast/reissue', data)
github polkascan / py-scale-codec / scalecodec / utils / ss58.py View on Github external
def ss58_decode(address, valid_address_type=None):
    checksum_prefix = b'SS58PRE'

    ss58_format = base58.b58decode(address)

    if valid_address_type and ss58_format[0] != valid_address_type:
        raise ValueError("Invalid Address type")

    # Determine checksum length according to length of address string
    if len(ss58_format) in [3, 4, 6, 10]:
        checksum_length = 1
    elif len(ss58_format) in [5, 7, 11, 35]:
        checksum_length = 2
    elif len(ss58_format) in [8, 12]:
        checksum_length = 3
    elif len(ss58_format) in [9, 13]:
        checksum_length = 4
    elif len(ss58_format) in [14]:
        checksum_length = 5
    elif len(ss58_format) in [15]:
github polyswarm / polyswarmd / polyswarmd.py View on Github external
def is_valid_ipfshash(ipfshash):
    # TODO: Further multihash validation
    try:
        return len(ipfshash) < 100 and base58.b58decode(ipfshash)
    except:
        pass

    return False
github bigchaindb / bigchaindb-driver / bigchaindb_driver / common / transaction.py View on Github external
def _fulfillment_from_details(data, _depth=0):
    """Load a fulfillment for a signing spec dictionary

    Args:
        data: tx.output[].condition.details dictionary
    """
    if _depth == 100:
        raise ThresholdTooDeep()

    if data['type'] == 'ed25519-sha-256':
        public_key = base58.b58decode(data['public_key'])
        return Ed25519Sha256(public_key=public_key)

    if data['type'] == 'threshold-sha-256':
        threshold = ThresholdSha256(data['threshold'])
        for cond in data['subconditions']:
            cond = _fulfillment_from_details(cond, _depth+1)
            threshold.add_subfulfillment(cond)
        return threshold

    raise UnsupportedTypeError(data.get('type'))
github habanoz / tezos-reward-distributor / src / pay / batch_payer.py View on Github external
logger.error("Error in preapply operation")
            logger.debug("Error in preapply, request '{}'".format(preapply_command_str))
            logger.debug("---")
            logger.debug("Error in preapply, response '{}'".format(preapply_command_response))

            return PaymentStatus.FAIL, ""

        # not necessary
        # preapplied = parse_response(preapply_command_response)

        # if dry_run, skip injection
        if dry_run: return PaymentStatus.DONE, ""

        # inject the operations
        logger.debug("Injecting {} operations".format(len(content_list)))
        decoded = base58.b58decode(signed_bytes).hex()

        if signed_bytes.startswith("edsig"):  # edsig signature
            decoded_edsig_signature = decoded[10:][:-8]  # first 5 bytes edsig, last 4 bytes checksum
            decoded_signature = decoded_edsig_signature
        elif signed_bytes.startswith("sig"):  # generic signature
            decoded_sig_signature = decoded[6:][:-8]  # first 3 bytes sig, last 4 bytes checksum
            decoded_signature = decoded_sig_signature
        elif signed_bytes.startswith("p2sig"):
            decoded_sig_signature = decoded[8:][:-8]  # first 4 bytes sig, last 4 bytes checksum
            decoded_signature = decoded_sig_signature
        else:
            raise Exception("Signature '{}' is not in expected format".format(signed_bytes))

        if len(decoded_signature) != 128:  # must be 64 bytes
            # raise Exception("Signature length must be 128 but it is {}. Signature is '{}'".format(len(signed_bytes), signed_bytes))
            logger.warn("Signature length must be 128 but it is {}. Signature is '{}'".format(len(signed_bytes), signed_bytes))
github ArcBlock / forge-python-sdk / forge_sdk / utils / utils.py View on Github external
def multibase_b58decode(data):
    if data.startswith('z'):
        return base58.b58decode((data[1:]).encode())
    raise ValueError('{} cannot be decoded by multibase'
                     ' base58.'.format(str(data)))
github bigchaindb / bigchaindb-driver / bigchaindb_driver / common / transaction.py View on Github external
#       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.digest(),
                base58.b58decode(key_pairs[public_key].encode()))
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_
github duniter / duniter-python-api / duniterpy / documents / crc_pubkey.py View on Github external
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType:
        """
        Return CRCPubkey instance from public key string

        :param pubkey: Public key
        :return:
        """
        hash_root = hashlib.sha256()
        hash_root.update(base58.b58decode(pubkey))
        hash_squared = hashlib.sha256()
        hash_squared.update(hash_root.digest())
        b58_checksum = ensure_str(base58.b58encode(hash_squared.digest()))

        crc = b58_checksum[:3]
        return cls(pubkey, crc)
github sovrin-foundation / old-sovrin / sovrin / agent / walleted.py View on Github external
def verifySignature(self, msg: Dict[str, str]):
        signature = msg.get(f.SIG.nm)
        identifier = msg.get(IDENTIFIER)
        msgWithoutSig = {k: v for k, v in msg.items() if k != f.SIG.nm}
        # TODO This assumes the current key is the cryptonym. This is a BAD
        # ASSUMPTION!!! Sovrin needs to provide the current key.
        ser = serializeMsg(msgWithoutSig)
        signature = b58decode(signature.encode())
        typ = msg.get(TYPE)
        # TODO: Maybe keeping ACCEPT_INVITE open is a better option than keeping
        # an if condition here?
        if typ == ACCEPT_INVITE:
            verkey = msg.get(VERKEY)
        else:
            try:
                link = self.getLinkForMsg(msg)
                verkey = self.getVerkeyForLink(link)
            except LinkNotFound:
                # This is for verification of `NOTIFY` events
                link = self.wallet.getLinkInvitationByTarget(identifier)
                # TODO: If verkey is None, it should be fetched from Sovrin.
                # Assuming CID for now.
                verkey = link.targetVerkey