def from_str(cls, obj):
        if not isinstance(obj, str):
            raise TypeError(
                "UnlockHash is expected to be a str, not {}".format(type(obj)))
        obj = jsstr.strip(obj)
        if len(obj) != UnlockHash._TOTAL_SIZE_HEX:
            raise ValueError(
                "UnlockHash is expexcted to be of length {} when stringified, not of length {}, invalid: {} ({})"
                .format(UnlockHash._TOTAL_SIZE_HEX, len(obj), obj, type(obj)))

        t = UnlockHashType(
            int(jsarr.slice_array(obj, 0, UnlockHash._TYPE_SIZE_HEX)))
        h = Hash(
            value=obj[UnlockHash._TYPE_SIZE_HEX:UnlockHash._TYPE_SIZE_HEX +
                      UnlockHash._HASH_SIZE_HEX])
        uh = cls(uhtype=t, uhhash=h)

        if t.__eq__(UnlockHashType.NIL):
            expectedNH = jshex.bytes_to_hex(
                bytes(jsarr.new_array(UnlockHash._HASH_SIZE)))
            nh = jshex.bytes_to_hex(h.value)
            if nh != expectedNH:
                raise ValueError("unexpected nil hash {}".format(nh))
        else:
            expected_checksum = jshex.bytes_to_hex(
                jsarr.slice_array(uh._checksum(), 0,
                                  UnlockHash._CHECKSUM_SIZE))
            checksum = jsarr.slice_array(
                obj,
                UnlockHash._TOTAL_SIZE_HEX - UnlockHash._CHECKSUM_SIZE_HEX)
            if expected_checksum != checksum:
                raise ValueError("unexpected checksum {}, expected {}".format(
                    checksum, expected_checksum))

        return uh
