def test_sha256_xor(self):
     h1 = Digest.sha256(int.to_bytes(1000, 2, 'little'), is_hex=True)
     h2 = Digest.sha256(int.to_bytes(89, 1, 'little'), is_hex=True)
     h = hex(int(h1, 16) ^ int(h2, 16))[2::]
     self.assertEqual('4307fbbb7e5b7c8f0339b060d171c49c881901d78ab712e60d805af9f9dc4ca1', h1)
     self.assertEqual('18f5384d58bcb1bba0bcd9e6a6781d1a6ac2cc280c330ecbab6cb7931b721552', h2)
     self.assertEqual('5bf2c3f626e7cd34a38569867709d986e2dbcdff86841c2da6eced6ae2ae59f3', h)
Esempio n. 2
0
 def validate_proof(proof: List[dict],
                    hex_target_hash: str,
                    hex_merkle_root: str,
                    is_big_endian: bool = False):
     if is_big_endian:
         hex_merkle_root = NeoData.to_reserve_hex_str(hex_merkle_root)
         hex_target_hash = NeoData.to_reserve_hex_str(hex_target_hash)
     if len(proof) == 0:
         return hex_target_hash == hex_merkle_root
     else:
         hex_proof_hash = hex_target_hash
         for node in proof:
             if is_big_endian:
                 sibling = NeoData.to_reserve_hex_str(node['TargetHash'])
             else:
                 sibling = node['TargetHash']
             try:
                 direction = node['Direction'].lower()
             except KeyError:
                 raise SDKException(ErrorCode.other_error('Invalid proof'))
             if direction == 'left':
                 value = bytes.fromhex('01' + sibling + hex_proof_hash)
                 hex_proof_hash = Digest.sha256(value, is_hex=True)
             elif direction == 'right':
                 value = bytes.fromhex('01' + hex_proof_hash + sibling)
                 hex_proof_hash = Digest.sha256(value, is_hex=True)
             else:
                 raise SDKException(ErrorCode.other_error('Invalid proof.'))
         return hex_proof_hash == hex_merkle_root
 def validate_proof(proof: List[dict], hex_target_hash: str,
                    hex_merkle_root: str):
     hex_merkle_root = ContractDataParser.to_reserve_hex_str(
         hex_merkle_root)
     hex_target_hash = ContractDataParser.to_reserve_hex_str(
         hex_target_hash)
     if len(proof) == 0:
         return hex_target_hash == hex_merkle_root
     else:
         hex_proof_hash = hex_target_hash
         for node in proof:
             sibling = ContractDataParser.to_reserve_hex_str(
                 node['TargetHash'])
             try:
                 direction = node['Direction'].lower()
             except KeyError:
                 raise SDKException(ErrorCode.other_error('Invalid proof'))
             if direction == 'left':
                 value = binascii.a2b_hex('01' + sibling + hex_proof_hash)
                 hex_proof_hash = Digest.sha256(value, is_hex=True)
             elif direction == 'right':
                 value = binascii.a2b_hex('01' + hex_proof_hash + sibling)
                 hex_proof_hash = Digest.sha256(value, is_hex=True)
             else:
                 raise SDKException(ErrorCode.other_error('Invalid proof.'))
         return hex_proof_hash == hex_merkle_root
Esempio n. 4
0
 def hash(bs: bytearray, engine):
     if engine.op_code == ScriptOp.SHA1:
         return None
     elif engine.op_code == ScriptOp.SHA256:
         return Digest.sha256(bs)
     elif engine.op_code == ScriptOp.HASH160:
         return Digest.hash160(bs)
     elif engine.op_code == ScriptOp.HASH256:
         return Digest.hash256(bs)
     return None
Esempio n. 5
0
 def __init__(self, ver: str, iss_ont_id: str, sub_ont_id: str, iat: int, exp: int, context: str, clm: dict,
              clm_rev: dict, jti: str = ''):
     if not isinstance(ver, str):
         raise SDKException(ErrorCode.require_str_params)
     if not isinstance(iss_ont_id, str):
         raise SDKException(ErrorCode.require_str_params)
     if not isinstance(sub_ont_id, str):
         raise SDKException(ErrorCode.require_str_params)
     if not isinstance(iat, int):
         raise SDKException(ErrorCode.require_int_params)
     if not isinstance(clm, dict):
         raise SDKException(ErrorCode.require_dict_params)
     if not isinstance(clm_rev, dict):
         raise SDKException(ErrorCode.require_dict_params)
     if not isinstance(jti, str):
         raise SDKException(ErrorCode.require_str_params)
     self.__version = ver
     self.__issuer_ont_id = iss_ont_id
     self.__subject = sub_ont_id
     self.__issued_at = iat
     self.__exp = exp
     self.__context = context
     self.__claim = clm
     self.__claim_revoke = clm_rev
     self.__jwt_id = jti
     if self.__jwt_id == '':
         self.__jwt_id = Digest.sha256(json.dumps(dict(self)).encode('utf-8'), is_hex=True)
