示例#1
0
 def make_etx_spec(self, our, their):
     our_color_def = self.resolve_color_spec(our['color_spec'])
     our_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [our_color_def.get_color_id()])
     their_color_def = self.resolve_color_spec(their['color_spec'])
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their_color_def.get_color_id()])
     extra_value = 0
     if our_color_def == UNCOLORED_MARKER:
         # pay fee + padding for one colored outputs
         extra_value = 10000 + 8192 * 1
     c_utxos, c_change = self.select_inputs(
         SimpleColorValue(colordef=our_color_def,
                          value=our['value'] + extra_value))
     inputs = {our['color_spec']: 
               [utxo.get_outpoint() for utxo in c_utxos]}
     wam = self.model.get_address_manager()
     our_address = wam.get_change_address(their_color_set)
     targets = [(our_address.get_address(),
                 their['color_spec'], their['value'])]
     if c_change > 0:
         our_change_address = wam.get_change_address(our_color_set)
         targets.append((our_change_address.get_address(),
                         our['color_spec'], c_change.get_value()))
     return ETxSpec(inputs, targets, c_utxos)
示例#2
0
 def test_add_asset_definition(self):
     colorset3 = ColorSet(self.colormap, [self.colormap.d[4]])
     def4 = {'monikers': ['test3'], 'color_set': colorset3.get_data()}
     self.adm.add_asset_definition(def4)
     self.assertTrue(
         self.adm.get_asset_by_moniker('test3').get_color_set().equals(
             colorset3))
示例#3
0
 def test_from_color_ids(self):
     self.assertTrue(self.colorset0.equals(ColorSet.from_color_ids(self.colormap, [0])))
     self.assertTrue(self.colorset3.equals(ColorSet.from_color_ids(self.colormap, [1, 2])))
     tmp = ColorSet.from_color_ids(self.colormap, [1, 2, 3])
     self.assertTrue(tmp.has_color_id(1))
     self.assertTrue(tmp.has_color_id(2))
     self.assertTrue(tmp.has_color_id(3))
示例#4
0
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [''])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {'monikers': ['bitcoin'],
                     'color_set': self.colorset0.get_data(),
                     'unit':100000000}
        self.def1 = {'monikers': ['test1'],
                     'color_set': self.colorset1.get_data(),
                     'unit':10}
        self.def2 = {'monikers': ['test2','test2alt'],
                     'color_set': self.colorset2.get_data(),
                     'unit':1}
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        self.assetvalue0 = AdditiveAssetValue(asset=self.asset0, value=5)
        self.assetvalue1 = AdditiveAssetValue(asset=self.asset0, value=6)
        self.assetvalue2 = AdditiveAssetValue(asset=self.asset1, value=7)

        self.assettarget0 = AssetTarget('address0', self.assetvalue0)
        self.assettarget1 = AssetTarget('address1', self.assetvalue1)
        self.assettarget2 = AssetTarget('address2', self.assetvalue2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)
示例#5
0
 def __init__(self, colormap, params):
     """Create an Asset for a color map <colormap> and configuration
     <params>. Note params has the color definitions used for this
     Asset.
     """
     self.monikers = params.get('monikers', [])
     self.color_set = ColorSet(colormap, params.get('color_set'))
     self.unit = int(params.get('unit', 1))
示例#6
0
class AssetDefinition(object):
    """Stores the definition of a particular asset, including its color set,
    it's name (moniker), and the wallet model that represents it.
    """
    def __init__(self, colormap, params):
        """Create an Asset for a color map <colormap> and configuration
        <params>. Note params has the color definitions used for this
        Asset.
        """
        self.monikers = params.get('monikers', [])
        self.color_set = ColorSet(colormap, params.get('color_set'))
        self.unit = int(params.get('unit', 1))

    def __repr__(self):
        return "%s: %s" % (self.monikers, self.color_set)

    def get_monikers(self):
        """Returns the list of monikers for this asset.
        """
        return self.monikers

    def get_color_set(self):
        """Returns the list of colors for this asset.
        """
        return self.color_set

    def get_colorvalue(self, utxo):
        """ return colorvalue for a given utxo"""
        if self.color_set.uncolored_only():
            return utxo.value
        else:
            if utxo.colorvalues:
                for cv in utxo.colorvalues:
                    if cv[0] in self.color_set.color_id_set:
                        return cv[1]
            raise Exception("cannot get colorvalue for UTXO: "
                            "no colorvalues available")

    def parse_value(self, portion):
        """Returns actual number of Satoshis for this Asset
        given the <portion> of the asset.
        """
        return int(float(portion) * self.unit)

    def format_value(self, atoms):
        """Returns a string representation of the portion of the asset.
        can involve rounding.  doesn't display insignificant zeros
        """
        return '{0:g}'.format(atoms / float(self.unit))

    def get_data(self):
        """Returns a JSON-compatible object that represents this Asset
        """
        return {
            "monikers": self.monikers,
            "color_set": self.color_set.get_data(),
            "unit": self.unit
        }
示例#7
0
class AssetDefinition(object):
    """Stores the definition of a particular asset, including its color set,
    it's name (moniker), and the wallet model that represents it.
    """
    def __init__(self, colormap, params):
        """Create an Asset for a color map <colormap> and configuration
        <params>. Note params has the color definitions used for this
        Asset.
        """
        self.monikers = params.get('monikers', [])
        self.color_set = ColorSet(colormap, params.get('color_set'))
        self.unit = int(params.get('unit', 1))

    def __repr__(self):
        return "%s: %s" % (self.monikers, self.color_set)

    def get_monikers(self):
        """Returns the list of monikers for this asset.
        """
        return self.monikers

    def get_color_set(self):
        """Returns the list of colors for this asset.
        """
        return self.color_set

    def get_colorvalue(self, utxo):
        """ return colorvalue for a given utxo"""
        if self.color_set.uncolored_only():
            return utxo.value
        else:
            if utxo.colorvalues:
                for cv in utxo.colorvalues:
                    if cv[0] in self.color_set.color_id_set:
                        return cv[1]
            raise Exception("cannot get colorvalue for UTXO: "
                            "no colorvalues available")

    def parse_value(self, portion):
        """Returns actual number of Satoshis for this Asset
        given the <portion> of the asset.
        """
        return int(float(portion) * self.unit)

    def format_value(self, atoms):
        """Returns a string representation of the portion of the asset.
        can involve rounding.  doesn't display insignificant zeros
        """
        return '{0:g}'.format(atoms / float(self.unit))

    def get_data(self):
        """Returns a JSON-compatible object that represents this Asset
        """
        return {
            "monikers": self.monikers,
            "color_set": self.color_set.get_data(),
            "unit": self.unit
            }
示例#8
0
    def __init__(self, colormap, config):
        """Create a deterministic wallet address manager given
        a color map <colormap> and a configuration <config>.
        Note address manager configuration is in the key "hdwam".
        """
        self.config = config
        self.testnet = config.get('testnet', False)
        self.colormap = colormap
        self.addresses = []

        # initialize the wallet manager if this is the first time
        #  this will generate a master key.
        params = config.get('hdwam', None)
        if params is None:
            params = self.init_new_wallet()

        # master key is stored in a separate config entry
        self.master_key = config['hdw_master_key']

        master = hashlib.sha512(self.master_key.decode('hex')).digest()

        # initialize a BIP-0032 wallet
        self.pycoin_wallet = Wallet(is_private=True, is_test=self.testnet,
                                    chain_code=master[32:],
                                    secret_exponent_bytes=master[:32])

        self.genesis_color_sets = params['genesis_color_sets']
        self.color_set_states = params['color_set_states']

        # import the genesis addresses
        for i, color_desc_list in enumerate(self.genesis_color_sets):
            addr = self.get_genesis_address(i)
            addr.color_set = ColorSet(self.colormap,
                                      color_desc_list)
            self.addresses.append(addr)

        # now import the specific color addresses
        for color_set_st in self.color_set_states:
            color_desc_list = color_set_st['color_set']
            max_index = color_set_st['max_index']
            color_set = ColorSet(self.colormap, color_desc_list)
            params = {
                'testnet': self.testnet,
                'pycoin_wallet': self.pycoin_wallet,
                'color_set': color_set
                }
            for index in xrange(max_index + 1):
                params['index'] = index
                self.addresses.append(BIP0032AddressRecord(**params))

        # import the one-off addresses from the config
        for addr_params in config.get('addresses', []):
            addr_params['testnet'] = self.testnet
            addr_params['color_set'] = ColorSet(self.colormap,
                                                addr_params['color_set'])
            address = LooseAddressRecord(**addr_params)
            self.addresses.append(address)
