Пример #1
0
    def test_script_hash(self):
        # Expected output taken from running: getHash(Buffer.from('abc', 'utf8')).toString('hex')
        # using https://github.com/CityOfZion/neon-wallet-react-native/blob/master/app/api/crypto/index.js
        expected_result = b'bb1be98c142444d7a56aa3981c3942a978e4dc33'

        result = Crypto.Default().Hash160(b'abc')
        self.assertEqual(expected_result, binascii.hexlify(result))
Пример #2
0
    def ToScriptHash(self, address):
        """
        Retrieve the script_hash based from an address.

        Args:
            address (str): a base58 encoded address.

        Raises:
            ValuesError: if an invalid address is supplied or the coin version is incorrect
            Exception: if the address string does not start with 'A' or the checksum fails

        Returns:
            UInt160: script hash.
        """
        if len(address) == 34:
            if address[0] == 'A':
                data = b58decode(address)
                if data[0] != self.AddressVersion:
                    raise ValueError('Not correct Coin Version')

                checksum = Crypto.Default().Hash256(data[:21])[:4]
                if checksum != data[21:]:
                    raise Exception('Address format error')
                return UInt160(data=data[1:21])
            else:
                raise Exception('Address format error')
        else:
            raise ValueError('Not correct Address, wrong length.')
Пример #3
0
    def __init__(self, trigger_type, container, table, service, gas, testMode=False, exit_on_error=False):

        super(ApplicationEngine, self).__init__(container=container, crypto=Crypto.Default(), table=table, service=service, exit_on_error=exit_on_error)

        self.Trigger = trigger_type
        self.gas_amount = self.gas_free + gas.value
        self.testMode = testMode
        self._is_stackitem_count_strict = True
Пример #4
0
def execute_test(data: dict):
    global test_count, skipped_test_count
    for test in data['tests']:
        test_count += 1
        # interop service
        service = InteropService.InteropService()

        # message provider
        script_container = None

        message = test.get("message", None)
        if message:
            script_container = MessageProvider(message)

        # prepare script table
        script_table = None  # there are currently no tests that load a script table so I don't know the format or key value they'll use

        # create engine and run
        engine = ExecutionEngine(crypto=Crypto.Default(), service=service, container=script_container, table=script_table, exit_on_error=True)

        # TODO: should enforce 0x<data> rule in the JSON test case
        if test['script'].startswith('0x'):
            script = test['script'][2:]
        else:
            script = test['script']
        try:
            script = binascii.unhexlify(script)
        except binascii.Error:
            print(f"Skipping test {data['category']}-{data['name']}, cannot read script data")
            test_count -= 1
            skipped_test_count += 1
            continue

        engine.LoadScript(script)

        steps = test.get('steps', None)
        if steps is None:
            continue

        for i, step in enumerate(steps):
            actions = step.get('actions', [])
            for action in actions:
                if action == "StepInto":
                    engine.StepInto()
                elif action == "Execute":
                    engine.Execute()
                elif action == "StepOver":
                    raise ValueError("StepOver not supported!")
                elif action == "StepOut":
                    raise ValueError("StepOut not supported!")

            test_name = test.get("name", "")
            msg = f"{data['category']}-{data['name']}-{test_name}-{i}"
            assert_result(engine, step['result'], msg)
