Example #1
0
    def build_payment_tx(self, options):
        tx = Transaction(self, None)
        if not options:
            tx.tx_json['obj'] = Exception('invalid options type')
            return tx
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']

        if options.__contains__('destination'):
            dst = options['destination']
        elif options.__contains__('to'):
            dst = options['to']
        amount = options['amount']

        if not Wallet.is_valid_address(src):
            tx.tx_json['src'] = Exception('invalid source address')
            return tx
        if not Wallet.is_valid_address(dst):
            tx.tx_json['dst'] = Exception('invalid destination address')
            return tx

        if not utils.is_valid_amount(amount):
            tx.tx_json['amount'] = Exception('invalid amount')
            return tx

        tx.tx_json['TransactionType'] = 'Payment'
        tx.tx_json['Account'] = src
        tx.tx_json['Amount'] = to_amount(amount)
        tx.tx_json['Destination'] = dst
        return tx
Example #2
0
    def __build_relation_set(self, options, tx):
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']

        des = options['target']
        limit = options['limit']

        if not Wallet.is_valid_address(src):
            tx.tx_json['src'] = Exception('invalid source address')
            return tx
        if not Wallet.is_valid_address(des):
            tx.tx_json['des'] = Exception('invalid target address')
            return tx
        if not utils.is_valid_amount(limit):
            tx.tx_json['limit'] = Exception('invalid amount')
            return tx

        if options['type'] == 'unfreeze':
            tx.tx_json['TransactionType'] = 'RelationDel'
        else:
            tx.tx_json['TransactionType'] = 'RelationSet'
        tx.tx_json['Account'] = src
        tx.tx_json['Target'] = des
        if options['type'] == 'authorize':
            tx.tx_json['RelationType'] = '1'
        else:
            tx.tx_json['RelationType'] = '3'
        if limit:
            tx.tx_json['LimitAmount'] = limit
        return tx
Example #3
0
    def call_contract_tx(self, options):
        """
        创建执行合约对象
         * @param options
         *    account, required
         *    destination, required
         *    foo, required
         * @returns {Transaction}
        """
        tx = Transaction(self, None)
        if not options:
            tx.tx_json['obj'] = Exception('invalid options type')
            return tx

        account = options['account']
        des = options['destination']
        foo = options['foo']
        if options.__contains__('params'):
            params = options['params']

        if not Wallet.is_valid_address(account):
            tx.tx_json['account'] = Exception('invalid account')
            return tx
        if not Wallet.is_valid_address(des):
            tx.tx_json['des'] = Exception('invalid destination')
            return tx

        if not isinstance(foo, str):
            tx.tx_json['foo'] = Exception('foo must be string')
            return tx

        if 'params' in vars():
            if not isinstance(params, list):
                tx.tx_json['params'] = Exception('invalid params')
                return tx

        tx.tx_json['TransactionType'] = 'ConfigContract'
        tx.tx_json['Account'] = account
        tx.tx_json['Method'] = 1
        tx.tx_json['Destination'] = des
        tx.tx_json['ContractMethod'] = str_to_hex(foo)
        tx.tx_json['Args'] = []
        for i in params:
            if not isinstance(i, str):
                tx.tx_json['params'] = Exception('params must be string')
                return tx
            obj = dict()
            obj['Arg'] = {'Parameter': str_to_hex(i)}
            tx.tx_json['Args'].append(obj)

        return tx
Example #4
0
    def __build_trust_set(self, options, tx):
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']
        limit = options['limit']
        if options.__contains__('quality_out'):
            tx.tx_json['QualityIn'] = options['quality_out']
        if options.__contains__('quality_in'):
            tx.tx_json['QualityOut'] = options['quality_in']

        if not Wallet.is_valid_address(src):
            tx.tx_json['src'] = Exception('invalid source address')
            return tx
        if not utils.is_valid_amount(limit):
            tx.tx_json['limit'] = Exception('invalid amount')
            return tx

        tx.tx_json['TransactionType'] = 'TrustSet'
        tx.tx_json['Account'] = src
        if limit:
            tx.tx_json['LimitAmount'] = limit
        return tx
Example #5
0
def is_valid_address(account):
    """
    直接调用baselib中的isValidAddress方法
    :param account:
    :return:
    """
    return Wallet.is_valid_address(account)
