Exemplo n.º 1
0
 def test_remove_account(self):
     w = WalletData(default_ontid='hahaha')
     acct1 = AccountData(address="123")
     acct2 = AccountData(address="456")
     w.add_account(acct1)
     w.add_account(acct2)
     print(len(w.accounts))
     w.remove_account("123")
     print(len(w.accounts))
Exemplo n.º 2
0
 def test_get_account_by_address(self):
     w = WalletData(default_ontid='hahaha')
     acct1 = AccountData(address="123")
     acct2 = AccountData(address="456")
     w.add_account(acct1)
     w.add_account(acct2)
     print(len(w.accounts))
     r = w.get_account_by_address("123")
     print(r[0])
     print(r[1])
 def test_add_account(self):
     test_id = "test_ont_id"
     w = WalletData(default_id=test_id)
     acct = AccountData()
     w.add_account(acct)
     acct = w.accounts[0]
     self.assertTrue(isinstance(acct, AccountData))
Exemplo n.º 4
0
    def __create_account(self, label: str, pwd: str, salt: bytes,
                         priv_key: bytes, account_flag: bool):
        account = Account(priv_key, self.scheme)
        # initialization
        if self.scheme == SignatureScheme.SHA256withECDSA:
            acct = AccountData()
        else:
            raise ValueError("scheme type is error")
        # set key
        if pwd != None:
            acct.key = account.export_gcm_encrypted_private_key(
                pwd, salt,
                Scrypt().get_n())
            pwd = None
        else:
            acct.key = account.serialize_private_key().hex()

        acct.address = account.get_address_base58()
        # set label
        if label == None or label == "":
            label = str(uuid.uuid4())[0:8]
        if account_flag:
            for index in range(len(self.wallet_in_mem.accounts)):
                if acct.address == self.wallet_in_mem.accounts[index].address:
                    raise ValueError("wallet account exists")

            if len(self.wallet_in_mem.accounts) == 0:
                acct.isDefault = True
                self.wallet_in_mem.defaultAccountAddress = acct.address
            acct.label = label
            acct.salt = base64.b64encode(salt).decode()
            acct.publicKey = account.serialize_public_key().hex()
            self.wallet_in_mem.accounts.append(acct)
        else:
            for index in range(len(self.wallet_in_mem.identities)):
                if self.wallet_in_mem.identities[
                        index].ontid == did_ont + acct.address:
                    raise ValueError("wallet identity exists")
            idt = Identity()
            idt.ontid = did_ont + acct.address
            idt.label = label
            if len(self.wallet_in_mem.identities) == 0:
                idt.isDefault = True
                self.wallet_in_mem.defaultOntid = idt.ontid
            ctl = Control(id="keys-1",
                          key=acct.key,
                          salt=base64.b64encode(salt).decode(),
                          address=acct.address,
                          public_key=account.serialize_public_key().hex())
            idt.controls.append(ctl)
            self.wallet_in_mem.identities.append(idt)
        return account
