Python base58.b58decode() Examples

The following are 30 code examples of base58.b58decode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module base58 , or try the search function .
Example #1
Source File: account.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 7 votes vote down vote up
def get_private_key_from_wif(wif: str) -> bytes:
        """
        This interface is used to decode a WIF encode ECDSA private key.

        :param wif: a WIF encode private key.
        :return: a ECDSA private key in the form of bytes.
        """
        if wif is None or wif is "":
            raise Exception("none wif")
        data = base58.b58decode(wif)
        if len(data) != 38 or data[0] != 0x80 or data[33] != 0x01:
            raise Exception("wif wrong")
        checksum = Digest.hash256(data[0:34])
        for i in range(4):
            if data[len(data) - 4 + i] != checksum[i]:
                raise Exception("wif wrong")
        return data[1:33] 
Example #2
Source File: test_transaction.py    From bigchaindb with Apache License 2.0 6 votes vote down vote up
def test_generate_outputs_split_half_single_owner(user_pub,
                                                  user2_pub, user3_pub):
    from bigchaindb.common.transaction import Output
    from cryptoconditions import Ed25519Sha256, ThresholdSha256

    expected_simple1 = Ed25519Sha256(public_key=b58decode(user_pub))
    expected_simple2 = Ed25519Sha256(public_key=b58decode(user2_pub))
    expected_simple3 = Ed25519Sha256(public_key=b58decode(user3_pub))

    expected = ThresholdSha256(threshold=2)
    expected_threshold = ThresholdSha256(threshold=2)
    expected_threshold.add_subfulfillment(expected_simple2)
    expected_threshold.add_subfulfillment(expected_simple3)
    expected.add_subfulfillment(expected_threshold)
    expected.add_subfulfillment(expected_simple1)

    cond = Output.generate([[expected_simple2, user3_pub], user_pub], 1)
    assert cond.fulfillment.to_dict() == expected.to_dict() 
Example #3
Source File: fields.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def _specific_validation(self, val):
        invalid_chars = set(val) - self._alphabet
        if invalid_chars:
            # only 10 chars to shorten the output
            # TODO: Why does it need to be sorted
            to_print = sorted(invalid_chars)[:10]
            return 'should not contain the following chars {}{}'.format(
                to_print, ' (truncated)' if len(to_print) < len(invalid_chars) else '')
        if self.byte_lengths is not None:
            # TODO could impact performance, need to check
            b58len = len(base58.b58decode(val))
            if b58len not in self.byte_lengths:
                expected_length = list(self.byte_lengths)[0] if len(self.byte_lengths) == 1 \
                    else 'one of {}'.format(list(self.byte_lengths))
                return 'b58 decoded value length {} should be {}' \
                    .format(b58len, expected_length) 
Example #4
Source File: verifier.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def __init__(self, verkey, identifier=None):
        _verkey = verkey
        self._verkey = None
        self._vr = None
        if identifier:
            rawIdr = b58decode(identifier)
            if len(rawIdr) == 32 and not verkey:  # assume cryptonym
                verkey = identifier

            if not verkey:
                raise ValueError("'verkey' should be a non-empty string")
            if verkey[0] == '~':  # abbreviated
                verkey = b58encode(b58decode(identifier) +
                                   b58decode(verkey[1:])).decode("utf-8")
        try:
            self.verkey = verkey
        except Exception as ex:
            raise InvalidKey("verkey {}".format(_verkey)) from ex 
Example #5
Source File: address.py    From PyWaves with MIT License 6 votes vote down vote up
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 = self.pywaves.wrapper('/assets/broadcast/reissue', data)
        if self.pywaves.OFFLINE:
            return req
        else:
            return req.get('id', 'ERROR') 