示例#9
0
 def test_from_color_ids(self):
     self.assertTrue(
         self.colorset0.equals(ColorSet.from_color_ids(self.colormap, [0])))
     self.assertTrue(
         self.colorset3.equals(
             ColorSet.from_color_ids(self.colormap, [1, 2])))
     tmp = ColorSet.from_color_ids(self.colormap, [1, 2, 3])
     self.assertTrue(tmp.has_color_id(1))
     self.assertTrue(tmp.has_color_id(2))
     self.assertTrue(tmp.has_color_id(3))
示例#10
0
class TestAddress(unittest.TestCase):
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap,
                                  [self.colormap.get_color_def(0).__repr__()])
        self.colorset1 = ColorSet(self.colormap, [d[1]])
        self.main_p = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
        self.main = LooseAddressRecord(address_data=self.main_p,
                                       color_set=self.colorset0,
                                       testnet=False)
        self.test_p = '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgyUY4Gk1'
        self.test = LooseAddressRecord(address_data=self.test_p,
                                       color_set=self.colorset1,
                                       testnet=True)

    def test_init(self):
        self.assertEqual(self.main.get_address(),
                         '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj')
        self.assertEqual(self.test.get_address(),
                         'mo3oihY41iwPco1GKwehHPHmxMT4Ld5W3q')
        self.assertRaises(EncodingError,
                          LooseAddressRecord,
                          address_data=self.main_p[:-2] + '88')
        self.assertRaises(EncodingError,
                          LooseAddressRecord,
                          address_data=self.test_p[:-2] + '88',
                          testnet=True)
        self.assertRaises(InvalidAddressError,
                          LooseAddressRecord,
                          address_data=self.main_p,
                          testnet=True)
        self.assertRaises(InvalidAddressError,
                          LooseAddressRecord,
                          address_data=self.test_p,
                          testnet=False)

    def test_get_color_set(self):
        self.assertEqual(self.main.get_color_set().__repr__(),
                         self.colorset0.__repr__())

    def test_get_color_address(self):
        self.assertEqual(self.main.get_color_address(),
                         '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj')
        self.assertEqual(self.test.get_color_address(),
                         'CP4YWLr8aAe4Hn@mo3oihY41iwPco1GKwehHPHmxMT4Ld5W3q')

    def test_get_data(self):
        self.assertEqual(self.main.get_data()['color_set'],
                         self.colorset0.get_data())
        self.assertEqual(self.main.get_data()['address_data'], self.main_p)
        self.assertEqual(self.test.get_data()['color_set'],
                         self.colorset1.get_data())
        self.assertEqual(self.test.get_data()['address_data'], self.test_p)
示例#11
0
 def __init__(self, colormap, params):
     """Create an Asset for a color map <colormap> and configuration
     <params>. Note params has the color definitions used for this
     Asset.
     """
     self.colormap = colormap
     self.monikers = params.get('monikers', [])
     # currently only single-color assets are supported
     assert len(params.get('color_set')) == 1
     self.color_set = ColorSet(colormap, params.get('color_set'))
     self.unit = int(params.get('unit', 1))
示例#12
0
 def setUp(self):
     self.colormap = MockColorMap()
     d = self.colormap.d
     self.colorset0 = ColorSet(self.colormap, [d[0]])
     self.colorset1 = ColorSet(self.colormap, [d[1]])
     self.main_p = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
     self.main = LooseAddressRecord(address_data=self.main_p,
                                    color_set=self.colorset0,
                                    testnet=False)
     self.test_p = '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgyUY4Gk1'
     self.test = LooseAddressRecord(address_data=self.test_p,
                                    color_set=self.colorset1,
                                    testnet=True)
示例#13
0
class TestAddress(unittest.TestCase):

    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [d[0]])
        self.colorset1 = ColorSet(self.colormap, [d[1]])
        self.main_p = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
        self.main = LooseAddressRecord(address_data=self.main_p,
                                       color_set=self.colorset0,
                                       testnet=False)
        self.test_p = '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgyUY4Gk1'
        self.test = LooseAddressRecord(address_data=self.test_p,
                                       color_set=self.colorset1,
                                       testnet=True)


    def test_init(self):
        self.assertEqual(self.main.get_address(),
                         '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj')
        self.assertEqual(self.test.get_address(),
                         'mo3oihY41iwPco1GKwehHPHmxMT4Ld5W3q')
        self.assertRaises(EncodingError, LooseAddressRecord,
                          address_data=self.main_p[:-2] + '88')
        self.assertRaises(EncodingError, LooseAddressRecord,
                          address_data=self.test_p[:-2] + '88',
                          testnet=True)
        self.assertRaises(InvalidAddressError, LooseAddressRecord,
                          address_data=self.main_p, testnet=True)
        self.assertRaises(InvalidAddressError, LooseAddressRecord,
                          address_data=self.test_p, testnet=False)

    def test_get_color_set(self):
        self.assertEqual(self.main.get_color_set().__repr__(),
                         self.colorset0.__repr__())

    def test_get_color_address(self):
        self.assertEqual(self.main.get_color_address(),
                         '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj')
        self.assertEqual(self.test.get_color_address(),
                         'CP4YWLr8aAe4Hn@mo3oihY41iwPco1GKwehHPHmxMT4Ld5W3q')

    def test_get_data(self):
        self.assertEqual(self.main.get_data()['color_set'],
                         self.colorset0.get_data())
        self.assertEqual(self.main.get_data()['address_data'],
                         self.main_p)
        self.assertEqual(self.test.get_data()['color_set'],
                         self.colorset1.get_data())
        self.assertEqual(self.test.get_data()['address_data'],
                         self.test_p)
示例#14
0
 def setUp(self):
     self.colormap = MockColorMap()
     d = self.colormap.d
     self.colorset0 = ColorSet(self.colormap,
                               [self.colormap.get_color_def(0).__repr__()])
     self.colorset1 = ColorSet(self.colormap, [d[1]])
     self.main_p = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
     self.main = LooseAddressRecord(address_data=self.main_p,
                                    color_set=self.colorset0,
                                    testnet=False)
     self.test_p = '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgyUY4Gk1'
     self.test = LooseAddressRecord(address_data=self.test_p,
                                    color_set=self.colorset1,
                                    testnet=True)
示例#15
0
 def setUp(self):
     self.colormap = MockColorMap()
     d = self.colormap.d
     self.colorset0 = ColorSet(self.colormap, [''])
     self.colorset1 = ColorSet(self.colormap, [d[1]])
     self.colorset1alt = ColorSet(self.colormap, [d[1],d[6]])
     self.colorset2 = ColorSet(self.colormap, [d[2]])
     self.colorset3 = ColorSet(self.colormap, [d[3], d[4]])
     self.def1 = {'monikers': ['test1'],
                  'color_set': self.colorset1.get_data(),
                  'unit':10}
     self.asset1 = AssetDefinition(self.colormap, self.def1)
     self.master_key = '265a1a0ad05e82fa321e3f6f6767679df0c68515797e0e4e24be1afc3272ee658ec53cecb683ab76a8377273347161e123fddf5320cbbce8849b0a00557bd12c'
     self.privkey = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
     self.pubkey = '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj'
     c = {
         'dw_master_key': self.master_key,
         'dwam': {
             'genesis_color_sets':[self.colorset1.get_data(),
                                   self.colorset2.get_data()],
             'color_set_states':[
                 {'color_set':self.colorset0.get_data(), "max_index":0},
                 {'color_set':self.colorset1.get_data(), "max_index":3},
                 {'color_set':self.colorset2.get_data(), "max_index":2},
                 ],
             },
         'addresses':[{'address_data': self.privkey,
                       'color_set': self.colorset1.get_data(),
                       }],
         'testnet': False,
         }
     self.config = copy.deepcopy(c)
     self.maindwam = DWalletAddressManager(self.colormap, c)