Example #6
0
    def signing(self):
        from jingtum_python_baselib.serializer import Serializer
        self.tx_json['Fee'] = self.tx_json['Fee'] / 1000000

        # payment
        if self.tx_json.__contains__('Amount') and '{' not in json.dumps(
                self.tx_json['Amount']):
            # 基础货币
            self.tx_json['Amount'] = Number(self.tx_json['Amount']) / 1000000

        if self.tx_json.__contains__('Memos'):
            memo_list = self.tx_json['Memos']
            i = 0
            while i < len(memo_list):
                memo_list[i]["Memo"]["MemoData"] = hex_to_str(
                    memo_list[i]["Memo"]["MemoData"])
                i += 1

        if self.tx_json.__contains__('SendMax') and isinstance(
                self.tx_json['SendMax'], str):
            self.tx_json['SendMax'] = Number(self.tx_json['SendMax']) / 1000000

        # order
        if self.tx_json.__contains__('TakerPays') and '{' not in json.dumps(
                self.tx_json['TakerPays']):
            # 基础货币
            self.tx_json['TakerPays'] = Number(
                self.tx_json['TakerPays']) / 1000000

        if self.tx_json.__contains__('TakerGets') and '{' not in json.dumps(
                self.tx_json['TakerGets']):
            # 基础货币
            self.tx_json['TakerGets'] = Number(
                self.tx_json['TakerGets']) / 1000000

        wt = Wallet(self._secret)
        self.tx_json['SigningPubKey'] = wt.get_public_key()
        prefix = 0x53545800
        serial = Serializer(None)
        hash = serial.from_json(self.tx_json).hash(prefix)
        # print('self.tx_json is', self.tx_json)
        # print('hash is' , hash)
        self.tx_json['TxnSignature'] = wt.sign(hash)
        self.tx_json['blob'] = serial.from_json(self.tx_json).to_hex()
        self.local_sign = True
        return self.tx_json['blob']
Example #7
0
    def build_offer_create_tx(self, options):
        tx = Transaction(self, None)
        if not options:
            tx.tx_json['obj'] = TypeError('invalid options type')
            return tx

        offer_type = options['type']
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']

        if options.__contains__('taker_gets'):
            taker_gets = options['taker_gets']
        elif options.__contains__('pays'):
            taker_gets = options['pays']

        if options.__contains__('taker_pays'):
            taker_pays = options['taker_pays']
        elif options.__contains__('gets'):
            taker_pays = options['gets']

        if not Wallet.is_valid_address(src):
            tx.tx_json['src'] = Exception('invalid source address')
            return tx
        if not isinstance(offer_type, str) or not offer_type in OfferTypes:
            tx.tx_json['offer_type'] = TypeError('invalid offer type')
            return tx

        if isinstance(taker_gets,
                      str) and not int(taker_gets) and not float(taker_gets):
            tx.tx_json['taker_gets2'] = Exception('invalid to pays amount')
            return tx
        if not taker_gets and not utils.is_valid_amount(taker_gets):
            tx.tx_json['taker_gets2'] = Exception(
                'invalid to pays amount object')
            return tx
        if isinstance(
                taker_pays,
                str) and not int(taker_pays) and not not float(taker_pays):
            tx.tx_json['taker_pays2'] = Exception('invalid to gets amount')
            return tx
        if not taker_pays and not utils.is_valid_amount(taker_pays):
            tx.tx_json['taker_pays2'] = Exception(
                'invalid to gets amount object')
            return tx

        tx.tx_json['TransactionType'] = 'OfferCreate'
        if offer_type is 'Sell':
            tx.set_flags(offer_type)
        tx.tx_json['Account'] = src
        tx.tx_json['TakerPays'] = to_amount(taker_pays)
        tx.tx_json['TakerGets'] = to_amount(taker_gets)
        return tx
Example #8
0
    def request_account(self, type, options, req):
        """
        :param type:
        :param options:
        :param req:
        :return:
        """
        req.command = type
        ledger = None
        peer = None
        limit = None
        marker = None
        account = options['account']
        if 'ledger' in options:
            ledger = options['ledger']
        if 'peer' in options:
            peer = options['peer']
        if 'limit' in options:
            limit = options['limit']
        if 'marker' in options:
            marker = options['marker']
        if 'type' in options:
            req.message['relation_type'] = self.get_relation_type(options['type'])
        if account:
            if not Wallet.is_valid_address(account):
                req.message['account'] = Exception('invalid account')
                return req
            else:
                req.message['account'] = account
        req.select_ledger(ledger)

        if Wallet.is_valid_address(peer):
            req.message['peer'] = peer
        if limit:
            limit = int(limit)
            if limit < 0:
                limit = 0
            if limit > 1e9:
                limit = 1e9
            req.message['limit'] = limit
        if marker:
            req.message['marker'] = marker
        return req