Example #6
Source File: dash_utils.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def wif_to_privkey(wif_key: str, dash_network: str):
    """
    Based on project: https://github.com/chaeplin/dashmnb with some changes related to usage of bitcoin library.
    """
    privkey_encoded = base58.b58decode(wif_key).hex()
    wif_prefix_cur = privkey_encoded[:2]
    wif_prefix_network = get_chain_params(dash_network).PREFIX_SECRET_KEY
    wif_prefix_network_str = wif_prefix_network.to_bytes(1, byteorder='big').hex()
    checksum_stored = privkey_encoded[-8:]

    vs = bytes.fromhex(privkey_encoded[:-8])
    checksum_actual = binascii.unhexlify(bitcoin.dbl_sha256(vs))[0:4]
    checksum_actual_str = checksum_actual.hex()

    if wif_prefix_cur == wif_prefix_network_str and checksum_stored == checksum_actual_str:
        privkey = privkey_encoded[2:-8]
        return privkey
    else:
        if wif_prefix_cur != wif_prefix_network_str:
            logging.warning('Private key and network prefixes differ. PK prefix: %s, network prefix: %s', wif_prefix_cur,
                            wif_prefix_network_str)
        if checksum_stored != checksum_actual_str:
            logging.warning('Invalid private key checksum. PK checksum: %s, required: %s', checksum_stored,
                            checksum_actual_str)
        return None 
Example #7
Source File: wallet.py    From bitcoin_tools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def btc_addr_to_hash_160(btc_addr):
    """ Calculates the RIPEMD-160 hash from a given Bitcoin address

    :param btc_addr: Bitcoin address.
    :type btc_addr: str
    :return: The corresponding RIPEMD-160 hash.
    :rtype: hex str
    """

    # Base 58 decode the Bitcoin address.
    decoded_addr = b58decode(btc_addr)
    # Covert the address from bytes to hex.
    decoded_addr_hex = hexlify(decoded_addr)
    # Obtain the RIPEMD-160 hash by removing the first and four last bytes of the decoded address, corresponding to
    # the network version and the checksum of the address.
    h160 = decoded_addr_hex[2:-8]

    return h160 
Example #8
Source File: test_state_multi_proofs_for_get_requests.py    From indy-node with Apache License 2.0 6 votes vote down vote up
def is_proof_verified(db_manager,
                      proof, path,
                      value, seq_no, txn_time):
    encoded_value = domain.encode_state_value(value, seq_no, txn_time)
    proof_nodes = base64.b64decode(proof[PROOF_NODES])
    root_hash = base58.b58decode(proof[ROOT_HASH])
    verified = db_manager.get_state(DOMAIN_LEDGER_ID).verify_state_proof(
        root_hash,
        path,
        encoded_value,
        proof_nodes,
        serialized=True
    )
    return verified


# Similar tests for Rich Schema objects are in indy_node/test/request_handlers/rich_schema 
Example #9
Source File: dataformat.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def base58_decode(self):
        """Decode as Base58
        
        Base58 is a notation for encoding arbitrary byte data using a 
        restricted set of symbols that can be conveniently used by humans 
        and processed by computers.This property decodes raw data 
        into an ASCII Base58 string.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("2UDrs31qcWSPi").base58_decode().output.decode()
            "some data"
        """
        self.state = base58.b58decode(self.state)
        return self 
Example #10
Source File: address.py    From PyWaves with MIT License 6 votes vote down vote up
def cancelOrderByID(self, assetPair, orderId):
        sData = base58.b58decode(self.publicKey) + \
                base58.b58decode(orderId)
        signature = crypto.sign(self.privateKey, sData)
        data = json.dumps({
            "sender": self.publicKey,
            "orderId": orderId,
            "signature": signature
        })
        req = self.pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % (pywaves.DEFAULT_CURRENCY if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, pywaves.DEFAULT_CURRENCY if assetPair.asset2.assetId=='' else assetPair.asset2.assetId), data, host=self.pywaves.MATCHER)
        if self.pywaves.OFFLINE:
            return req
        else:
            id = -1
            if req['status'] == 'OrderCanceled':
                id = req['orderId']
                logging.info('Order Cancelled - ID: %s' % id)
            return id 
Example #11
Source File: rest_handlers.py    From gateway with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, address=None):
        if address is None:
            raise HTTPError(400, reason="No address")

        try:
            from_height = long(self.get_argument("from_height", 0))
        except:
            raise HTTPError(400)

        address_decoded = base58.b58decode(address)
        address_version = address_decoded[0]
        address_hash = address_decoded[1:21]

        request = {
            "id": random_id_number(),
            "command":"fetch_history",
            "params": [address_version, address_hash, from_height]
        }

        self.application._obelisk_handler.handle_request(self, request) 