示例#16
0
    def __init__(self, colormap, config):
        """Create a deterministic wallet address manager given
        a colormap <colormap> and a configuration <config>.
        Note address manager configuration is in the key "dwam".
        """
        self.config = config
        self.testnet = config.get('testnet', False)
        self.colormap = colormap
        self.addresses = []

        # initialize the wallet manager if this is the first time
        #  this will generate a master key.
        params = config.get('dwam', None)
        if params is None:
            params = self.init_new_wallet()

        # master key is stored in a separate config entry
        self.master_key = config['dw_master_key']

        self.genesis_color_sets = params['genesis_color_sets']
        self.color_set_states = params['color_set_states']

        # import the genesis addresses
        for i, color_desc_list in enumerate(self.genesis_color_sets):
            addr = self.get_genesis_address(i)
            addr.color_set = ColorSet(self.colormap, color_desc_list)
            self.addresses.append(addr)

        # now import the specific color addresses
        for color_set_st in self.color_set_states:
            color_desc_list = color_set_st['color_set']
            max_index = color_set_st['max_index']
            color_set = ColorSet(self.colormap, color_desc_list)
            params = {
                'testnet': self.testnet,
                'master_key': self.master_key,
                'color_set': color_set
            }
            for index in xrange(max_index + 1):
                params['index'] = index
                self.addresses.append(DeterministicAddressRecord(**params))

        # import the one-off addresses from the config
        for addr_params in config.get('addresses', []):
            addr_params['testnet'] = self.testnet
            addr_params['color_set'] = ColorSet(self.colormap,
                                                addr_params['color_set'])
            address = LooseAddressRecord(**addr_params)
            self.addresses.append(address)
示例#17
0
 def get_asset_value_for_colorvalue(self, colorvalue):
     colorset = ColorSet.from_color_ids(self.colormap,
                                        [colorvalue.get_color_id()])
     asset = self.find_asset_by_color_set(colorset)
     if not asset:
         raise Exception('asset not found')
     return AdditiveAssetValue(asset=asset, value=colorvalue.get_value())
示例#18
0
 def make_etx_spec(self, our, their):
     fee = FEE if our.get_colordef() == UNCOLORED_MARKER else 0
     c_utxos, c_change = self.select_inputs(our + fee)
     inputs = {our.get_colordef(): 
               [utxo.get_outpoint() for utxo in c_utxos]}
     wam = self.model.get_address_manager()
     our_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                             [our.get_color_id()]) 
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their.get_color_id()]) 
     our_address = wam.get_change_address(their_color_set)
     targets = [ColorTarget(our_address.get_address(), their)]
     if c_change > 0:
         our_change_address = wam.get_change_address(our_color_set)
         targets.append(ColorTarget(our_change_address.get_address(),
                                    c_change))
     return ETxSpec(inputs, targets, c_utxos)
示例#19
0
 def __init__(self, colormap, params):
     """Create an Asset for a color map <colormap> and configuration
     <params>. Note params has the color definitions used for this
     Asset.
     """
     self.monikers = params.get('monikers', [])
     self.color_set = ColorSet(colormap, params.get('color_set'))
     self.unit = int(params.get('unit', 1))
示例#20
0
 def get_asset_value_for_colorvalue(self, colorvalue):
     colorset = ColorSet.from_color_ids(self.colormap, 
                                        [colorvalue.get_color_id()])
     asset = self.find_asset_by_color_set(colorset)
     if not asset:
         raise Exception('asset not found')
     return AdditiveAssetValue(asset=asset,
                               value=colorvalue.get_value())
示例#21
0
 def increment_max_index_for_color_set(self, color_set):
     """Given a color <color_set>, record that there is one more
     new address for that color.
     """
     # TODO: speed up, cache(?)
     for color_set_st in self.color_set_states:
         color_desc_list = color_set_st['color_set']
         max_index = color_set_st['max_index']
         cur_color_set = ColorSet(self.colormap,
                                  color_desc_list)
         if cur_color_set.equals(color_set):
             max_index += 1
             color_set_st['max_index'] = max_index
             return max_index
     self.color_set_states.append({"color_set": color_set.get_data(),
                                   "max_index": 0})
     return 0
示例#22
0
 def increment_max_index_for_color_set(self, color_set):
     """Given a color <color_set>, record that there is one more
     new address for that color.
     """
     # TODO: speed up, cache(?)
     for color_set_st in self.color_set_states:
         color_desc_list = color_set_st['color_set']
         max_index = color_set_st['max_index']
         cur_color_set = ColorSet(self.colormap, color_desc_list)
         if cur_color_set.equals(color_set):
             max_index += 1
             color_set_st['max_index'] = max_index
             return max_index
     self.color_set_states.append({
         "color_set": color_set.get_data(),
         "max_index": 0
     })
     return 0
示例#23
0
 def prepare_targets(self, etx_spec, their):
     self.targets = etx_spec.targets
     wam = self.model.get_address_manager()
     colormap = self.model.get_color_map()
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their.get_color_id()]) 
     ct = ColorTarget(wam.get_change_address(their_color_set).get_address(),
                      their)
     self.targets.append(ct)
示例#24
0
 def make_etx_spec(self, our, their):
     fee = FEE if our.get_colordef() == UNCOLORED_MARKER else 0
     c_utxos, c_change = self.select_inputs(our + fee)
     inputs = {
         our.get_colordef(): [utxo.get_outpoint() for utxo in c_utxos]
     }
     wam = self.model.get_address_manager()
     our_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                             [our.get_color_id()])
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their.get_color_id()])
     our_address = wam.get_change_address(their_color_set)
     targets = [ColorTarget(our_address.get_address(), their)]
     if c_change > 0:
         our_change_address = wam.get_change_address(our_color_set)
         targets.append(
             ColorTarget(our_change_address.get_address(), c_change))
     return ETxSpec(inputs, targets, c_utxos)
示例#25
0
 def prepare_targets(self, etx_spec, their):
     self.targets = etx_spec.targets
     wam = self.model.get_address_manager()
     colormap = self.model.get_color_map()
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their.get_color_id()])
     ct = ColorTarget(
         wam.get_change_address(their_color_set).get_address(), their)
     self.targets.append(ct)
示例#26
0
 def get_genesis_address(self, genesis_index):
     """Given the index <genesis_index>, will return
     the BIP0032 Address Record associated with that
     index. In general, that index corresponds to the nth
     color created by this wallet.
     """
     return BIP0032AddressRecord(pycoin_wallet=self.pycoin_wallet,
                                 color_set=ColorSet(self.colormap, []),
                                 index=genesis_index,
                                 testnet=self.testnet)
示例#27
0
文件: asset.py 项目: F483/ngcccbase
 def __init__(self, colormap, params):
     """Create an Asset for a color map <colormap> and configuration
     <params>. Note params has the color definitions used for this
     Asset.
     """
     self.colormap = colormap
     self.monikers = params.get('monikers', [])
     # currently only single-color assets are supported
     assert len(params.get('color_set')) == 1
     self.color_set = ColorSet(colormap, params.get('color_set'))
     self.unit = int(params.get('unit', 1))
示例#28
0
 def get_genesis_address(self, genesis_index):
     """Given the index <genesis_index>, will return
     the Deterministic Address Record associated with that
     index. In general, that index corresponds to the nth
     color created by this wallet.
     """
     return DeterministicAddressRecord(master_key=self.master_key,
                                       color_set=ColorSet(
                                           self.colormap, []),
                                       index=genesis_index,
                                       testnet=self.testnet)