Example #9
0
    def __build_delegate_key_set(self, options, tx):
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']
        delegate_key = options['delegate_key']

        if not Wallet.is_valid_address(src):
            tx.tx_json['delegate_key'] = Exception('invalid source address')
            return tx
        if not Wallet.is_valid_address(delegate_key):
            tx.tx_json['delegate_key'] = Exception('invalid regular key address')
            return tx
        tx.tx_json['TransactionType'] = 'SetRegularKey'
        tx.tx_json['Account'] = src
        tx.tx_json['RegularKey'] = delegate_key
        return tx
Example #10
0
    def deploy_contract_tx(self, options):
        """
        创建部署合约对象
         * @param options
         *    account, required
         *    amount, required
         *    payload, required
         * @returns {Transaction}
        """
        tx = Transaction(self, None)
        if not options:
            tx.tx_json['obj'] = Exception('invalid options type')
            return tx

        account = options['account']
        amount = options['amount']
        payload = options['payload']
        if options.__contains__('params'):
            params = options['params']

        if not Wallet.is_valid_address(account):
            tx.tx_json['account'] = Exception('invalid account')
            return tx

        if math.isnan(amount):
            tx.tx_json['amount'] = Exception('invalid amount')
            return tx

        if not isinstance(payload, str):
            tx.tx_json['payload'] = Exception('invalid payload: type error.')
            return tx

        if 'params' in vars():
            if not isinstance(params, list):
                tx.tx_json['params'] = Exception('invalid params')
                return tx

        tx.tx_json['TransactionType'] = 'ConfigContract'
        tx.tx_json['Account'] = account
        tx.tx_json['Amount'] = amount * 1000000
        tx.tx_json['Method'] = 0
        tx.tx_json['Payload'] = payload
        tx.tx_json['Args'] = []

        if 'params' in vars():
            for i in params:
                obj = dict()
                obj['Arg'] = {'Parameter': str_to_hex(i)}
                tx.tx_json['Args'].append(obj)
        # print(tx.tx_json['Args'])

        return tx
Example #11
0
 def is_valid_amount0(amount):
     if (not amount):
         return False
     # check amount currency
     if (not amount.__contains__('currency') or not utils.is_valid_currency(amount['currency'])):
         return False
     # native currency issuer is empty
     if (amount['currency'] == Config.currency and amount['issuer'] != ''):
         return False
     # non native currency issuer is not allowed to be empty
     if (amount['currency'] != Config.currency
             and not Wallet.is_valid_address(amount['issuer'])):
         return False
     return True
Example #12
0
def is_valid_amount(amount):
    if (not amount):
        return False
    # check amount value
    if (not amount.__contains__('value') and amount['value'] != 0) or not is_num(amount['value']):
        return False
    # check amount currency
    if not amount.__contains__('currency') or not is_valid_currency(amount['currency']):
        return False
    # native currency issuer is empty
    if amount['currency'] == Config.currency and amount['issuer'] != '':
        return False
    # non native currency issuer is not allowed to be empty
    if amount['currency'] != Config.currency and not Wallet.is_valid_address(amount['issuer']):
        return False
    return True
Example #13
0
    def request_account_tx(self, options):
        data = []
        request = Request(self, 'account_tx', None)
        if not isinstance(options, object):
            request.message['type'] = Exception('invalid options type')
            return request

        if not Wallet.is_valid_address(options['account']):
            request.message['account'] = Exception(
                'account parameter is invalid')
            return request

        request.message['account'] = options['account']

        if options.__contains__('ledger_min') and Number(
                options['ledger_min']):
            request.message['ledger_index_min'] = Number(options['ledger_min'])
        else:
            request.message['ledger_index_min'] = 0
        if options.__contains__('ledger_max') and Number(
                options['ledger_max']):
            request.message['ledger_index_max'] = Number(options['ledger_max'])
        else:
            request.message['ledger_index_max'] = -1

        if options.__contains__('limit') and isinstance(options['limit'], int):
            if options['limit'] > 0:  # limit must be positive
                request.message['limit'] = options['limit']

        if options.__contains__('offset') and Number(options['offset']):
            request.message['offset'] = Number(options['offset'])

        if options.__contains__('marker') and isinstance(
                options['marker'], 'object') and Number(
                    options.marker['ledger']) != None and Number(
                        options['marker']['seq']) != None:
            request.message['marker'] = options['marker']

        if options.__contains__('forward') and isinstance(
                options['forward'], 'boolean'):
            request.message['forward'] = options['forward']

        return request