Example #12
Source File: keys.py    From eospy with MIT License 6 votes vote down vote up
def _check_decode(self, key_string, key_type=None) :
        '''    '''
        buffer = hexlify(base58.b58decode(key_string)).decode()
        chksum = buffer[-8:]
        key = buffer[:-8]
        if key_type == 'sha256x2' :
            # legacy
            first_sha = sha256(unhexlify(key))
            newChk = sha256(unhexlify(first_sha))[:8]
        else :
            check = key
            if key_type :
                check += hexlify(bytearray(key_type, 'utf-8')).decode()
            newChk = ripemd160(unhexlify(check))[:8]
        #print('newChk: '+newChk)
        if chksum != newChk :
            raise ValueError('checksums do not match: {0} != {1}'.format(chksum, newChk))
        return key 
Example #13
Source File: address.py    From ledger-api-py with Apache License 2.0 6 votes vote down vote up
def is_address(address: str) -> bool:
        raw_address = base58.b58decode(address)

        if len(raw_address) != Address.DISPLAY_BYTE_LENGTH:
            return False

        # split the identity into address and checksum
        address_raw = raw_address[:Address.BYTE_LENGTH]
        checksum = raw_address[Address.BYTE_LENGTH:]

        # calculate the expected checksum
        expected_checksum = Address._calculate_checksum(address_raw)

        if checksum != expected_checksum:
            return False

        return True 
Example #14
Source File: test_transaction.py    From bigchaindb with Apache License 2.0 6 votes vote down vote up
def test_generate_output_split_half_recursive(user_pub, user2_pub, user3_pub):
    from bigchaindb.common.transaction import Output
    from cryptoconditions import Ed25519Sha256, ThresholdSha256

    expected_simple1 = Ed25519Sha256(public_key=b58decode(user_pub))
    expected_simple2 = Ed25519Sha256(public_key=b58decode(user2_pub))
    expected_simple3 = Ed25519Sha256(public_key=b58decode(user3_pub))

    expected = ThresholdSha256(threshold=2)
    expected.add_subfulfillment(expected_simple1)
    expected_threshold = ThresholdSha256(threshold=2)
    expected_threshold.add_subfulfillment(expected_simple2)
    expected_threshold.add_subfulfillment(expected_simple3)
    expected.add_subfulfillment(expected_threshold)

    cond = Output.generate([user_pub, [user2_pub, expected_simple3]], 1)
    assert cond.fulfillment.to_dict() == expected.to_dict() 
Example #15
Source File: util.py    From old-sovrin with Apache License 2.0 5 votes vote down vote up
def verifySig(identifier, signature, msg) -> bool:
    key = cryptonymToHex(identifier) if not isHex(
        identifier) else identifier
    ser = serializeMsg(msg)
    b64sig = signature.encode('utf-8')
    sig = b58decode(b64sig)
    vr = Verifier(key)
    return vr.verify(sig, ser) 
Example #16
Source File: client.py    From old-sovrin with Apache License 2.0 5 votes vote down vote up
def doAttrDisclose(self, origin, target, txnId, key):
        box = libnacl.public.Box(b58decode(origin), b58decode(target))

        data = json.dumps({TXN_ID: txnId, SKEY: key})
        nonce, boxedMsg = box.encrypt(data.encode(), pack_nonce=False)

        op = {
            TARGET_NYM: target,
            TXN_TYPE: DISCLO,
            NONCE: b58encode(nonce),
            DATA: b58encode(boxedMsg)
        }
        self.submit(op, identifier=origin) 
Example #17
Source File: walleted.py    From old-sovrin with Apache License 2.0 5 votes vote down vote up
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

        v = DidVerifier(verkey, identifier=identifier)
        if not v.verify(signature, ser):
            raise SignatureRejected
        else:
            if typ == ACCEPT_INVITE:
                self.agentLogger.info('\nSignature accepted.')
            return True 