示例#29
0
 def setUp(self):
     self.colormap = MockColorMap()
     d = self.colormap.d
     self.colorset0 = ColorSet(self.colormap, [""])
     self.colorset1 = ColorSet(self.colormap, [d[1]])
     self.colorset2 = ColorSet(self.colormap, [d[2]])
     self.colorset3 = ColorSet(self.colormap, [d[1], d[2]])
     self.colorset4 = ColorSet(self.colormap, [d[3], d[2]])
     self.colorset5 = ColorSet(self.colormap, [d[3], d[1]])
     self.colorset6 = ColorSet(self.colormap, [])
    def setUp(self):
        self.path = ":memory:"
        self.config = {
            'dw_master_key': 'test',
            'testnet': True,
            'ccc': {
                'colordb_path': self.path
            },
            'bip0032': False
        }
        self.pwallet = PersistentWallet(self.path, self.config)
        self.pwallet.init_model()
        self.model = self.pwallet.get_model()
        self.wc = WalletController(self.model)
        self.wc.testing = True
        self.wc.debug = True
        self.colormap = self.model.get_color_map()
        self.bcolorset = ColorSet(self.colormap, [''])
        wam = self.model.get_address_manager()
        self.baddress = wam.get_new_address(self.bcolorset)
        self.baddr = self.baddress.get_address()

        self.blockhash = '00000000c927c5d0ee1ca362f912f83c462f644e695337ce3731b9f7c5d1ca8c'
        self.txhash = '4fe45a5ba31bab1e244114c4555d9070044c73c98636231c77657022d76b87f7'

        script = tools.compile(
            "OP_DUP OP_HASH160 {0} OP_EQUALVERIFY OP_CHECKSIG".format(
                self.baddress.rawPubkey().encode("hex"))).encode("hex")

        self.model.utxo_man.store.add_utxo(self.baddr, self.txhash, 0, 100,
                                           script)

        script = tools.compile(
            "OP_DUP OP_HASH160 {0} OP_EQUALVERIFY OP_CHECKSIG".format(
                self.baddress.rawPubkey().encode("hex"))).encode("hex")

        self.model.utxo_man.store.add_utxo(self.baddr, self.txhash, 1,
                                           1000000000, script)

        self.model.ccc.blockchain_state.bitcoind = MockBitcoinD('test')

        def x(s):
            return self.blockhash, True

        self.model.ccc.blockchain_state.get_tx_blockhash = x
        self.moniker = 'test'
        self.wc.issue_coins(self.moniker, 'obc', 10000, 1)
        self.asset = self.model.get_asset_definition_manager(
        ).get_asset_by_moniker(self.moniker)
        self.basset = self.model.get_asset_definition_manager(
        ).get_asset_by_moniker('bitcoin')
        self.color_id = list(self.asset.color_set.color_id_set)[0]
        self.model.ccc.metastore.set_as_scanned(self.color_id, self.blockhash)
示例#31
0
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [d[0]])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {'monikers': ['bitcoin'],
                     'color_set': self.colorset0.get_data(),
                     'unit':100000000}
        self.def1 = {'monikers': ['test1'],
                     'color_set': self.colorset1.get_data(),
                     'unit':10}
        self.def2 = {'monikers': ['test2','test2alt'],
                     'color_set': self.colorset2.get_data(),
                     'unit':1}
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)
示例#32
0
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [d[0]])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {
            'monikers': ['bitcoin'],
            'color_set': self.colorset0.get_data(),
            'unit': 100000000
        }
        self.def1 = {
            'monikers': ['test1'],
            'color_set': self.colorset1.get_data(),
            'unit': 10
        }
        self.def2 = {
            'monikers': ['test2', 'test2alt'],
            'color_set': self.colorset2.get_data(),
            'unit': 1
        }
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)
示例#33
0
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [''])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {
            'monikers': ['bitcoin'],
            'color_set': self.colorset0.get_data(),
            'unit': 100000000
        }
        self.def1 = {
            'monikers': ['test1'],
            'color_set': self.colorset1.get_data(),
            'unit': 10
        }
        self.def2 = {
            'monikers': ['test2', 'test2alt'],
            'color_set': self.colorset2.get_data(),
            'unit': 1
        }
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        self.assetvalue0 = AdditiveAssetValue(asset=self.asset0, value=5)
        self.assetvalue1 = AdditiveAssetValue(asset=self.asset0, value=6)
        self.assetvalue2 = AdditiveAssetValue(asset=self.asset1, value=7)

        self.assettarget0 = AssetTarget('address0', self.assetvalue0)
        self.assettarget1 = AssetTarget('address1', self.assetvalue1)
        self.assettarget2 = AssetTarget('address2', self.assetvalue2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)
示例#34
0
 def make_query(self, query):
     """Create a UTXOQuery from query <query>. Queries are dicts with:
     color_set - color associated with this query
     """
     color_set = query.get('color_set')
     if not color_set:
         if 'color_id_set' in query:
             color_set = ColorSet.from_color_ids(
                 self.model.get_color_map(), query['color_id_set'])
         elif 'asset' in query:
             color_set = query['asset'].get_color_set()
         else:
             raise Exception('color set is not specified')
     return UTXOQuery(self.model, color_set)
示例#35
0
 def make_query(self, query):
     """Create a UTXOQuery from query <query>. Queries are dicts with:
     color_set - color associated with this query
     """
     color_set = query.get('color_set')
     if not color_set:
         if 'color_id_set' in query:
             color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                                 query['color_id_set'])
         elif 'asset' in query:
             color_set = query['asset'].get_color_set()
         else:
             raise Exception('color set is not specified')
     return UTXOQuery(self.model, color_set)
示例#36
0
 def get_change_addr(self, color_def):
     """Get an address associated with color definition <color_def>
     that is in the current wallet for receiving change.
     """
     color_id = color_def.color_id
     wam = self.model.get_address_manager()
     color_set = None
     if color_def == UNCOLORED_MARKER:
         color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                             [0])
     elif self.asset.get_color_set().has_color_id(color_id):
         color_set = self.asset.get_color_set()
     if color_set is None:
         raise InvalidColorIdError('wrong color id')
     aw = wam.get_change_address(color_set)
     return aw.get_address()
示例#37
0
 def prepare_targets(self, etx_spec, their):
     self.targets = []
     for address, color_spec, value in etx_spec.targets:
         colordef = self.ewctrl.resolve_color_spec(color_spec)
         self.targets.append(ColorTarget(address, 
                                    SimpleColorValue(colordef=colordef,
                                                     value=value)))
     wam = self.model.get_address_manager()
     colormap = self.model.get_color_map()
     their_colordef = self.ewctrl.resolve_color_spec(their['color_spec'])
     their_color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                               [their_colordef.get_color_id()])
     ct = ColorTarget(wam.get_change_address(their_color_set).get_address(),
                      SimpleColorValue(colordef=their_colordef,
                                       value=their['value']))
     self.targets.append(ct)
示例#38
0
 def setUp(self):
     self.path = ":memory:"
     self.config = {
         'hdw_master_key':
             '91813223e97697c42f05e54b3a85bae601f04526c5c053ff0811747db77cfdf5f1accb50b3765377c379379cd5aa512c38bf24a57e4173ef592305d16314a0f4',
         'testnet': True,
         'ccc': {'colordb_path' : self.path},
         }
     self.pwallet = PersistentWallet(self.path, self.config)
     self.pwallet.init_model()
     self.model = self.pwallet.get_model()
     self.colormap = self.model.get_color_map()
     self.bcolorset = ColorSet(self.colormap, [''])
     self.basset = self.model.get_asset_definition_manager(
         ).get_asset_by_moniker('bitcoin')
     self.cqf = self.model.get_coin_query_factory()
示例#39
0
 def get_change_addr(self, color_def):
     """Get an address associated with color definition <color_def>
     that is in the current wallet for receiving change.
     """
     color_id = color_def.color_id
     wam = self.model.get_address_manager()
     color_set = None
     if color_def == UNCOLORED_MARKER:
         color_set = ColorSet.from_color_ids(self.model.get_color_map(),
                                             [0])
     elif self.asset.get_color_set().has_color_id(color_id):
         color_set = self.asset.get_color_set()
     if color_set is None:
         raise InvalidColorIdError('wrong color id')
     aw = wam.get_change_address(color_set)
     return aw.get_address()