Exemplo n.º 2
0
 def to_mnemonic(self, data):
     if len(data) not in [16, 20, 24, 28, 32]:
         raise ValueError(
             'Data length should be one of the following: [16, 20, 24, 28, 32], but it is not (%d).'
             % len(data))
     h = jshex.bytes_to_hex(self._sha256_func(data))
     b = jsstr.zfill(jshex.hex_to_bin(jshex.bytes_to_hex(data))[2:], len(data) * 8) + \
         jsstr.zfill(jshex.hex_to_bin(h)[2:], 256)[:len(data) * 8 // 32]
     result = []
     for i in range(len(b) // 11):
         idx = jsbin.bin_str_to_int(b[i * 11:(i + 1) * 11])
         result.append(self.wordlist[idx])
     result_phrase = ' '.join(result)
     return result_phrase
Exemplo n.º 3
0
 def check(self, mnemonic):
     if not isinstance(mnemonic, str):
         return False
     mnemonic = jsstr.strip(mnemonic)
     mnemonic = mnemonic.split(' ')
     # list of valid mnemonic lengths
     if len(mnemonic) not in [12, 15, 18, 21, 24]:
         return False
     try:
         idx = map(
             lambda x: jsstr.zfill(
                 jsint.to_bin_str(jsarr.index_of(self.wordlist, x))[2:], 11
             ), mnemonic)
         b = ''.join(idx)
     except ValueError:
         return False
     l = len(b)  # noqa: E741
     d = b[:l // 33 * 32]
     h = b[-l // 33:]
     nd = jshex.bytes_from_hex(
         jsstr.zfill(
             jsstr.rstrip(jshex.hex_from_bin(jsint.to_bin_str(d)[2:]), 'L'),
             l // 33 * 8))
     nh = jsstr.zfill(
         jshex.hex_to_bin(jshex.bytes_to_hex(self._sha256_func(nd)))[2:],
         256)[:l // 33]
     return h == nh
Exemplo n.º 4
0
def _as_primitive(obj):
    if isinstance(obj, (bytes, bytearray)) or jsarr.is_uint8_array(obj):
        return jshex.bytes_to_hex(obj)
    if isinstance(obj, tfjson.BaseJSONObject):
        return _as_primitive(obj.json())
    if jsobj.is_js_obj(obj):
        return jsjson.json_dumps(obj)
    return obj
Exemplo n.º 5
0
def sha256(data):
    data = jshex.bytes_to_hex(data)
    digest = ''
    __pragma__(
        "js", "{}", """
  const input = sjcl.codec.hex.toBits(data);
  const words = sjcl.hash.sha256.hash(input)
  digest = sjcl.codec.hex.fromBits(words);
  """)
    return jshex.bytes_from_hex(digest)
Exemplo n.º 6
0
    def __init__(self, value=None, fixed_size=None, strencoding=None):
        # define string encoding
        if strencoding != None and not isinstance(strencoding, str):
            raise TypeError(
                "strencoding should be None or a str, not be of type {}".format(strencoding))
        if strencoding == None or jsstr.String(strencoding).lower().strip().__eq__('hex'):
            self._from_str = lambda s: jshex.bytes_from_hex(s)
            self._to_str = lambda value: jshex.bytes_to_hex(value)
        elif jsstr.String(strencoding).lower().strip().__eq__('base64'):
            self._from_str = lambda s: jsbase64.bytes_from_b64(s)
            self._to_str = lambda value: jsbase64.bytes_to_b64(value)
        elif jsstr.String(strencoding).lower().strip().__eq__('hexprefix'):
            self._from_str = lambda s: jshex.bytes_from_hex(
                s[2:] if (s.startswith("0x") or s.startswith("0X")) else s)
            self._to_str = lambda value: '0x' + jshex.bytes_to_hex(value)
        else:
            raise TypeError(
                "{} is not a valid string encoding".format(strencoding))
        self._strencoding = strencoding

        # define fixed size
        if fixed_size != None:
            if not isinstance(fixed_size, int):
                raise TypeError(
                    "fixed size should be None or int, not be of type {}".format(type(fixed_size)))
            if fixed_size < 0:
                raise TypeError(
                    "fixed size should be at least 0, {} is not allowed".format(fixed_size))
        if fixed_size != 0:
            self._fixed_size = fixed_size
        else:
            self._fixed_size = None  # for now use no fixed size

        # define the value (finally)
        self._value = None
        self.value = value

        if fixed_size == 0:
            # define the fixed size now, if the fixed_size was 0
            # based on the binary length of the value
            self._fixed_size = len(self.value)
 def __str__(self):
     checksum = jshex.bytes_to_hex(
         jsarr.slice_array(self._checksum(), 0, UnlockHash._CHECKSUM_SIZE))
     return "{}{}{}".format(
         jshex.bytes_to_hex(bytes([self._type.__int__()])),
         self._hash.__str__(), checksum)
def from_recipient(recipient, lock=None):
    """
    Create automatically a recipient condition based on any accepted pythonic value (combo).
    """

    # define base condition
    if isinstance(recipient, ConditionBaseClass):
        condition = recipient
    else:
        condition = None
        if recipient == None:
            # free-for-all wallet
            condition = nil_new()
        elif isinstance(recipient, str):
            if recipient == jsstr.repeat('0', 78):  # nil wallet
                condition = nil_new()
            else:  # single sig wallet
                condition = unlockhash_new(unlockhash=recipient)
        elif isinstance(recipient, UnlockHash):
            # single sig wallet
            condition = unlockhash_new(unlockhash=recipient)
        elif isinstance(recipient,
                        (bytes, bytearray)) or jsarr.is_uint8_array(recipient):
            # single sig wallet
            condition = unlockhash_new(
                unlockhash=jshex.bytes_to_hex(recipient))
        elif isinstance(recipient, list) or jsobj.is_js_arr(recipient):
            if len(recipient) == 2:
                sig_count, owners = None, None
                if isinstance(recipient[0], (int, float)):
                    sig_count, owners = int(recipient[0]), recipient[1]
                if isinstance(recipient[1], (int, float)):
                    if sig_count != None:
                        raise TypeError(
                            "invalid recipient {}".format(recipient))
                    sig_count, owners = int(recipient[1]), recipient[0]
                if sig_count != None:
                    condition = multi_signature_new(min_nr_sig=sig_count,
                                                    unlockhashes=owners)
            if condition == None:
                # multisig to an all-for-all wallet
                condition = multi_signature_new(min_nr_sig=len(recipient),
                                                unlockhashes=recipient)
        elif isinstance(recipient, tuple):
            # multisig wallet with custom x-of-n definition
            if len(recipient) != 2:
                raise ValueError(
                    "recipient is expected to be a tupple of 2 values in the form (sigcount,hashes) or (hashes,sigcount), cannot be of length {}"
                    .format(len(recipient)))
            # allow (sigs,hashes) as well as (hashes,sigs)
            if isinstance(recipient[0], int):
                condition = multi_signature_new(min_nr_sig=recipient[0],
                                                unlockhashes=recipient[1])
            else:
                condition = multi_signature_new(min_nr_sig=recipient[1],
                                                unlockhashes=recipient[0])
        else:
            raise TypeError("invalid type for recipient parameter: {}: {}",
                            type(recipient), recipient)

    # if lock is defined, define it as a locktime value
    if lock != None:
        condition = locktime_new(lock=lock, condition=condition)

    # return condition
    return condition