Exemplo n.º 5
0
 def __init__(self, name: str = 'MyWallet', version: str = '1.1', create_time: str = '', default_id: str = '',
              default_address='', scrypt: Scrypt = Scrypt(), identities: List[Identity] = None,
              accounts: List[AccountData] = None):
     if not isinstance(scrypt, Scrypt):
         raise SDKException(ErrorCode.other_error('Wallet Data init failed'))
     if identities is None:
         identities = list()
     if accounts is None:
         accounts = list()
     self.name = name
     self.version = version
     self.create_time = create_time
     self.default_ont_id = default_id
     self.default_account_address = default_address
     self.scrypt = scrypt
     self.identities = list()
     self.accounts = list()
     for dict_identity in identities:
         if isinstance(dict_identity, dict):
             list_controls = list()
             is_default = dict_identity.get('isDefault', False)
             for ctrl_data in dict_identity['controls']:
                 hash_value = ctrl_data.get('hash', 'sha256')
                 public_key = ctrl_data.get('publicKey', '')
                 try:
                     ctrl = Control(kid=ctrl_data['id'], address=ctrl_data['address'], enc_alg=ctrl_data['enc-alg'],
                                    key=ctrl_data['key'], algorithm=ctrl_data['algorithm'], salt=ctrl_data['salt'],
                                    param=ctrl_data['parameters'], hash_value=hash_value, public_key=public_key)
                 except KeyError:
                     raise SDKException(ErrorCode.other_error('invalid parameters.'))
                 list_controls.append(ctrl)
             try:
                 identity = Identity(ont_id=dict_identity['ontid'], label=dict_identity['label'],
                                     lock=dict_identity['lock'], controls=list_controls, is_default=is_default)
             except KeyError:
                 raise SDKException(ErrorCode.other_error('invalid parameters.'))
             self.identities.append(identity)
         else:
             self.identities = identities
             break
     for dict_account in accounts:
         if isinstance(dict_account, dict):
             try:
                 public_key = dict_account['publicKey']
             except KeyError:
                 public_key = ''
             try:
                 acct = AccountData(b58_address=dict_account['address'], enc_alg=dict_account['enc-alg'],
                                    key=dict_account['key'], algorithm=dict_account['algorithm'],
                                    salt=dict_account['salt'], param=dict_account['parameters'],
                                    label=dict_account['label'], public_key=public_key,
                                    sig_scheme=dict_account['signatureScheme'],
                                    is_default=dict_account['isDefault'], lock=dict_account['lock'])
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.accounts.append(acct)
         else:
             self.accounts = accounts
             break
 def test_add_account(self):
     test_id = "test_ont_id"
     wallet = WalletData(default_id=test_id)
     b58_address = 'AKck7c1ySGr63UinVcMcyuoZD4nXbMk7Sw'
     acct = AccountData(b58_address)
     wallet.add_account(acct)
     acct = wallet.accounts[0]
     self.assertTrue(isinstance(acct, AccountData))
Exemplo n.º 7
0
 def __init__(self, name: str = "MyWallet", version: str = "1.1", create_time: str = "", default_id: str = "",
              default_address="", scrypt: Scrypt = None, identities: list = None, accounts: list = None):
     if scrypt is None:
         scrypt = Scrypt()
     if identities is None:
         identities = list()
     if accounts is None:
         accounts = list()
     self.name = name
     self.version = version
     self.create_time = create_time
     self.default_ont_id = default_id
     self.default_account_address = default_address
     self.scrypt = scrypt
     self.identities = list()
     self.accounts = list()
     for index in range(len(identities)):
         dict_identity = identities[index]
         if isinstance(dict_identity, dict):
             list_controls = list()
             try:
                 try:
                     is_default = dict_identity['isDefault']
                 except Exception as e:
                     is_default = False
                 for control_data in dict_identity['controls']:
                     list_controls.append(Control.dict2obj(control_data))
                 identity = Identity(ont_id=dict_identity['ontid'], label=dict_identity['label'],
                                     lock=dict_identity['lock'], controls=list_controls,
                                     is_default=is_default)
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.identities.append(identity)
         else:
             self.identities = identities
             break
     for index in range(len(accounts)):
         dict_account = accounts[index]
         if isinstance(dict_account, dict):
             try:
                 public_key = dict_account['publicKey']
             except KeyError:
                 public_key = ''
             try:
                 acct = AccountData(address=dict_account['address'], enc_alg=dict_account['enc-alg'],
                                    key=dict_account['key'], algorithm=dict_account['algorithm'],
                                    salt=dict_account['salt'], param=dict_account['parameters'],
                                    label=dict_account['label'], public_key=public_key,
                                    sign_scheme=dict_account['signatureScheme'],
                                    is_default=dict_account['isDefault'], lock=dict_account['lock'])
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.accounts.append(acct)
         else:
             self.accounts = accounts
             break
 def create_wallet_data(self, default_id, size):
     wallet = WalletData(default_id=default_id)
     address_list = list()
     for i in range(size):
         address = randint(0, 1000000000)
         acct = AccountData(b58_address=address)
         wallet.add_account(acct)
         address_list.append(address)
         self.assertEqual(len(wallet.accounts), i + 1)
     return wallet, address_list