示例#40
0
 def make_query(self, query):
     """Create a CoinQuery from query <query>. Queries are dicts with:
     color_set - color associated with this query
     """
     query = query.copy()
     color_set = query.get('color_set')
     if not color_set:
         if 'color_id_set' in query:
             color_set = ColorSet.from_color_ids(
                 self.model.get_color_map(), query['color_id_set'])
         elif 'asset' in query:
             color_set = query['asset'].get_color_set()
         else:
             raise Exception('Color set is not specified!')
     if 'spent' not in query:
         query['spent'] = False
     return CoinQuery(self.model, color_set, query)
示例#41
0
    def select_inputs(self, colorvalue):
        cs = ColorSet.from_color_ids(self.model.get_color_map(),
                                     [colorvalue.get_color_id()])

        cq = self.model.make_coin_query({"color_set": cs})
        utxo_list = cq.get_result()
        selection = []
        csum = SimpleColorValue(colordef=colorvalue.get_colordef(), value=0)

        for utxo in utxo_list:
            csum += SimpleColorValue.sum(utxo.colorvalues)
            selection.append(utxo)
            if csum >= colorvalue:
                break
        if csum < colorvalue:
            raise InsufficientFundsError('not enough money')
        return selection, (csum - colorvalue)
示例#42
0
    def select_inputs(self, colorvalue):
        cs = ColorSet.from_color_ids(self.model.get_color_map(),
                                     [colorvalue.get_color_id()])

        cq = self.model.make_coin_query({"color_set": cs})
        utxo_list = cq.get_result()
        selection = []
        csum = SimpleColorValue(colordef=colorvalue.get_colordef(), value=0)

        for utxo in utxo_list:
            csum += SimpleColorValue.sum(utxo.colorvalues)
            selection.append(utxo)
            if csum >= colorvalue:
                break
        if csum < colorvalue:
            raise InsufficientFundsError('not enough money')
        return selection, (csum - colorvalue)
示例#43
0
class TestDeterministic(unittest.TestCase):

    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [''])
        self.colorset1 = ColorSet(self.colormap, [d[1]])
        self.colorset1alt = ColorSet(self.colormap, [d[1],d[6]])
        self.colorset2 = ColorSet(self.colormap, [d[2]])
        self.colorset3 = ColorSet(self.colormap, [d[3], d[4]])
        self.def1 = {'monikers': ['test1'],
                     'color_set': self.colorset1.get_data(),
                     'unit':10}
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.master_key = '265a1a0ad05e82fa321e3f6f6767679df0c68515797e0e4e24be1afc3272ee658ec53cecb683ab76a8377273347161e123fddf5320cbbce8849b0a00557bd12c'
        self.privkey = '5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF'
        self.pubkey = '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj'
        c = {
            'dw_master_key': self.master_key,
            'dwam': {
                'genesis_color_sets':[self.colorset1.get_data(),
                                      self.colorset2.get_data()],
                'color_set_states':[
                    {'color_set':self.colorset0.get_data(), "max_index":0},
                    {'color_set':self.colorset1.get_data(), "max_index":3},
                    {'color_set':self.colorset2.get_data(), "max_index":2},
                    ],
                },
            'addresses':[{'address_data': self.privkey,
                          'color_set': self.colorset1.get_data(),
                          }],
            'testnet': False,
            }
        self.config = copy.deepcopy(c)
        self.maindwam = DWalletAddressManager(self.colormap, c)

    def test_init_new_wallet(self):
        c = copy.deepcopy(self.config)
        del c['dw_master_key']
        del c['dwam']
        newdwam = DWalletAddressManager(self.colormap, c)
        params = newdwam.init_new_wallet()
        self.assertNotEqual(self.config['dw_master_key'],
                            newdwam.config['dw_master_key'])

        c = copy.deepcopy(self.config)
        c['addresses'][0]['address_data'] = 'notreal'
        self.assertRaises(EncodingError, DWalletAddressManager,
                          self.colormap, c)

    def test_get_new_address(self):
        self.assertEqual(self.maindwam.get_new_address(self.colorset2).index,
                         3)
        self.assertEqual(self.maindwam.get_new_address(self.asset1).index,
                         4)

    def test_get_new_genesis_address(self):
        addr = self.maindwam.get_new_genesis_address()
        self.assertEqual(addr.index, 2)
        addr2 = self.maindwam.get_new_address(addr.get_color_set())
        self.assertEqual(addr2.index, 0)

    def test_get_update_genesis_address(self):
        addr = self.maindwam.get_genesis_address(0)
        self.maindwam.update_genesis_address(addr, self.colorset1alt)
        self.assertEqual(addr.get_color_set(), self.colorset1alt)

    def test_get_change_address(self):
        addr = self.maindwam.get_change_address(self.colorset0)
        self.assertEqual(addr.get_color_set().__repr__(),
                         self.colorset0.__repr__())
        self.assertEqual(self.maindwam.get_change_address(self.colorset3).index,
                         0)

    def test_get_all_addresses(self):
        addrs = [a.get_address() for a in self.maindwam.get_all_addresses()]
        self.assertTrue(self.pubkey in addrs)