Example #18
Source File: client_authn.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
def authenticate_multi(self, msg: Dict, signatures: Dict[str, str],
                           threshold: Optional[int] = None, verifier: Verifier = DidVerifier):

        num_sigs = len(signatures)
        if threshold is not None:
            if num_sigs < threshold:
                raise InsufficientSignatures(num_sigs, threshold)
        else:
            threshold = num_sigs

        correct_sigs_from = []
        incorrect_signatures = {}
        for idr, sig in signatures.items():
            try:
                sig_decoded = base58.b58decode(sig)
            except Exception as ex:
                raise InvalidSignatureFormat from ex

            ser = self.serializeForSig(msg, identifier=idr)

            verkey = self.getVerkey(idr, msg)
            if verkey is None:
                raise CouldNotAuthenticate(idr)

            vr = verifier(verkey, identifier=idr)
            if vr.verify(sig_decoded, ser):
                correct_sigs_from.append(idr)
                if len(correct_sigs_from) == threshold:
                    break
            else:
                incorrect_signatures[idr] = sig
        else:
            raise InsufficientCorrectSignatures(threshold, len(correct_sigs_from), incorrect_signatures)

        return correct_sigs_from 
Example #19
Source File: utils.py    From bigchaindb with Apache License 2.0 5 votes vote down vote up
def generate_validators(powers):
    """Generates an arbitrary number of validators with random public keys.

       The object under the `storage` key is in the format expected by DB.

       The object under the `eleciton` key is in the format expected by
       the upsert validator election.

       `public_key`, `private_key` are in the format used for signing transactions.

       Args:
           powers: A list of intergers representing the voting power to
                   assign to the corresponding validators.
    """
    validators = []
    for power in powers:
        kp = crypto.generate_key_pair()
        validators.append({
            'storage': {
                'public_key': {
                    'value': key_to_base64(base58.b58decode(kp.public_key).hex()),
                    'type': 'ed25519-base64',
                },
                'voting_power': power,
            },
            'election': {
                'node_id': f'node-{random.choice(range(100))}',
                'power': power,
                'public_key': {
                    'value': base64.b16encode(base58.b58decode(kp.public_key)).decode('utf-8'),
                    'type': 'ed25519-base16',
                },
            },
            'public_key': kp.public_key,
            'private_key': kp.private_key,
        })
    return validators 
Example #20
Source File: util.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
def friendlyToRaw(f):
    return base58.b58decode(f) 
Example #21
Source File: format.py    From PBinCLI with MIT License 5 votes vote down vote up
def setHash(self, passphrase):
        if self._version == 2:
            from base58 import b58decode
            self._key = b58decode(passphrase)
        else:
            self._key = b64decode(passphrase) 
Example #22
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def setAssetScript(self, asset, scriptSource, txFee=pywaves.DEFAULT_ASSET_SCRIPT_FEE, timestamp=0):
        script = self.pywaves.wrapper('/utils/script/compile', scriptSource)['script'][7:]
        if not self.privateKey:
            logging.error('Private key required')
        else:
            compiledScript = base64.b64decode(script)
            scriptLength = len(compiledScript)
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            sData = b'\x0f' + \
                b'\1' + \
                crypto.str2bytes(str(self.pywaves.CHAIN_ID)) + \
                base58.b58decode(self.publicKey) + \
                base58.b58decode(asset.assetId) + \
                struct.pack(">Q", txFee) + \
                struct.pack(">Q", timestamp) + \
                b'\1' + \
                struct.pack(">H", scriptLength) + \
                compiledScript
            signature = crypto.sign(self.privateKey, sData)

            data = json.dumps({
                "type": 15,
                "version": 1,
                "assetId": asset.assetId,
                "senderPublicKey": self.publicKey,
                "fee": txFee,
                "timestamp": timestamp,
                "script": 'base64:' + script,
                "proofs": [
                    signature
                ]
            })
            print(data)

            return self.pywaves.wrapper('/transactions/broadcast', data) 
