# Path: keepkeylib/tools.py
# def parse_path(nstr):
#     """
#     Convert BIP32 path string to list of uint32 integers with hardened flags.
#     Several conventions are supported to set the hardened flag: -1, 1', 1h
#     e.g.: "0/1h/1" -> [0, 0x80000001, 1]
#     :param nstr: path string
#     :return: list of integers
#     """
#     if not nstr:
#         return []
# 
#     n = nstr.split('/')
# 
#     # m/a/b/c => a/b/c
#     if n[0] == 'm':
#         n = n[1:]
# 
#     # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
#     #if n[0] in slip44:
#     #    coin_id = slip44[n[0]]
#     #    n[0:1] = ['44h', '{}h'.format(coin_id)]
# 
#     def str_to_harden(x):
#         if x.startswith('-'):
#             return H_(abs(int(x)))
#         elif x.endswith(('h', "'")):
#             return H_(int(x[:-1]))
#         else:
#             return int(x)
# 
#     try:
#         return list(str_to_harden(x) for x in n)
#     except Exception:
#         raise ValueError('Invalid BIP32 path', nstr)
# 
# Path: keepkeylib/client.py
# class CallException(Exception):
#     def __init__(self, code, message):
#         super(CallException, self).__init__()
#         self.args = [code, message]
# 
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
#     def __init__(self, network, url):
#     def fetch_json(self, url, resource, resourceid):
#     def get_tx(self, txhash):
#     def __init__(self, network, url, zcash=None):
#     def get_tx(self, txhash):
#     def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):


import unittest
import common
import binascii
import itertools
import pytest
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
from binascii import unhexlify
from keepkeylib.tools import parse_path
from keepkeylib.client import CallException
from keepkeylib import tx_api
        out2 = proto_types.TxOutputType(address_n=[3],  # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5
                              amount=100000,
                              script_type=proto_types.PAYTOADDRESS,
                              )

        global run_attack
        run_attack = False

        def attack_processor(req, msg):
            global run_attack

            if req.details.tx_hash != b'':
                return msg

            if req.details.request_index != 1:
                return msg

            if not run_attack:
                run_attack = True
                return msg

            msg.outputs[0].amount = 9999999  # Sign output with another amount
            return msg

        # Test if the transaction can be signed normally
        (_, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2], None, True)

        # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb

        # Now run the attack, must trigger the exception

# Path: keepkeylib/tools.py
# def parse_path(nstr):
#     """
#     Convert BIP32 path string to list of uint32 integers with hardened flags.
#     Several conventions are supported to set the hardened flag: -1, 1', 1h
#     e.g.: "0/1h/1" -> [0, 0x80000001, 1]
#     :param nstr: path string
#     :return: list of integers
#     """
#     if not nstr:
#         return []
# 
#     n = nstr.split('/')
# 
#     # m/a/b/c => a/b/c
#     if n[0] == 'm':
#         n = n[1:]
# 
#     # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
#     #if n[0] in slip44:
#     #    coin_id = slip44[n[0]]
#     #    n[0:1] = ['44h', '{}h'.format(coin_id)]
# 
#     def str_to_harden(x):
#         if x.startswith('-'):
#             return H_(abs(int(x)))
#         elif x.endswith(('h', "'")):
#             return H_(int(x[:-1]))
#         else:
#             return int(x)
# 
#     try:
#         return list(str_to_harden(x) for x in n)
#     except Exception:
#         raise ValueError('Invalid BIP32 path', nstr)
# 
# Path: keepkeylib/client.py
# class CallException(Exception):
#     def __init__(self, code, message):
#         super(CallException, self).__init__()
#         self.args = [code, message]
# 
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
#     def __init__(self, network, url):
#     def fetch_json(self, url, resource, resourceid):
#     def get_tx(self, txhash):
#     def __init__(self, network, url, zcash=None):
#     def get_tx(self, txhash):
#     def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):


# Path: tests/test_msg_signtx_raw.py
import unittest
import common
import binascii
import itertools
import pytest
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
from binascii import unhexlify
from keepkeylib.tools import parse_path
from keepkeylib.client import CallException
from keepkeylib import tx_api

        out2 = proto_types.TxOutputType(address_n=[3],  # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5
                              amount=100000,
                              script_type=proto_types.PAYTOADDRESS,
                              )

        global run_attack
        run_attack = False

        def attack_processor(req, msg):
            global run_attack

            if req.details.tx_hash != b'':
                return msg

            if req.details.request_index != 1:
                return msg

            if not run_attack:
                run_attack = True
                return msg

            msg.outputs[0].amount = 9999999  # Sign output with another amount
            return msg

        # Test if the transaction can be signed normally
        (_, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2], None, True)

        # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb

        # Now run the attack, must trigger the exception

        pytest.raises(CallException, self.client.sign_tx, 'Bitcoin', [inp1, inp2], [out1, out2], 1, 0, attack_processor)