Esempio n. 6
0
 def export_wif(self):
     data = b'\x80'
     data = data + self.serialize_private_key()
     data += b'\01'
     checksum = Digest.hash256(data[0:34])
     data += checksum[0:4]
     return base58.b58encode(data)
Esempio n. 7
0
 def hash256(self, is_hex: bool = False) -> bytes or str:
     tx_serial = self.serialize_unsigned()
     tx_serial = a2b_hex(tx_serial)
     r = Digest.hash256(tx_serial, is_hex)
     if isinstance(r, bytes) or isinstance(r, str):
         return r
     else:
         raise RuntimeError
 def hash256_hex(self) -> str:
     tx_serial = self.serialize_unsigned()
     tx_serial = a2b_hex(tx_serial)
     r = Digest.hash256(tx_serial, True)
     if isinstance(r, str):
         return r
     else:
         raise RuntimeError
 def hash256_bytes(self) -> bytes:
     tx_serial = self.serialize_unsigned()
     tx_serial = a2b_hex(tx_serial)
     r = Digest.hash256(tx_serial, False)
     if isinstance(r, bytes):
         return r
     else:
         raise RuntimeError
 def hash256_explorer(self) -> str:
     tx_serial = self.serialize_unsigned()
     tx_serial = a2b_hex(tx_serial)
     digest = Digest.hash256(tx_serial)
     if isinstance(digest, bytes):
         return b2a_hex(digest[::-1]).decode('ascii')
     else:
         return ''
Esempio n. 11
0
 def set_claim(self, kid: str, iss_ont_id: str, sub_ont_id: str, exp: int, context: str, clm: dict, clm_rev: dict,
               jti: str = '', ver: str = 'v1.0'):
     if not isinstance(jti, str):
         raise SDKException(ErrorCode.require_str_params)
     if jti == '':
         jti = Digest.sha256(uuid.uuid1().bytes, is_hex=True)
     self.__head = Header(kid)
     self.__payload = Payload(ver, iss_ont_id, sub_ont_id, int(time()), exp, context, clm, clm_rev, jti)
 def b58decode(address: str):
     data = base58.b58decode(address)
     if len(data) != 25:
         raise SDKException(ErrorCode.param_error)
     if data[0] != int.from_bytes(Address.__COIN_VERSION, "little"):
         raise SDKException(ErrorCode.param_error)
     checksum = Digest.hash256(data[0:21])
     if data[21:25] != checksum[0:4]:
         raise SDKException(ErrorCode.param_error)
     return Address(data[1:21])
Esempio n. 13
0
    def test_startNewRound(self):
        payerAcct = adminAcct
        param_list = []
        param_list.append("test1".encode())
        param_list1 = []
        a = 1000
        b = 89
        # Within Contract
        # hash1 = sha256(1000) = 4307fbbb7e5b7c8f0339b060d171c49c881901d78ab712e60d805af9f9dc4ca1
        # hash2 = sha256(89) = 18f5384d58bcb1bba0bcd9e6a6781d1a6ac2cc280c330ecbab6cb7931b721552
        # hash3 = hash1 ^ hash2 = 5bf2c3f626e7cd34a38569867709d986e2dbcdff86841c2da6eced6ae2ae59f3

        # h1 = Digest.sha256(int.to_bytes(1000, 2, 'little'), is_hex=True)
        # h2 = Digest.sha256(int.to_bytes(89, 1, 'little'), is_hex=True)
        # h = hex(int(h1, 16) ^ int(h2, 16))[2::]
        # self.assertEqual('4307fbbb7e5b7c8f0339b060d171c49c881901d78ab712e60d805af9f9dc4ca1', h1)
        # self.assertEqual('18f5384d58bcb1bba0bcd9e6a6781d1a6ac2cc280c330ecbab6cb7931b721552', h2)
        # self.assertEqual('5bf2c3f626e7cd34a38569867709d986e2dbcdff86841c2da6eced6ae2ae59f3', h)

        hash1 = Digest.sha256(bigint_to_neo_bytes(1000), 0).hex()
        print("hash1 is ", hash1, type(hash1))
        hash2 = Digest.sha256(bigint_to_neo_bytes(89), 0).hex()
        print("hash2 is ", hash2, type(hash2))
        h1 = (bytearray.fromhex(hash1))
        h1.reverse()
        h2 = (bytearray.fromhex(hash2))
        h2.reverse()
        res = int(h1.hex(), 16) ^ int(h2.hex(), 16)
        tmph = hex(res)
        h3 = bytearray.fromhex(tmph[2:])
        h3.reverse()
        hash3 = h3.hex()
        print("hash  is ", hash3)
        param_list1.append(1000)
        param_list1.append(89)
        param_list1.append(h3)
        param_list.append(param_list1)
        print("***** test1", param_list)
        hash = self.test_invoke(payerAcct, param_list)
        print("hash === test1", hash)
        # time.sleep(6)
        self.test_handleEvent("startNewRound", hash)
        return True
Esempio n. 14
0
 def decodeBase58(addr):
     data = base58.b58decode(addr)
     if len(data) != 25:
         raise TypeError
     if data[0] != int.from_bytes(Address.__COIN_VERSION, "little"):
         raise TypeError
     checksum = Digest.hash256(data[0:21])
     if data[21:25] != checksum[0:4]:
         raise TypeError
     return Address(data[1:21])