Example #23
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def setScript(self, scriptSource, txFee=pywaves.DEFAULT_SCRIPT_FEE, timestamp=0):
        print(self.pywaves.wrapper('/utils/script/compile', scriptSource));
        script = self.pywaves.wrapper('/utils/script/compile', scriptSource)['script'][7:]
        if not self.privateKey:
            logging.error('Private key required')
        else:
            compiledScript = base64.b64decode(script)
            scriptLength = len(compiledScript)
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            sData = b'\x0d' + \
                b'\1' + \
                crypto.str2bytes(str(self.pywaves.CHAIN_ID)) + \
                base58.b58decode(self.publicKey) + \
                b'\1' + \
                struct.pack(">H", scriptLength) + \
                compiledScript + \
                struct.pack(">Q", txFee) + \
                struct.pack(">Q", timestamp)
            signature = crypto.sign(self.privateKey, sData)

            data = json.dumps({
                "type": 13,
                "version": 1,
                "senderPublicKey": self.publicKey,
                "fee": txFee,
                "timestamp": timestamp,
                "script": 'base64:' + script,
                "proofs": [
                    signature
                ]
            })

            return self.pywaves.wrapper('/transactions/broadcast', data) 
Example #24
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def sponsorAsset(self, assetId, minimalFeeInAssets, txFee=pywaves.DEFAULT_SPONSOR_FEE, timestamp=0):
        if not self.privateKey:
            logging.error('Private key required')
        else:
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            sData = b'\x0e' + \
                b'\1' + \
                base58.b58decode(self.publicKey) + \
                base58.b58decode(assetId) + \
                struct.pack(">Q", minimalFeeInAssets) + \
                struct.pack(">Q", txFee) + \
                struct.pack(">Q", timestamp)
            signature = crypto.sign(self.privateKey, sData)

            data = json.dumps({
                "type": 14,
                "version": 1,
                "senderPublicKey": self.publicKey,
                "assetId": assetId,
                "fee": txFee,
                "timestamp": timestamp,
                "minSponsoredAssetFee": minimalFeeInAssets,
                "proofs": [
                    signature
                ]
            })

            return self.pywaves.wrapper('/transactions/broadcast', data) 
Example #25
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def createAlias(self, alias, txFee=pywaves.DEFAULT_ALIAS_FEE, timestamp=0):
        aliasWithNetwork = b'\x02' + crypto.str2bytes(str(self.pywaves.CHAIN_ID)) + struct.pack(">H", len(alias)) + crypto.str2bytes(alias)
        if not self.privateKey:
            msg = 'Private key required'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        else:
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            '''sData = b'\x0a' + \
                    base58.b58decode(self.publicKey) + \
                    struct.pack(">H", len(aliasWithNetwork)) + \
                    crypto.str2bytes(str(aliasWithNetwork)) + \
                    struct.pack(">Q", txFee) + \
                    struct.pack(">Q", timestamp)'''
            sData = b'\x0a' + \
                    base58.b58decode(self.publicKey) + \
                    struct.pack(">H", len(aliasWithNetwork)) + \
                    aliasWithNetwork + \
                    struct.pack(">Q", txFee) + \
                    struct.pack(">Q", timestamp)
            signature = crypto.sign(self.privateKey, sData)
            data = json.dumps({
                "type": 10,
                "alias": alias,
                "senderPublicKey": self.publicKey,
                "fee": txFee,
                "timestamp": timestamp,
                "signature": signature,
                "version": 1
            })
            return self.pywaves.wrapper('/alias/broadcast/create', data) 
Example #26
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def cancelOpenOrders(self, assetPair):
        orders = self.getOrderHistory(assetPair)
        for order in orders:
            status = order['status']
            orderId = order['id']
            if status=='Accepted' or status=='PartiallyFilled':
                sData = base58.b58decode(self.publicKey) + \
                        base58.b58decode(orderId)
                signature = crypto.sign(self.privateKey, sData)
                data = json.dumps({
                    "sender": self.publicKey,
                    "orderId": orderId,
                    "signature": signature
                })
                self.pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % (pywaves.DEFAULT_CURRENCY if assetPair.asset1.assetId == '' else assetPair.asset1.assetId, pywaves.DEFAULT_CURRENCY if assetPair.asset2.assetId == '' else assetPair.asset2.assetId), data, host=self.pywaves.MATCHER) 