示例#44
0
class TestAssetDefinition(unittest.TestCase):

    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [''])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {'monikers': ['bitcoin'],
                     'color_set': self.colorset0.get_data(),
                     'unit':100000000}
        self.def1 = {'monikers': ['test1'],
                     'color_set': self.colorset1.get_data(),
                     'unit':10}
        self.def2 = {'monikers': ['test2','test2alt'],
                     'color_set': self.colorset2.get_data(),
                     'unit':1}
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        self.assetvalue0 = AdditiveAssetValue(asset=self.asset0, value=5)
        self.assetvalue1 = AdditiveAssetValue(asset=self.asset0, value=6)
        self.assetvalue2 = AdditiveAssetValue(asset=self.asset1, value=7)

        self.assettarget0 = AssetTarget('address0', self.assetvalue0)
        self.assettarget1 = AssetTarget('address1', self.assetvalue1)
        self.assettarget2 = AssetTarget('address2', self.assetvalue2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)

    def test_repr(self):
        self.assertEquals(self.asset0.__repr__(), "['bitcoin']: ['']")
        self.assertEquals(
            self.asset1.__repr__(),
            "['test1']: ['obc:color_desc_1:0:0', 'obc:color_desc_2:0:1']")
        self.assertEquals(self.asset2.__repr__(),
                          "['test2', 'test2alt']: ['obc:color_desc_3:0:1']")

    def test_get_monikers(self):
        self.assertEquals(self.asset0.get_monikers(), ['bitcoin'])
        self.assertEquals(self.asset1.get_monikers(), ['test1'])
        self.assertEquals(self.asset2.get_monikers(), ['test2', 'test2alt'])

    def test_get_color_set(self):
        self.assertTrue(self.asset0.get_color_set().equals(self.colorset0))
        self.assertTrue(self.asset1.get_color_set().equals(self.colorset1))
        self.assertTrue(self.asset2.get_color_set().equals(self.colorset2))

    def test_get_colorvalue(self):
        g = {'txhash':'blah', 'height':1, 'outindex':0}
        cid0 = list(self.colorset0.color_id_set)[0]
        cdef0 = OBColorDefinition(cid0, g)
        cid1 = list(self.colorset1.color_id_set)[0]
        cdef1 = OBColorDefinition(cid1, g)
        cid2 = list(self.colorset2.color_id_set)[0]
        cdef2 = OBColorDefinition(cid2, g)
        cv0 = SimpleColorValue(colordef=cdef0, value=1)
        cv1 = SimpleColorValue(colordef=cdef1, value=2)
        cv2 = SimpleColorValue(colordef=cdef2, value=3)

        utxo = MockUTXO([cv0, cv1, cv2])

        self.assertEquals(self.asset0.get_colorvalue(utxo), cv0)
        self.assertEquals(self.asset1.get_colorvalue(utxo), cv1)
        self.assertEquals(self.asset2.get_colorvalue(utxo), cv2)

        utxo = MockUTXO([cv0, cv2])
        self.assertRaises(Exception, self.asset1.get_colorvalue, utxo)

    def test_parse_value(self):
        self.assertEquals(self.asset0.parse_value(1.25), 125000000)
        self.assertEquals(self.asset1.parse_value(2), 20)
        self.assertEquals(self.asset2.parse_value(5), 5)

    def test_format_value(self):
        self.assertEquals(self.asset0.format_value(10000),'0.0001')
        self.assertEquals(self.asset1.format_value(2),'0.2')
        self.assertEquals(self.asset2.format_value(5),'5')

    def test_get_data(self):
        self.assertEquals(self.asset0.get_data(), self.def0)
        self.assertEquals(self.asset1.get_data(), self.def1)
        self.assertEquals(self.asset2.get_data(), self.def2)

    def test_register_asset_definition(self):
        self.assertRaises(Exception, self.adm.register_asset_definition,
                          self.asset1)

    def test_add_asset_definition(self):
        colorset3 = ColorSet(self.colormap, [self.colormap.d[4]])
        def4 = {'monikers': ['test3'], 'color_set': colorset3.get_data()}
        self.adm.add_asset_definition(def4)
        self.assertTrue(self.adm.get_asset_by_moniker('test3').get_color_set()
                        .equals(colorset3))

    def test_all_assets(self):
        reprs = [asset.__repr__() for asset in self.adm.get_all_assets()]
        self.assertTrue(self.asset0.__repr__() in reprs)
        self.assertTrue(self.asset1.__repr__() in reprs)
        self.assertTrue(self.asset2.__repr__() in reprs)

    def test_get_asset_and_address(self):
        ch = self.asset1.get_color_set().get_color_hash()
        addr = '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj'
        coloraddress = "%s@%s" % (ch, addr)
        asset, address = self.adm.get_asset_and_address(coloraddress)
        self.assertEquals(asset.__repr__(), self.asset1.__repr__())
        self.assertEquals(addr, address)
        asset, address = self.adm.get_asset_and_address(addr)
        self.assertEquals(asset.__repr__(), self.asset0.__repr__())
        self.assertEquals(addr, address)
        self.assertRaises(Exception, self.adm.get_asset_and_address, '0@0')

    def test_add(self):
        assetvalue3 = self.assetvalue0 + self.assetvalue1
        self.assertEqual(assetvalue3.get_value(), 11)
        assetvalue3 = 0 + self.assetvalue1
        self.assertEqual(assetvalue3.get_value(), 6)
        self.assertRaises(IncompatibleTypesError, self.assetvalue0.__add__,
                          self.assetvalue2)

    def test_iadd(self):
        assetvalue = self.assetvalue0.clone()
        assetvalue += self.assetvalue1
        self.assertEqual(assetvalue.get_value(), 11)

    def test_sub(self):
        assetvalue = self.assetvalue1 - self.assetvalue0
        self.assertEqual(assetvalue.get_value(), 1)
        assetvalue = self.assetvalue1 - 0
        self.assertEqual(assetvalue.get_value(), self.assetvalue1.get_value())

    def test_lt(self):
        self.assertTrue(self.assetvalue0 < self.assetvalue1)
        self.assertTrue(self.assetvalue1 > self.assetvalue0)
        self.assertTrue(self.assetvalue1 >= self.assetvalue0)
        self.assertTrue(self.assetvalue1 > 0)

    def test_sum(self):
        assetvalues = [self.assetvalue0, self.assetvalue1,
                       AdditiveAssetValue(asset=self.asset0, value=3)]
        self.assertEqual(AdditiveAssetValue.sum(assetvalues).get_value(), 14)

    def test_get_asset(self):
        self.assertEqual(self.assettarget0.get_asset(), self.asset0)

    def test_get_value(self):
        self.assertEqual(self.assettarget0.get_value(), self.assetvalue0.get_value())

    def test_sum(self):
        assettargets = [self.assettarget0, self.assettarget1,
                        AssetTarget('address3',self.assettarget1)]
        self.assertEqual(AssetTarget.sum(assettargets).get_value(), 17)
        self.assertEqual(AssetTarget.sum([]), 0)

    def test_get_address(self):
        self.assertEqual(self.assettarget0.get_address(), 'address0')

    def test_repr(self):
        self.assertEqual(self.assettarget0.__repr__(), 'address0: Asset Value: 5')
示例#45
0
 def test_add_asset_definition(self):
     colorset3 = ColorSet(self.colormap, [self.colormap.d[4]])
     def4 = {'monikers': ['test3'], 'color_set': colorset3.get_data()}
     self.adm.add_asset_definition(def4)
     self.assertTrue(self.adm.get_asset_by_moniker('test3').get_color_set()
                     .equals(colorset3))
示例#46
0
 def resolve_color_spec(self, color_spec):
     colormap = self.model.get_color_map()
     color_id = colormap.resolve_color_desc(color_spec, False)
     if color_id is None:
         raise Exception("color spec not recognized")
     return ColorSet.from_color_ids(self.model.get_color_map(), [color_id])
示例#47
0
 def get_change_addr(self, color_def):
     color_id = color_def.color_id
     cs = ColorSet.from_color_ids(self.model.get_color_map(), [color_id])
     wam = self.model.get_address_manager()
     return wam.get_change_address(cs).get_address()
示例#48
0
class TestAssetDefinition(unittest.TestCase):

    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [d[0]])
        self.colorset1 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset2 = ColorSet(self.colormap, [d[3]])
        self.def0 = {'monikers': ['bitcoin'],
                     'color_set': self.colorset0.get_data(),
                     'unit':100000000}
        self.def1 = {'monikers': ['test1'],
                     'color_set': self.colorset1.get_data(),
                     'unit':10}
        self.def2 = {'monikers': ['test2','test2alt'],
                     'color_set': self.colorset2.get_data(),
                     'unit':1}
        self.asset0 = AssetDefinition(self.colormap, self.def0)
        self.asset1 = AssetDefinition(self.colormap, self.def1)
        self.asset2 = AssetDefinition(self.colormap, self.def2)

        config = {'asset_definitions': [self.def1, self.def2]}
        self.adm = AssetDefinitionManager(self.colormap, config)

    def test_repr(self):
        self.assertEquals(self.asset0.__repr__(), "['bitcoin']: ['']")
        self.assertEquals(
            self.asset1.__repr__(),
            "['test1']: ['obc:color_desc_1:0:0', 'obc:color_desc_2:0:1']")
        self.assertEquals(self.asset2.__repr__(),
                          "['test2', 'test2alt']: ['obc:color_desc_3:0:1']")

    def test_get_monikers(self):
        self.assertEquals(self.asset0.get_monikers(), ['bitcoin'])
        self.assertEquals(self.asset1.get_monikers(), ['test1'])
        self.assertEquals(self.asset2.get_monikers(), ['test2', 'test2alt'])

    def test_get_color_set(self):
        self.assertTrue(self.asset0.get_color_set().equals(self.colorset0))
        self.assertTrue(self.asset1.get_color_set().equals(self.colorset1))
        self.assertTrue(self.asset2.get_color_set().equals(self.colorset2))

    def test_get_colorvalue(self):
        utxo = MockUTXO(5,[[1,2],[2,3],[3,4]])

        self.assertEquals(self.asset0.get_colorvalue(utxo), 5)
        self.assertEquals(self.asset1.get_colorvalue(utxo), 2)
        self.assertEquals(self.asset2.get_colorvalue(utxo), 4)

        utxo = MockUTXO(5,[[5,2],[6,3],[3,4]])
        self.assertRaises(Exception, self.asset1.get_colorvalue, utxo)

    def test_parse_value(self):
        self.assertEquals(self.asset0.parse_value(1.25), 125000000)
        self.assertEquals(self.asset1.parse_value(2), 20)
        self.assertEquals(self.asset2.parse_value(5), 5)

    def test_format_value(self):
        self.assertEquals(self.asset0.format_value(10000),'0.0001')
        self.assertEquals(self.asset1.format_value(2),'0.2')
        self.assertEquals(self.asset2.format_value(5),'5')

    def test_get_data(self):
        self.assertEquals(self.asset0.get_data(), self.def0)
        self.assertEquals(self.asset1.get_data(), self.def1)
        self.assertEquals(self.asset2.get_data(), self.def2)

    def test_register_asset_definition(self):
        self.assertRaises(Exception, self.adm.register_asset_definition,
                          self.asset1)

    def test_add_asset_definition(self):
        colorset3 = ColorSet(self.colormap, [self.colormap.d[4]])
        def4 = {'monikers': ['test3'], 'color_set': colorset3.get_data()}
        self.adm.add_asset_definition(def4)
        self.assertTrue(self.adm.get_asset_by_moniker('test3').get_color_set()
                        .equals(colorset3))

    def test_all_assets(self):
        reprs = [asset.__repr__() for asset in self.adm.get_all_assets()]
        self.assertTrue(self.asset0.__repr__() in reprs)
        self.assertTrue(self.asset1.__repr__() in reprs)
        self.assertTrue(self.asset2.__repr__() in reprs)

    def test_get_asset_and_address(self):
        ch = self.asset1.get_color_set().get_color_hash()
        addr = '1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj'
        coloraddress = "%s@%s" % (ch, addr)
        asset, address = self.adm.get_asset_and_address(coloraddress)
        self.assertEquals(asset.__repr__(), self.asset1.__repr__())
        self.assertEquals(addr, address)
        asset, address = self.adm.get_asset_and_address(addr)
        self.assertEquals(asset.__repr__(), self.asset0.__repr__())
        self.assertEquals(addr, address)
        self.assertRaises(Exception, self.adm.get_asset_and_address, '0@0')