Пример #5
0
    def test_sign_and_verify_str(self):
        privkey = KeyPair.PrivateKeyFromWIF(
            "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
        keypair = KeyPair(privkey)
        hashdata = "74657374"

        keypair_signature = Crypto.Sign(hashdata, bytes(keypair.PrivateKey))
        keypair_signature2 = Crypto.Default().Sign(hashdata,
                                                   bytes(keypair.PrivateKey))
        self.assertEqual(keypair_signature, keypair_signature2)

        # verify without unhexing
        verification_result = Crypto.VerifySignature("test",
                                                     keypair_signature,
                                                     keypair.PublicKey,
                                                     unhex=False)
        verification_result2 = Crypto.Default().VerifySignature(
            "test", keypair_signature, keypair.PublicKey, unhex=False)
        self.assertEqual(verification_result, verification_result2)
        self.assertTrue(verification_result)
Пример #6
0
    def test_sign_and_verify(self):
        privkey = KeyPair.PrivateKeyFromWIF(
            "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
        keypair = KeyPair(privkey)
        hashdata = b'aabbcc'

        keypair_signature = Crypto.Sign(hashdata, bytes(keypair.PrivateKey))
        keypair_signature2 = Crypto.Default().Sign(hashdata,
                                                   bytes(keypair.PrivateKey))
        self.assertEqual(keypair_signature, keypair_signature2)

        verification_result = Crypto.VerifySignature(hashdata.decode('utf8'),
                                                     keypair_signature,
                                                     keypair.PublicKey)
        verification_result2 = Crypto.Default().VerifySignature(
            hashdata.decode('utf8'), keypair_signature, keypair.PublicKey)
        self.assertEqual(verification_result, verification_result2)
        self.assertTrue(verification_result)

        # verify with compressed key
        verification_result3 = Crypto.VerifySignature(
            hashdata.decode('utf8'), keypair_signature,
            binascii.unhexlify(keypair.PublicKey.encode_point(True)))
        self.assertTrue(verification_result3)

        # verify without unhexxing
        verification_result4 = Crypto.VerifySignature(
            binascii.unhexlify(hashdata),
            keypair_signature,
            binascii.unhexlify(keypair.PublicKey.encode_point(True)),
            unhex=False)
        self.assertTrue(verification_result4)

        # this should fail because the signature will not match the input data
        verification_result = Crypto.VerifySignature(b'aabb',
                                                     keypair_signature,
                                                     keypair.PublicKey)
        self.assertFalse(verification_result)
Пример #7
0
    def Sign(verifiable, keypair):
        """
        Sign the `verifiable` object with the private key from `keypair`.

        Args:
            verifiable:
            keypair (neo.Core.KeyPair):

        Returns:
            bool: True if successfully signed. False otherwise.
        """
        prikey = bytes(keypair.PrivateKey)
        hashdata = verifiable.GetHashData()
        res = Crypto.Default().Sign(hashdata, prikey)
        return res
Пример #8
0
    def SignMessage(self, message, script_hash):
        """
        Sign a message with a specified script_hash.

        Args:
            message (str): a hex encoded message to sign
            script_hash (UInt160): a bytearray (len 20).

        Returns:
            str: the signed message
        """

        keypair = self.GetKeyByScriptHash(script_hash)
        prikey = bytes(keypair.PrivateKey)
        res = Crypto.Default().Sign(message, prikey)
        return res, keypair.PublicKey
Пример #9
0
    def Export(self):
        """
        Export this KeyPair's private key in WIF format.

        Returns:
            str: The key in wif format
        """
        data = bytearray(38)
        data[0] = 0x80
        data[1:33] = self.PrivateKey[0:32]
        data[33] = 0x01

        checksum = Crypto.Default().Hash256(data[0:34])
        data[34:38] = checksum[0:4]
        b58 = base58.b58encode(bytes(data))

        return b58.decode("utf-8")
Пример #10
0
    def __init__(self,
                 trigger_type,
                 container,
                 snapshot,
                 gas,
                 testMode=False,
                 exit_on_error=True):

        super(ApplicationEngine,
              self).__init__(container=container,
                             crypto=Crypto.Default(),
                             table=snapshot,
                             service=StateMachine(trigger_type, snapshot),
                             exit_on_error=exit_on_error)

        self.gas_amount = self.gas_free + gas.value
        self.testMode = testMode
        self.snapshot = snapshot
        self._is_stackitem_count_strict = True
        self.debugger = None
        self.gas_consumed = 0
        self.invocation_args = None
Пример #11
0
    def AddrStrToScriptHash(address):
        """
        Convert a public address to a script hash.

        Args:
            address (str): base 58 check encoded public address.

        Raises:
            ValueError: if the address length of address version is incorrect.
            Exception: if the address checksum fails.

        Returns:
            UInt160:
        """
        data = b58decode(address)
        if len(data) != 25:
            raise ValueError('Not correct Address, wrong length.')
        if data[0] != settings.ADDRESS_VERSION:
            raise ValueError('Not correct Coin Version')

        checksum = Crypto.Default().Hash256(data[:21])[:4]
        if checksum != data[21:]:
            raise Exception('Address format error')
        return UInt160(data=data[1:21])
Пример #12
0
 def setUp(self):
     self.engine = ExecutionEngine(crypto=Crypto.Default())
     self.econtext = ExecutionContext(engine=self.engine)
Пример #13
0
 def Add(self, script: bytearray) -> None:
     h = bytearray(Crypto.Default().Hash160(script))
     h.reverse()
     self.data[binascii.hexlify(h)] = script
Пример #14
0
 def setUp(self):
     self.engine = ExecutionEngine(crypto=Crypto.Default())
     self.econtext = ExecutionContext(Script(self.engine.Crypto, b''), 0)
     self.engine.InvocationStack.PushT(self.econtext)
Пример #15
0
 def setUp(self):
     self.engine = ExecutionEngine(crypto=Crypto.Default())
     self.econtext = ExecutionContext(Script(self.engine.Crypto, b''), 0)
     self.engine.InvocationStack.PushT(self.econtext)
     snapshot = GetBlockchain()._db.createSnapshot()
     self.state_reader = StateReader(TriggerType.Application, snapshot)