Example #27
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def getOrderHistory(self, assetPair, timestamp=0):
        if timestamp == 0:
            timestamp = int(time.time() * 1000)
        sData = base58.b58decode(self.publicKey) + \
                struct.pack(">Q", timestamp)
        signature = crypto.sign(self.privateKey, sData)
        data = {
            "Accept": "application/json",
            "Timestamp": str(timestamp),
            "Signature": signature
        }
        req = self.pywaves.wrapper('/matcher/orderbook/%s/%s/publicKey/%s' % (pywaves.DEFAULT_CURRENCY if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, pywaves.DEFAULT_CURRENCY if assetPair.asset2.assetId=='' else assetPair.asset2.assetId, self.publicKey), headers=data, host=self.pywaves.MATCHER)
        return req 
Example #28
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def leaseCancel(self, leaseId, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0):
        if not self.privateKey:
            msg = 'Private key required'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        elif not self.pywaves.OFFLINE and self.balance() < txFee:
            msg = 'Insufficient Waves balance'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        else:
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            sData = b'\x09' + \
                    base58.b58decode(self.publicKey) + \
                    struct.pack(">Q", txFee) + \
                    struct.pack(">Q", timestamp) + \
                    base58.b58decode(leaseId)
            signature = crypto.sign(self.privateKey, sData)
            data = json.dumps({
                "senderPublicKey": self.publicKey,
                "txId": leaseId,
                "fee": txFee,
                "timestamp": timestamp,
                "signature": signature
            })
            req = self.pywaves.wrapper('/leasing/broadcast/cancel', data)
            if self.pywaves.OFFLINE:
                return req
            elif 'leaseId' in req:
                return req['leaseId'] 
Example #29
Source File: address.py    From PyWaves with MIT License 5 votes vote down vote up
def lease(self, recipient, amount, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0):
        if not self.privateKey:
            msg = 'Private key required'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        elif amount <= 0:
            msg = 'Amount must be > 0'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        elif not self.pywaves.OFFLINE and self.balance() < amount + txFee:
            msg = 'Insufficient Waves balance'
            logging.error(msg)
            self.pywaves.throw_error(msg)
        else:
            if timestamp == 0:
                timestamp = int(time.time() * 1000)
            sData = b'\x08' + \
                    base58.b58decode(self.publicKey) + \
                    base58.b58decode(recipient.address) + \
                    struct.pack(">Q", amount) + \
                    struct.pack(">Q", txFee) + \
                    struct.pack(">Q", timestamp)
            signature = crypto.sign(self.privateKey, sData)
            data = json.dumps({
                "senderPublicKey": self.publicKey,
                "recipient": recipient.address,
                "amount": amount,
                "fee": txFee,
                "timestamp": timestamp,
                "signature": signature
            })
            req = self.pywaves.wrapper('/leasing/broadcast/lease', data)
            return req 
Example #30
Source File: cli.py    From old-sovrin with Apache License 2.0 5 votes vote down vote up
def _getNym(self, nym):
        identity = Identity(identifier=nym)
        req = self.activeWallet.requestIdentity(
            identity, sender=self.activeWallet.defaultId)
        self.activeClient.submitReqs(req)
        self.print("Getting nym {}".format(nym))

        def getNymReply(reply, err, *args):
            self.print("Transaction id for NYM {} is {}".
                       format(nym, reply[TXN_ID]), Token.BoldBlue)
            try:
                if reply[DATA]:
                    data=json.loads(reply[DATA])
                    if data:
                        idr = base58.b58decode(nym)
                        if data.get(VERKEY) is None:
                            if len(idr) == 32:
                                self.print(
                                    "Current verkey is same as identifier {}"
                                        .format(nym), Token.BoldBlue)
                            else:
                                self.print(
                                    "No verkey ever assigned to the identifier {}".
                                    format(nym), Token.BoldBlue)
                            return
                        if data.get(VERKEY) == '':
                            self.print("No active verkey found for the identifier {}".
                                       format(nym), Token.BoldBlue)
                        else:
                            self.print("Current verkey for NYM {} is {}".
                               format(nym, data[VERKEY]), Token.BoldBlue)
                else:
                    self.print("NYM {} not found".format(nym), Token.BoldBlue)
            except BaseException as e:
                self.print("Error during fetching verkey: {}".format(e),
                           Token.BoldOrange)

        self.looper.loop.call_later(.2, self._ensureReqCompleted,
                                    req.key, self.activeClient, getNymReply)