示例#49
0
 def get_change_addr(self, color_def):
     color_id = color_def.color_id
     cs = ColorSet.from_color_ids(self.model.get_color_map(), [color_id])
     wam = self.model.get_address_manager()
     return wam.get_change_address(cs).get_address()
示例#50
0
class TestColorSet(unittest.TestCase):
    def setUp(self):
        self.colormap = MockColorMap()
        d = self.colormap.d
        self.colorset0 = ColorSet(self.colormap, [""])
        self.colorset1 = ColorSet(self.colormap, [d[1]])
        self.colorset2 = ColorSet(self.colormap, [d[2]])
        self.colorset3 = ColorSet(self.colormap, [d[1], d[2]])
        self.colorset4 = ColorSet(self.colormap, [d[3], d[2]])
        self.colorset5 = ColorSet(self.colormap, [d[3], d[1]])
        self.colorset6 = ColorSet(self.colormap, [])

    def test_repr(self):
        self.assertEquals(self.colorset0.__repr__(), "['']")
        self.assertEquals(self.colorset1.__repr__(), "['obc:color_desc_1:0:0']")
        self.assertEquals(self.colorset3.__repr__(), "['obc:color_desc_1:0:0', 'obc:color_desc_2:0:1']")

    def test_uncolored_only(self):
        self.assertTrue(self.colorset0.uncolored_only())
        self.assertFalse(self.colorset1.uncolored_only())
        self.assertFalse(self.colorset3.uncolored_only())

    def test_get_data(self):
        self.assertEquals(self.colorset0.get_data(), [""])
        self.assertEquals(self.colorset1.get_data(), ["obc:color_desc_1:0:0"])

    def test_get_hash_string(self):
        self.assertEquals(
            self.colorset0.get_hash_string(), "055539df4a0b804c58caf46c0cd2941af10d64c1395ddd8e50b5f55d945841e6"
        )
        self.assertEquals(
            self.colorset1.get_hash_string(), "ca90284eaa79e05d5971947382214044fe64f1bdc2e97040cfa9f90da3964a14"
        )
        self.assertEquals(
            self.colorset3.get_hash_string(), "09f731f25cf5bfaad512d4ee6f37cb9481f442df3263b15725dd1624b4678557"
        )

    def test_get_earliest(self):
        self.assertEquals(self.colorset5.get_earliest(), "obc:color_desc_1:0:0")
        self.assertEquals(self.colorset4.get_earliest(), "obc:color_desc_2:0:1")
        self.assertEquals(self.colorset6.get_earliest(), "\x00\x00\x00\x00")

    def test_get_color_string(self):
        self.assertEquals(self.colorset1.get_color_hash(), "CP4YWLr8aAe4Hn")
        self.assertEquals(self.colorset3.get_color_hash(), "ZUTSoEEwZY6PB")

    def test_has_color_id(self):
        self.assertTrue(self.colorset0.has_color_id(0))
        self.assertTrue(self.colorset3.has_color_id(1))
        self.assertFalse(self.colorset1.has_color_id(0))
        self.assertFalse(self.colorset4.has_color_id(1))

    def test_intersects(self):
        self.assertFalse(self.colorset0.intersects(self.colorset1))
        self.assertTrue(self.colorset1.intersects(self.colorset3))
        self.assertTrue(self.colorset3.intersects(self.colorset1))
        self.assertTrue(self.colorset4.intersects(self.colorset3))
        self.assertFalse(self.colorset2.intersects(self.colorset0))
        self.assertFalse(self.colorset1.intersects(self.colorset4))

    def test_equals(self):
        self.assertFalse(self.colorset1.equals(self.colorset0))
        self.assertTrue(self.colorset3.equals(self.colorset3))
        self.assertFalse(self.colorset4.equals(self.colorset5))

    def test_from_color_ids(self):
        self.assertTrue(self.colorset0.equals(ColorSet.from_color_ids(self.colormap, [0])))
        self.assertTrue(self.colorset3.equals(ColorSet.from_color_ids(self.colormap, [1, 2])))
        tmp = ColorSet.from_color_ids(self.colormap, [1, 2, 3])
        self.assertTrue(tmp.has_color_id(1))
        self.assertTrue(tmp.has_color_id(2))
        self.assertTrue(tmp.has_color_id(3))
示例#51
0
    def setUp(self):
        self.path = ":memory:"
        self.pwallet = PersistentWallet(self.path)
        self.config = {
            'dw_master_key': 'test',
            'testnet': True,
            'ccc': {
                'colordb_path': self.path
            },
            'bip0032': False
        }
        self.pwallet.wallet_config = self.config
        self.pwallet.init_model()
        self.model = self.pwallet.get_model()
        self.colormap = self.model.get_color_map()

        self.colordesc0 = "obc:color0:0:0"
        self.colordesc1 = "obc:color1:0:0"
        self.colordesc2 = "obc:color2:0:0"

        # add some colordescs
        self.colorid0 = self.colormap.resolve_color_desc(self.colordesc0)
        self.colorid1 = self.colormap.resolve_color_desc(self.colordesc1)
        self.colorid2 = self.colormap.resolve_color_desc(self.colordesc2)

        self.colordef0 = OBColorDefinition(self.colorid0, {
            'txhash': 'color0',
            'outindex': 0
        })
        self.colordef1 = OBColorDefinition(self.colorid1, {
            'txhash': 'color1',
            'outindex': 0
        })
        self.colordef2 = OBColorDefinition(self.colorid2, {
            'txhash': 'color2',
            'outindex': 0
        })

        self.asset_config = {
            'monikers': ['blue'],
            'color_set': [self.colordesc0],
        }
        self.basset_config = {
            'monikers': ['bitcoin'],
            'color_set': [''],
        }
        self.asset = AssetDefinition(self.colormap, self.asset_config)
        self.basset = AssetDefinition(self.colormap, self.basset_config)
        self.basic = BasicTxSpec(self.model)
        self.bbasic = BasicTxSpec(self.model)

        wam = self.model.get_address_manager()
        self.address0 = wam.get_new_address(self.asset.get_color_set())
        self.addr0 = self.address0.get_address()

        self.bcolorset = ColorSet(self.colormap, [''])
        self.baddress = wam.get_new_address(self.bcolorset)
        self.baddr = self.baddress.get_address()

        self.assetvalue0 = AdditiveAssetValue(asset=self.asset, value=5)
        self.assetvalue1 = AdditiveAssetValue(asset=self.asset, value=6)
        self.assetvalue2 = AdditiveAssetValue(asset=self.asset, value=7)
        self.bassetvalue = AdditiveAssetValue(asset=self.basset, value=8)
        self.assettarget0 = AssetTarget(self.addr0, self.assetvalue0)
        self.assettarget1 = AssetTarget(self.addr0, self.assetvalue1)
        self.assettarget2 = AssetTarget(self.addr0, self.assetvalue2)
        self.bassettarget = AssetTarget(self.baddr, self.bassetvalue)

        self.atargets = [
            self.assettarget0, self.assettarget1, self.assettarget2
        ]

        # add some targets
        self.colorvalue0 = SimpleColorValue(colordef=self.colordef0, value=5)
        self.colortarget0 = ColorTarget(self.addr0, self.colorvalue0)
        self.colorvalue1 = SimpleColorValue(colordef=self.colordef0, value=6)
        self.colortarget1 = ColorTarget(self.addr0, self.colorvalue1)
        self.colorvalue2 = SimpleColorValue(colordef=self.colordef0, value=7)
        self.colortarget2 = ColorTarget(self.addr0, self.colorvalue2)
        self.bcolorvalue = SimpleColorValue(colordef=UNCOLORED_MARKER, value=8)
        self.bcolortarget = ColorTarget(self.baddr, self.bcolorvalue)

        self.targets = [
            self.colortarget0, self.colortarget1, self.colortarget2
        ]
        self.transformer = TransactionSpecTransformer(self.model, self.config)
        self.blockhash = '00000000c927c5d0ee1ca362f912f83c462f644e695337ce3731b9f7c5d1ca8c'
        self.txhash = '4fe45a5ba31bab1e244114c4555d9070044c73c98636231c77657022d76b87f7'