Example #14
0
 def parse_json(self, in_json):
     if isinstance(in_json, (int, float)):
         self.parse_swt_value(str(in_json))
     elif isinstance(in_json, str):
         # only allow
         self.parse_swt_value(in_json)
     elif isinstance(in_json, object):
         if not is_tum_code(in_json['currency']):
             raise Exception(
                 'Amount.parse_json: Input JSON has invalid Tum info!')
         else:
             # AMOUNT could have a field named either as 'issuer' or as 'counterparty' for SWT, self can be undefined
             if (in_json['currency'] != 'SWT'):
                 self._currency = in_json['currency']
                 self._is_native = False
                 if in_json.__contains__(
                         'issuer') and in_json['issuer'] is not None:
                     if (Wallet.is_valid_address(in_json['issuer'])):
                         self._issuer = in_json['issuer']
                         # TODO, need to find a better way for extracting the exponent and digits
                         vpow = float(in_json['value'])
                         vpow = str("%e" % vpow)
                         vpow = vpow[vpow.rfind("e") + 1:].replace("0", "")
                         offset = 15 - int(vpow)
                         factor = math.pow(10, offset)
                         self._value = int(float(in_json['value']) * factor)
                         self._offset = -1 * offset
                     else:
                         raise Exception(
                             'Amount.parse_json: Input JSON has invalid issuer info!'
                         )
                 else:
                     raise Exception(
                         'Amount.parse_json: Input JSON has invalid issuer info!'
                     )
             else:
                 self.parse_swt_value(str(in_json['value']))
     else:
         raise Exception('Amount.parse_json: Unsupported JSON type!')
     return self
Example #15
0
 def build_offer_cancel_tx(self, options):
     tx = Transaction(self, None)
     if not options:
         tx.tx_json.obj = Exception('invalid options type')
         return tx
     if options.__contains__('source'):
         src = options['source']
     elif options.__contains__('from'):
         src = options['from']
     elif options.__contains__('account'):
         src = options['account']
     sequence = options['sequence']
     if not Wallet.is_valid_address(src):
         tx.tx_json['src'] = Exception('invalid source address')
         return tx
     if not int(sequence) and not float(sequence):
         tx.tx_json['sequence'] = Exception('invalid sequence param')
         return tx
     tx.tx_json['TransactionType'] = 'OfferCancel'
     tx.tx_json['Account'] = src
     tx.tx_json['OfferSequence'] = int(sequence)
     return tx
Example #16
0
    def __build_account_set(self, options, tx):
        if options.__contains__('source'):
            src = options['source']
        elif options.__contains__('from'):
            src = options['from']
        elif options.__contains__('account'):
            src = options['account']
        if options.__contains__('set_flag'):
            set_flag = options['set_flag']
        elif options.__contains__('set'):
            set_flag = options['set']
        if options.__contains__('clear_flag'):
            clear_flag = options['clear_flag']
        elif options.__contains__('clear'):
            clear_flag = options['clear']
        else:
            clear_flag = None
        if not Wallet.is_valid_address(src):
            tx.tx_json['src'] = Exception('invalid source address')
            return tx

        tx.tx_json['TransactionType'] = 'AccountSet'
        tx.tx_json['Account'] = src

        SetClearFlags = set_clear_flags['AccountSet']

        if set_flag:
            set_flag = self.__prepare_flag(set_flag, SetClearFlags)
            if set_flag:
                tx.tx_json['SetFlag'] = set_flag

        if clear_flag is not None:
            clear_flag = self.__prepare_flag(clear_flag, SetClearFlags)
            if clear_flag:
                tx.tx_json['ClearFlag'] = clear_flag

        return tx
Example #17
0
 def new_listener(self, account, listener):
     if account == 'removeListener':
         return
     if not Wallet.is_valid_address(account):
         self.account = Exception('invalid account')
     self.accounts[account] = listener
Example #18
0
    def remove_listener(self, account):
        if not Wallet.is_valid_address(account):
            raise Exception('invalid account')

        del self.accounts[account]
Example #19
0
 def test_from_secret():
     result = Wallet.from_secret('ss2A7yahPhoduQjmG7z9BHu3uReDk123')
     logger.info(result)
Example #20
0
 def test_is_valid_address(self):
     self.assertTrue(
         Wallet.is_valid_address('jfdLqEWhfYje92gEaWixVWsYKjK5C6bMoi'))
Example #21
0
 def set_secret(self, secret):
     if not Wallet.is_valid_secret(secret):
         self.tx_json['_secret'] = Exception('invalid secret')
         return
     self._secret = secret
Example #22
0
    def parse_issuer(self, issuer):
        if (Wallet.is_valid_address(issuer)):
            self._issuer = issuer

        return self
Example #23
0
 def test_generate():
     result = Wallet.generate()
     logger.info(result)