Exemplo n.º 9
0
    def __create_account(self, label: str, pwd: str, salt: str,
                         private_key: str, account_flag: bool) -> Account:
        account = Account(private_key, self.scheme)
        if self.scheme == SignatureScheme.SHA256withECDSA:
            acct_data = AccountData()
        else:
            raise SDKException(ErrorCode.other_error('Scheme type is error.'))
        if pwd is not None:
            acct_data.key = account.export_gcm_encrypted_private_key(pwd, salt)
        else:
            acct_data.key = account.get_private_key_hex()

        acct_data.b58_address = account.get_address_base58()
        if len(label) == 0 or label is None:
            label = uuid.uuid4().hex[0:8]
        if account_flag:
            for memory_acct in self.wallet_in_mem.accounts:
                if memory_acct.b58_address == account.get_address_base58():
                    raise SDKException(
                        ErrorCode.other_error('Wallet account exists.'))
            if len(self.wallet_in_mem.accounts) == 0:
                acct_data.is_default = True
                self.wallet_in_mem.default_account_address = acct_data.b58_address
            acct_data.label = label
            acct_data.salt = base64.b64encode(
                salt.encode('latin-1')).decode('ascii')
            acct_data.public_key = account.get_public_key_hex()
            self.wallet_in_mem.accounts.append(acct_data)
        else:
            for identity in self.wallet_in_mem.identities:
                if identity.ont_id == DID_ONT + acct_data.b58_address:
                    raise SDKException(
                        ErrorCode.other_error('Wallet identity exists.'))
            idt = Identity()
            idt.ont_id = DID_ONT + acct_data.b58_address
            idt.label = label
            if len(self.wallet_in_mem.identities) == 0:
                idt.is_default = True
                self.wallet_in_mem.default_ont_id = idt.ont_id
            ctl = Control(kid='keys-1',
                          key=acct_data.key,
                          salt=base64.b64encode(salt.encode()).decode('ascii'),
                          address=acct_data.b58_address,
                          public_key=account.get_public_key_hex())
            idt.controls.append(ctl)
            self.wallet_in_mem.identities.append(idt)
        return account
    def load(self):
        with open(self.wallet_path, "r") as f:
            fstr = f.read()
            r = json.loads(fstr.replace("enc-", "enc_"), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
            # r = json.load(f, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
            scrypt = Scrypt(r.scrypt.n, r.scrypt.r, r.scrypt.p, r.scrypt.dkLen)
            identities = []
            try:
                for index in range(len(r.identities)):
                    r_identities = r.identities[index]
                    control = [Control(id=r_identities.controls[0].id,
                                       algorithm=r_identities.controls[0].algorithm,
                                       param=r_identities.controls[0].parameters,
                                       key=r_identities.controls[0].key,
                                       address=r_identities.controls[0].address,
                                       salt=r_identities.controls[0].salt,
                                       enc_alg=r_identities.controls[0].enc_alg,
                                       hash_value=r_identities.controls[0].hash,
                                       public_key=r_identities.controls[0].publicKey)]
                    identities.append(Identity(r_identities.ont_id, r_identities.label, r_identities.lock, control))
            except AttributeError as e:
                pass

            accounts = []
            try:
                for index in range(len(r.accounts)):
                    temp = AccountData(label=r.accounts[index].label, public_key=r.accounts[index].publicKey,
                                       sign_scheme=r.accounts[index].signatureScheme,
                                       isDefault=r.accounts[index].isDefault,
                                       lock=r.accounts[index].lock, address=r.accounts[index].address,
                                       algorithm=r.accounts[index].algorithm, param=r.accounts[index].parameters,
                                       key=r.accounts[index].key, enc_alg=r.accounts[index].enc_alg,
                                       salt=r.accounts[index].salt)
                    accounts.append(temp)
            except AttributeError as e:
                pass
            default_ont_id = ""
            try:
                default_ont_id = r.defaultOntid
            except AttributeError as e:
                pass
            default_account_address = ""
            try:
                default_account_address = r.defaultAccountAddress
            except AttributeError as e:
                pass
            create_time = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
            try:
                create_time = r.createTime
            except Exception as e:
                pass
            res = WalletData(r.name, r.version, create_time, default_ont_id, default_account_address, scrypt,
                             identities, accounts)
            return res
    def test_get_account_by_address(self):
        test_id = "test_ont_id"
        wallet = WalletData(default_id=test_id)
        size = 10
        address_list = list()
        for i in range(size):
            address = randint(0, 1000000000)
            acct = AccountData(b58_address=address)
            wallet.add_account(acct)
            address_list.append(address)
            self.assertEqual(len(wallet.accounts), i + 1)

        for i in range(size * 2):
            rand_address = choice(address_list)
            acct = wallet.get_account_by_b58_address(rand_address)
            self.assertEqual(rand_address, acct.b58_address)
 def test_remove_account(self):
     test_id = "test_ont_id"
     wallet = WalletData(default_id=test_id)
     size = 10
     address_list = list()
     for i in range(size):
         address = randint(0, 1000000000)
         acct = AccountData(b58_address=address)
         wallet.add_account(acct)
         address_list.append(address)
         self.assertEqual(len(wallet.accounts), i + 1)
     for i in range(size):
         rand_address = choice(address_list)
         wallet.remove_account(rand_address)
         address_list.remove(rand_address)
         self.assertEqual(len(wallet.accounts), size - i - 1)
    def test_get_account_by_index(self):
        test_id = "test_ont_id"
        w = WalletData(default_id=test_id)
        size = 10
        address_list = list()
        for i in range(size):
            address = random.randint(0, 1000000000)
            acct = AccountData(address=address)
            w.add_account(acct)
            address_list.append(address)
            self.assertEqual(len(w.accounts), i + 1)

        for i in range(size * 2):
            index = random.choice(range(size))
            acct = w.get_account_by_index(index)
            self.assertEqual(address_list[index], acct.address)
Exemplo n.º 14
0
    def load(self):
        with open(self.wallet_path, "r") as f:
            r = json.load(f,
                          object_hook=lambda d: namedtuple('X', d.keys())
                          (*d.values()))
            scrypt = Scrypt(r.scrypt.n, r.scrypt.r, r.scrypt.p,
                            r.scrypt.dk_len)

            identities = []
            for index in range(len(r.identities)):
                r_identities = r.identities()[index]
                control = [
                    Control(id=r_identities.controls[0].id,
                            algorithm=r_identities.controls[0].algorithm,
                            param=r_identities.controls[0].parameters,
                            key=r_identities.controls[0].key,
                            address=r_identities.controls[0].address,
                            salt=r_identities.controls[0].salt,
                            enc_alg=r_identities.controls[0].enc_alg,
                            hash_value=r_identities.controls[0].hash,
                            public_key=r_identities.controls[0].publicKey)
                ]
                identities.append(
                    Identity(r_identities.ont_id, r_identities.label,
                             r_identities.lock, control))

            accounts = []
            for index in range(len(r.accounts)):
                temp = AccountData(
                    label=r.accounts[index].label,
                    public_key=r.accounts[index].publicKey,
                    sign_scheme=r.accounts[index].signatureScheme,
                    is_default=r.accounts[index].is_default,
                    lock=r.accounts[index].lock,
                    address=r.accounts[index].address,
                    algorithm=r.accounts[index].algorithm,
                    param=r.accounts[index].parameters,
                    key=r.accounts[index].key,
                    enc_alg=r.accounts[index].enc_alg,
                    salt=r.accounts[index].salt,
                    hash_value=r.accounts[index].hash)
                accounts.append(temp)

            res = WalletData(r.name, r.version, r.create_time,
                             r.default_ont_id, r.default_account_address,
                             scrypt, identities, accounts)
            return res
Exemplo n.º 15
0
 def add_account(self, b58_address='AatF7ATuecga82vk8wBqjZizCPUce4rpZ5'):
     acct = AccountData(b58_address)
     self.wallet.add_account(acct)
Exemplo n.º 16
0
 def test_field(self):
     data = AccountData()
     print(data.algorithm)
Exemplo n.º 17
0
 def test_account_data_constructor(self):
     data = AccountData()
     self.assertEqual(data.algorithm, 'ECDSA')
Exemplo n.º 18
0
 def test_add_account(self):
     w = WalletData(default_ontid='hahaha')
     acct = AccountData()
     w.add_account(acct)
     print(w.accounts[0])