示例#52
0
 def setUp(self):
     self.colormap = MockColorMap()
     d = self.colormap.d
     self.colorset0 = ColorSet(self.colormap, [d[0]])
     self.colorset1 = ColorSet(self.colormap, [d[1]])
     self.colorset2 = ColorSet(self.colormap, [d[2]])
     self.colorset3 = ColorSet(self.colormap, [d[1], d[2]])
     self.colorset4 = ColorSet(self.colormap, [d[3], d[2]])
     self.colorset5 = ColorSet(self.colormap, [d[3], d[1]])
     self.colorset6 = ColorSet(self.colormap, [])
示例#53
0
class AssetDefinition(object):
    """Stores the definition of a particular asset, including its color set,
    it's name (moniker), and the wallet model that represents it.
    """
    def __init__(self, colormap, params):
        """Create an Asset for a color map <colormap> and configuration
        <params>. Note params has the color definitions used for this
        Asset.
        """
        self.colormap = colormap
        self.monikers = params.get('monikers', [])
        self.color_set = ColorSet(colormap, params.get('color_set'))
        self.unit = int(params.get('unit', 1))

    def __repr__(self):
        return "%s: %s" % (self.monikers, self.color_set)

    def get_monikers(self):
        """Returns the list of monikers for this asset.
        """
        return self.monikers

    def has_color_id(self, color_id):
        return self.get_color_set().has_color_id(color_id)

    def get_color_set(self):
        """Returns the list of colors for this asset.
        """
        return self.color_set

    def get_null_colorvalue(self):
        color_set = self.get_color_set() 
        assert len(color_set.color_desc_list) == 1
        cd = self.colormap.get_color_def(color_set.color_desc_list[0])
        return SimpleColorValue(colordef=cd, value=0)

    def get_colorvalue(self, utxo):
        """ return colorvalue for a given utxo"""
        if utxo.colorvalues:
            for cv in utxo.colorvalues:
                if self.has_color_id(cv.get_color_id()):
                    return cv
        raise Exception("cannot get colorvalue for UTXO: "
                        "no colorvalues available")

    def parse_value(self, portion):
        """Returns actual number of Satoshis for this Asset
        given the <portion> of the asset.
        """
        return int(float(portion) * self.unit)

    def format_value(self, value):
        """Returns a string representation of the portion of the asset.
        can involve rounding.  doesn't display insignificant zeros
        """
        if isinstance(value, ColorValue):
            atoms = value.get_value()
        else:
            atoms = value
        return '{0:g}'.format(atoms / float(self.unit))

    def get_data(self):
        """Returns a JSON-compatible object that represents this Asset
        """
        return {
            "monikers": self.monikers,
            "color_set": self.color_set.get_data(),
            "unit": self.unit
            }
示例#54
0
 def resolve_color_spec(self, color_spec):
     colormap = self.model.get_color_map()
     color_id = colormap.resolve_color_desc(color_spec, False)
     if color_id is None:
         raise InvalidColorIdError("color spec not recognized")
     return ColorSet.from_color_ids(self.model.get_color_map(), [color_id])
示例#55
0
文件: asset.py 项目: F483/ngcccbase
 def get_asset_by_color_id(self, colorid):
     colorset = ColorSet.from_color_ids(self.colormap, [colorid])
     asset = self.find_asset_by_color_set(colorset)
     if not asset:
         raise Exception('Asset not found!')
     return asset
示例#56
0
文件: asset.py 项目: F483/ngcccbase
class AssetDefinition(object):
    """Stores the definition of a particular asset, including its color set,
    it's name (moniker), and the wallet model that represents it.
    """
    def __init__(self, colormap, params):
        """Create an Asset for a color map <colormap> and configuration
        <params>. Note params has the color definitions used for this
        Asset.
        """
        self.colormap = colormap
        self.monikers = params.get('monikers', [])
        # currently only single-color assets are supported
        assert len(params.get('color_set')) == 1
        self.color_set = ColorSet(colormap, params.get('color_set'))
        self.unit = int(params.get('unit', 1))

    def __repr__(self):
        return "%s: %s" % (self.monikers, self.color_set)

    def get_id(self):
        return self.color_set.get_color_hash()

    def get_all_ids(self):
        return [self.get_id()]

    def get_monikers(self):
        """Returns the list of monikers for this asset.
        """
        return self.monikers

    def get_color_id(self):
        return list(self.get_color_set().color_id_set)[0]

    def has_color_id(self, color_id):
        return self.get_color_set().has_color_id(color_id)

    def get_color_set(self):
        """Returns the list of colors for this asset.
        """
        return self.color_set

    def get_color_def(self):
        color_set = self.get_color_set()
        assert len(color_set.color_desc_list) == 1
        return self.colormap.get_color_def(color_set.color_desc_list[0])

    def get_null_colorvalue(self):
        cd = self.get_color_def()
        return SimpleColorValue(colordef=cd, value=0)

    def get_colorvalue(self, utxo):
        """ return colorvalue for a given utxo"""
        if utxo.colorvalues:
            for cv in utxo.colorvalues:
                if self.has_color_id(cv.get_color_id()):
                    return cv
        raise Exception("Cannot get colorvalue for UTXO!")

    def validate_value(self, portion):
        """Returns True if the portion is an exact multiple of the Asset atoms.
        """
        if isinstance(portion, ColorValue) or isinstance(portion, AssetValue):
            portion = portion.get_value()
        atom = Decimal("1") / Decimal(self.unit)
        return Decimal(portion) % atom == Decimal("0")

    def parse_value(self, portion):
        """Returns actual number of Satoshis for this Asset
        given the <portion> of the asset.
        """
        return int(Decimal(portion) * Decimal(self.unit))

    def format_value(self, value):
        """Returns a string representation of the portion of the asset.
        can involve rounding.  doesn't display insignificant zeros
        """
        if isinstance(value, ColorValue) or isinstance(value, AssetValue):
            value = value.get_value()
        return str(Decimal(value) / Decimal(self.unit))

    def get_atom(self):
        return self.format_value(1)

    def get_data(self):
        """Returns a JSON-compatible object that represents this Asset
        """
        return {
            "monikers": self.monikers,
            "assetid" : self.get_color_set().get_color_hash(),
            "color_set": self.color_set.get_data(),
            "unit": self.unit
            }