Esempio n. 15
0
 def get_privatekey_from_wif(self, wif: str):
     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]
Esempio n. 16
0
    def export_wif(self) -> str:
        """
        This interface is used to get export ECDSA private key in the form of WIF which
        is a way to encoding an ECDSA private key and make it easier to copy.

        :return: a WIF encode private key.
        """
        data = b''.join([b'\x80', self.__private_key, b'\01'])
        checksum = Digest.hash256(data[0:34])
        wif = base58.b58encode(b''.join([data, checksum[0:4]]))
        return wif.decode('ascii')
Esempio n. 17
0
    def export_wif(self) -> str:
        """
        This interface is used to get export ECDSA private key in the form of WIF which
        is a way to encoding an ECDSA private key and make it easier to copy.

        :return: a WIF encode private key.
        """
        data = b'\x80'
        data = data + self.serialize_private_key()
        data += b'\01'
        checksum = Digest.hash256(data[0:34])
        data += checksum[0:4]
        wif = base58.b58encode(data)
        return wif.decode('ascii')
Esempio n. 18
0
def pbkdf2(seed: str or bytes, dk_len: int) -> bytes:
    """
    Derive one key from a seed.

    :param seed: the secret pass phrase to generate the keys from.
    :param dk_len: the length in bytes of every derived key.
    :return:
    """
    key = b''
    index = 1
    bytes_seed = to_bytes(seed)
    while len(key) < dk_len:
        key += Digest.sha256(b''.join([bytes_seed, index.to_bytes(4, 'big', signed=True)]))
        index += 1
    return key[:dk_len]
Esempio n. 19
0
    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]
 def to_script_hash(byte_script):
     return a2b_hex(Digest.hash160(msg=byte_script, is_hex=True))
Esempio n. 21
0
 def b58encode(self):
     sb = Address.__COIN_VERSION + self.ZERO
     c256 = Digest.hash256(sb)[0:4]
     outb = sb + bytearray(c256)
     return base58.b58encode(bytes(outb)).decode('utf-8')
Esempio n. 22
0
 def test_sha256(self):
     msg = b'Nobody inspects the spammish repetition'
     sha256_digest = b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
     hex_sha256_digest = '031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
     self.assertEqual(sha256_digest, Digest.sha256(msg))
     self.assertEqual(hex_sha256_digest, Digest.sha256(msg, is_hex=True))
Esempio n. 23
0
 def test_hash160(self):
     msg = b'Nobody inspects the spammish repetition'
     hash160_digest = b'\x1c\x9b{H\x04\x9a\x8f\x98i\x9b\xca"\xa5\x85l^\xf5q\xcdh'
     hex_hash160_digest = '1c9b7b48049a8f98699bca22a5856c5ef571cd68'
     self.assertEqual(hash160_digest, Digest.hash160(msg))
     self.assertEqual(hex_hash160_digest, Digest.hash160(msg, is_hex=True))
Esempio n. 24
0
 def test_hash256(self):
     msg = b'Nobody inspects the spammish repetition'
     hash256_digest = b"\x9f>\x9eV\xb0\xe6K\x8a\xd0\xd8\xfd\xb4\x87\xfb\x0b\xfc\xfc\xd2\xb2x\xa3\xf2\x04\xdb\xc6t\x10\xdbL@\x90'"
     hex_hash256_digest = '9f3e9e56b0e64b8ad0d8fdb487fb0bfcfcd2b278a3f204dbc67410db4c409027'
     self.assertEqual(hash256_digest, Digest.hash256(msg))
     self.assertEqual(hex_hash256_digest, Digest.hash256(msg, is_hex=True))
Esempio n. 25
0
 def b58encode(self):
     data = Address.__COIN_VERSION + self.ZERO
     checksum = Digest.hash256(data)[0:4]
     return base58.b58encode(data + checksum).decode('utf-8')
Esempio n. 26
0
 def __from_byte_script(cls,
                        byte_script: bytes,
                        little_endian: bool = True):
     if not little_endian:
         return cls(Digest.hash160(msg=byte_script, is_hex=False)[::-1])
     return cls(Digest.hash160(msg=byte_script, is_hex=False))
Esempio n. 27
0
 def to_script_hash(byte_script) -> bytes:
     return Digest.hash160(msg=byte_script, is_hex=False)
Esempio n. 28
0
 def b58encode(self):
     script_builder = Address.__COIN_VERSION + self.ZERO
     c256 = Digest.hash256(script_builder)[0:4]
     out_bytes = script_builder + c256
     return base58.b58encode(out_bytes).decode('utf-8')
Esempio n. 29
0
 def test_getHash(self, value):
     hash1 = Digest.sha256(bigint_to_neo_bytes(value), 0).hex()
     return hash1
 def b58encode(self):
     script_builder = Address.__COIN_VERSION + self.ZERO
     c256 = Digest.hash256(script_builder)[0:4]
     out_byte_array = script_builder + bytearray(c256)
     return base58.b58encode(bytes(out_byte_array)).decode('utf-8')