Browse Source

change pid to 0x eth address

pull/40/head
Neo Sun 3 years ago
parent
commit
c2b1cf74bc
  1. 6
      Cargo.toml
  2. 10
      lib/apps/chat/add.dart
  3. 12
      lib/apps/dao/tmp/add.dart
  4. 2
      lib/apps/dao/tmp/detail.dart
  5. 4
      lib/apps/device/page.dart
  6. 4
      lib/apps/domain/page.dart
  7. 4
      lib/apps/wallet/page.dart
  8. 2
      lib/pages/home.dart
  9. 4
      lib/pages/setting/network.dart
  10. 2
      lib/pages/setting/profile.dart
  11. 50
      lib/utils/better_print.dart
  12. 8
      lib/widgets/chat_message.dart
  13. 10
      lib/widgets/user_info.dart
  14. 18
      src/account.rs
  15. 2
      src/apps/domain/models.rs
  16. 2
      src/apps/group/models/group.rs
  17. 33
      src/apps/wallet/rpc.rs
  18. 2
      types/cloud/Cargo.toml
  19. 4
      types/dao/Cargo.toml
  20. 4
      types/data/Cargo.toml
  21. 2
      types/domain/Cargo.toml
  22. 2
      types/group/Cargo.toml
  23. 2
      types/primitives/Cargo.toml
  24. 17
      types/primitives/src/lib.rs

6
Cargo.toml

@ -48,9 +48,9 @@ rand_chacha = "0.3"
sha2 = "0.10" sha2 = "0.10"
sysinfo = "0.26" sysinfo = "0.26"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn = { version = "0.8", default-features = false, features = ["std"] } tdn = { version = "0.10", default-features = false, features = ["std"] }
tdn_did = { version = "0.8" } tdn_did = { version = "0.10" }
tdn_storage = { version = "0.8" } tdn_storage = { version = "0.10" }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
tracing = "0.1" tracing = "0.1"
tracing-appender = "0.2" tracing-appender = "0.2"

10
lib/apps/chat/add.dart

@ -45,7 +45,7 @@ class _ChatAddState extends State<ChatAdd> {
setState(() { setState(() {
this._showHome = false; this._showHome = false;
final avatar = Avatar(name: params[1], width: 100.0, colorSurface: false); final avatar = Avatar(name: params[1], width: 100.0, colorSurface: false);
String id = pidParse(params[0].trim()); String id = params[0].trim();
this._coreScreen = _InfoScreen( this._coreScreen = _InfoScreen(
callback: this._sendCallback, callback: this._sendCallback,
@ -312,7 +312,7 @@ class _ChatAddState extends State<ChatAdd> {
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
const Divider(height: 1.0, color: Color(0x40ADB0BB)), const Divider(height: 1.0, color: Color(0x40ADB0BB)),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
_infoListTooltip(Icons.person, color.primary, pidText(request.pid), pidPrint(request.pid)), _infoListTooltip(Icons.person, color.primary, request.pid, pidPrint(request.pid)),
_infoList(Icons.turned_in, color.primary, request.remark), _infoList(Icons.turned_in, color.primary, request.remark),
_infoList(Icons.access_time_rounded, color.primary, request.time.toString()), _infoList(Icons.access_time_rounded, color.primary, request.time.toString()),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
@ -666,7 +666,7 @@ class _InputScreenState extends State<_InputScreen> {
FocusNode remarkFocus = FocusNode(); FocusNode remarkFocus = FocusNode();
send() { send() {
final id = pidParse(userIdEditingController.text.trim()); final id = userIdEditingController.text.trim();
if (id == '') { if (id == '') {
return; return;
} }
@ -694,7 +694,7 @@ class _InputScreenState extends State<_InputScreen> {
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
InputText( InputText(
icon: Icons.person, icon: Icons.person,
text: lang.id + ' (EH00..00)', text: lang.id + ' (0x00..00)',
controller: userIdEditingController, controller: userIdEditingController,
focus: userIdFocus), focus: userIdFocus),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
@ -752,7 +752,7 @@ class _InfoScreen extends StatelessWidget {
title: Text(pidPrint(this.id), style: TextStyle(fontSize: 16.0)), title: Text(pidPrint(this.id), style: TextStyle(fontSize: 16.0)),
trailing: TextButton( trailing: TextButton(
child: Icon(Icons.copy, size: 20.0), child: Icon(Icons.copy, size: 20.0),
onPressed: () => Clipboard.setData(ClipboardData(text: pidText(this.id))), onPressed: () => Clipboard.setData(ClipboardData(text: this.id)),
) )
), ),
ListTile( ListTile(

12
lib/apps/dao/tmp/add.dart

@ -182,7 +182,7 @@ class _GroupAddPageState extends State<GroupAddPage> {
print(params); print(params);
if (isOk && app == 'add-group' && params.length == 3) { if (isOk && app == 'add-group' && params.length == 3) {
this._joinIdController.text = gidText(params[0]); this._joinIdController.text = gidText(params[0]);
this._joinAddrController.text = addrText(params[1]); this._joinAddrController.text = params[1];
this._joinNameController.text = params[2]; this._joinNameController.text = params[2];
setState(() {}); setState(() {});
} }
@ -193,7 +193,7 @@ class _GroupAddPageState extends State<GroupAddPage> {
if (id.length < 2) { if (id.length < 2) {
return; return;
} }
final addr = addrParse(_joinAddrController.text.trim()); final addr = _joinAddrController.text.trim();
final name = _joinNameController.text.trim(); final name = _joinNameController.text.trim();
context.read<GroupChatProvider>().join(GroupType.Open, id, addr, name, ""); context.read<GroupChatProvider>().join(GroupType.Open, id, addr, name, "");
setState(() { setState(() {
@ -231,7 +231,7 @@ class _GroupAddPageState extends State<GroupAddPage> {
_addrChecked = false; _addrChecked = false;
_joinIdController.text = gidText(widget.id, 'EG'); _joinIdController.text = gidText(widget.id, 'EG');
_joinAddrController.text = addrText(widget.addr); _joinAddrController.text = widget.addr;
_joinNameController.text = widget.name; _joinNameController.text = widget.name;
_joinIdFocus.addListener(() { _joinIdFocus.addListener(() {
@ -485,7 +485,7 @@ class _GroupAddPageState extends State<GroupAddPage> {
), ),
trailing: IconButton(icon: Icon(Icons.send, color: color.primary), trailing: IconButton(icon: Icon(Icons.send, color: color.primary),
onPressed: () { onPressed: () {
final addr = addrParse(_createAddrController.text.trim()); final addr = _createAddrController.text.trim();
if (addr.length > 0) { if (addr.length > 0) {
rpc.send('group-chat-provider-check', [0, addr]); rpc.send('group-chat-provider-check', [0, addr]);
} }
@ -692,7 +692,7 @@ class _RequestItem extends StatelessWidget {
request.isMe ? gidText(request.gid, 'EG') : gidText(request.gid), request.isMe ? gidText(request.gid, 'EG') : gidText(request.gid),
request.isMe ? gidPrint(request.gid, 'EG') : gidPrint(request.gid), request.isMe ? gidPrint(request.gid, 'EG') : gidPrint(request.gid),
), ),
_infoListTooltip(Icons.location_on, color.primary, addrText(request.addr), addrPrint(request.addr)), _infoListTooltip(Icons.location_on, color.primary, request.addr, pidPrint(request.addr)),
_infoList(Icons.turned_in, color.primary, request.remark), _infoList(Icons.turned_in, color.primary, request.remark),
_infoList(Icons.access_time_rounded, color.primary, request.time.toString()), _infoList(Icons.access_time_rounded, color.primary, request.time.toString()),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
@ -824,7 +824,7 @@ class _RequestItem extends StatelessWidget {
Text(request.name, maxLines: 1, overflow: TextOverflow.ellipsis, Text(request.name, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 16.0)), style: TextStyle(fontSize: 16.0)),
Text( Text(
gidPrint(request.gid, 'EG') + " (${addrPrint(request.addr)})", gidPrint(request.gid, 'EG') + " (${pidPrint(request.addr)})",
maxLines: 1, overflow: TextOverflow.ellipsis, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(color: Color(0xFFADB0BB), style: TextStyle(color: Color(0xFFADB0BB),
fontSize: 12.0)), fontSize: 12.0)),

2
lib/apps/dao/tmp/detail.dart

@ -732,7 +732,7 @@ class _MemberDetailState extends State<MemberDetail> {
const Divider(height: 1.0, color: Color(0x40ADB0BB)), const Divider(height: 1.0, color: Color(0x40ADB0BB)),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
_infoListTooltip(Icons.person, color.primary, gidText(widget.member.mid), gidPrint(widget.member.mid)), _infoListTooltip(Icons.person, color.primary, gidText(widget.member.mid), gidPrint(widget.member.mid)),
_infoListTooltip(Icons.location_on, color.primary, addrText(widget.member.addr), addrPrint(widget.member.addr)), _infoListTooltip(Icons.location_on, color.primary, widget.member.addr, pidPrint(widget.member.addr)),
if (widget.isGroupOwner) if (widget.isGroupOwner)
Container( Container(
padding: const EdgeInsets.only(top: 20.0, bottom: 10.0), padding: const EdgeInsets.only(top: 20.0, bottom: 10.0),

4
lib/apps/device/page.dart

@ -36,7 +36,7 @@ class _DevicesPageState extends State<DevicesPage> {
const SizedBox(height: 32.0), const SizedBox(height: 32.0),
ButtonText( ButtonText(
action: () { action: () {
final addr = addrParse(this._addrController.text.trim()); final addr = this._addrController.text.trim();
if (addr.length > 0) { if (addr.length > 0) {
Provider.of<DeviceProvider>(context, listen: false).connect(addr); Provider.of<DeviceProvider>(context, listen: false).connect(addr);
Navigator.pop(context); Navigator.pop(context);
@ -52,7 +52,7 @@ class _DevicesPageState extends State<DevicesPage> {
final res = await httpPost('account-mnemonic', [lock]); final res = await httpPost('account-mnemonic', [lock]);
if (res.isOk) { if (res.isOk) {
final words = res.params[0]; final words = res.params[0];
final info = json.encode({'app': 'distribute', 'params': [name, pidText(id), words]}); final info = json.encode({'app': 'distribute', 'params': [name, id, words]});
showShadowDialog(context, Icons.qr_code_rounded, lang.deviceQrcode, showShadowDialog(context, Icons.qr_code_rounded, lang.deviceQrcode,
Column( Column(
children: [ children: [

4
lib/apps/domain/page.dart

@ -303,7 +303,7 @@ class _ListProviderScreen extends StatelessWidget {
title: Text(provider.name, style: TextStyle(fontWeight: FontWeight.bold)), title: Text(provider.name, style: TextStyle(fontWeight: FontWeight.bold)),
subtitle: Row( subtitle: Row(
children: <Widget>[ children: <Widget>[
Expanded(child: Text(addrPrint(provider.addr), style: TextStyle(fontSize: 14.0))), Expanded(child: Text(pidPrint(provider.addr), style: TextStyle(fontSize: 14.0))),
], ],
), ),
trailing: Container( trailing: Container(
@ -505,7 +505,7 @@ class _AddProviderScreenState extends State<_AddProviderScreen> {
ButtonText( ButtonText(
enable: !this._waiting, enable: !this._waiting,
action: () { action: () {
final addr = addrParse(_addrController.text.trim()); final addr = _addrController.text.trim();
if (addr.length < 2) { if (addr.length < 2) {
return; return;
} }

4
lib/apps/wallet/page.dart

@ -1025,7 +1025,7 @@ class _TransferTokenState extends State<_TransferToken> {
items: this._nft.map((value) { items: this._nft.map((value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(pidPrint(value, '', 6)), child: Text(pidPrint(value, 6)),
); );
}).toList(), }).toList(),
), ),
@ -1248,7 +1248,7 @@ class _ImportNftState extends State<_ImportNft> {
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
final hash = this._nft[index]; final hash = this._nft[index];
return ListTile( return ListTile(
title: Text('TokenID: ' + pidPrint(hash, '', 6)), title: Text('TokenID: ' + pidPrint(hash, 6)),
trailing: IconButton(icon: Icon(Icons.link, color: color.primary), trailing: IconButton(icon: Icon(Icons.link, color: color.primary),
onPressed: () { onPressed: () {
launch(widget.token.nftUrl(hash)); launch(widget.token.nftUrl(hash));

2
lib/pages/home.dart

@ -99,7 +99,7 @@ class _HomeListState extends State<HomeList> {
builder: (context) => QRScan(callback: (isOk, app, params) { builder: (context) => QRScan(callback: (isOk, app, params) {
Navigator.of(context).pop(); Navigator.of(context).pop();
if (app == 'add-friend' && params.length == 2) { if (app == 'add-friend' && params.length == 2) {
final id = pidParse(params[0]); final id = params[0];
final name = params[1].trim(); final name = params[1].trim();
final widget = ChatAdd(id: id, name: name); final widget = ChatAdd(id: id, name: name);
Provider.of<AccountProvider>(context, listen: false).systemAppFriendAddNew = false; Provider.of<AccountProvider>(context, listen: false).systemAppFriendAddNew = false;

4
lib/pages/setting/network.dart

@ -199,7 +199,7 @@ class _NetworkDetailState extends State<NetworkDetail> {
size: 18.0, size: 18.0,
color: color.primary), color: color.primary),
SizedBox(width: 15.0), SizedBox(width: 15.0),
Text(addrPrint(item[0]), Text(pidPrint(item[0]),
style: TextStyle(fontSize: 14.0)) style: TextStyle(fontSize: 14.0))
])); ]));
}), }),
@ -225,7 +225,7 @@ class _NetworkDetailState extends State<NetworkDetail> {
Icon(Icons.cloud_done_outlined, Icon(Icons.cloud_done_outlined,
size: 18.0, color: color.primary), size: 18.0, color: color.primary),
SizedBox(width: 15.0), SizedBox(width: 15.0),
Text(addrPrint(item), Text(pidPrint(item),
style: TextStyle(fontSize: 14.0)), style: TextStyle(fontSize: 14.0)),
])); ]));
}), }),

2
lib/pages/setting/profile.dart

@ -167,7 +167,7 @@ class _ProfileDetailState extends State<ProfileDetail> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
children: [ children: [
_infoListTooltip(Icons.person, color.primary, pidText(account.pid), pidPrint(account.pid)), _infoListTooltip(Icons.person, color.primary, account.pid, pidPrint(account.pid)),
SizedBox( SizedBox(
height: 40.0, height: 40.0,
child: Row( child: Row(

50
lib/utils/better_print.dart

@ -1,57 +1,13 @@
String pidText(String? pid, [String pre='EH']) { String pidPrint(String? pid, [int n = 6]) {
if (pid == null) { if (pid == null) {
return ''; return '';
} }
return pre + pid.toUpperCase();
}
String pidPrint(String? pid, [String pre='EH', int n = 6]) { final info = pid;
if (pid == null) {
return '';
}
final info = pid.toUpperCase();
final len = info.length; final len = info.length;
if (len > n+n) { if (len > n+n) {
return pre + info.substring(0, n) + '...' + info.substring(len - n, len); return info.substring(0, n) + '...' + info.substring(len - n, len);
} else {
return info;
}
}
String pidParse(String pid, [String pre='EH']) {
if (pid.length > 2 && pid.substring(0, 2) == pre) {
return pid.substring(2);
} else {
return pid;
}
}
String addrText(String? addr) {
if (addr == null) {
return '';
}
return '0x' + addr.toLowerCase();
}
String addrPrint(String? addr) {
if (addr == null) {
return '';
}
final info = addr.toLowerCase();
final len = info.length;
if (len > 12) {
return '0x' + info.substring(0, 6) + '...' + info.substring(len - 6, len);
} else { } else {
return info; return info;
} }
} }
String addrParse(String addr) {
if (addr.length > 2 && addr.substring(0, 2) == '0x') {
return addr.substring(2);
} else {
return addr;
}
}

8
lib/widgets/chat_message.dart

@ -28,7 +28,7 @@ class ChatMessage extends StatelessWidget {
const ChatMessage({Key? key, required this.fpid, required this.name, required this.message, this.avatar}): super(key: key); const ChatMessage({Key? key, required this.fpid, required this.name, required this.message, this.avatar}): super(key: key);
Widget _showContactCard(Widget avatar, String pid, String name, String title, ColorScheme color, [String pre='EH']) { Widget _showContactCard(Widget avatar, String pid, String name, String title, ColorScheme color) {
return Container( return Container(
padding: const EdgeInsets.only(top: 10, bottom: 6.0, left: 10.0, right: 10.0), padding: const EdgeInsets.only(top: 10, bottom: 6.0, left: 10.0, right: 10.0),
width: 200.0, width: 200.0,
@ -41,7 +41,7 @@ class ChatMessage extends StatelessWidget {
child: Column(children: [ child: Column(children: [
Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: color.onPrimary, fontSize: 16.0)), Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: color.onPrimary, fontSize: 16.0)),
const SizedBox(height: 4.0), const SizedBox(height: 4.0),
Text(pidPrint(pid, pre), style: TextStyle(color: Colors.grey, fontSize: 12.0)), Text(pidPrint(pid), style: TextStyle(color: Colors.grey, fontSize: 12.0)),
]))]), ]))]),
const SizedBox(height: 5.0), const SizedBox(height: 5.0),
const Divider(height: 1.0, color: Color(0x40ADB0BB)), const Divider(height: 1.0, color: Color(0x40ADB0BB)),
@ -260,7 +260,7 @@ class ChatMessage extends StatelessWidget {
context, context,
Icons.groups_rounded, Icons.groups_rounded,
lang.groupChat, lang.groupChat,
UserInfo(showQr: false, id: infos[1], name: infos[3], pre: 'EG', UserInfo(showQr: false, id: infos[1], name: infos[3],
title: gtype.lang(lang), title: gtype.lang(lang),
avatar: Container(width: 100.0, height: 100.0, avatar: Container(width: 100.0, height: 100.0,
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
@ -281,7 +281,7 @@ class ChatMessage extends StatelessWidget {
decoration: BoxDecoration(color: color.surface, borderRadius: BorderRadius.circular(10.0)), decoration: BoxDecoration(color: color.surface, borderRadius: BorderRadius.circular(10.0)),
child: Icon(Icons.groups_rounded, color: color.primary, size: 20.0), child: Icon(Icons.groups_rounded, color: color.primary, size: 20.0),
), ),
infos[1], infos[3], lang.groupChat, color, 'EG') infos[1], infos[3], lang.groupChat, color)
); );
} else { } else {
return _showText(context, color, maxWidth); return _showText(context, color, maxWidth);

10
lib/widgets/user_info.dart

@ -18,7 +18,6 @@ class UserInfo extends StatefulWidget {
final bool showQr; final bool showQr;
final Widget? avatar; final Widget? avatar;
Map? qrInfo; Map? qrInfo;
final String pre;
UserInfo({Key? key, UserInfo({Key? key,
required this.id, required this.id,
@ -30,12 +29,11 @@ class UserInfo extends StatefulWidget {
this.avatar, this.avatar,
this.title, this.title,
this.showQr = true, this.showQr = true,
this.pre = 'EH',
}) : super(key: key) { }) : super(key: key) {
if (this.showQr) { if (this.showQr) {
this.qrInfo = { this.qrInfo = {
"app": this.app, "app": this.app,
"params": [pidText(this.id, this.pre), this.name], "params": [this.id, this.name],
}; };
} }
} }
@ -54,7 +52,7 @@ class _UserInfoState extends State<UserInfo> {
Color idColor = idCopy ? color.primary : color.onPrimary; Color idColor = idCopy ? color.primary : color.onPrimary;
print(pidText(widget.id)); print(widget.id);
return Column( return Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@ -108,7 +106,7 @@ class _UserInfoState extends State<UserInfo> {
Text(widget.title!, style: TextStyle(fontSize: 16.0, fontStyle: FontStyle.italic)), Text(widget.title!, style: TextStyle(fontSize: 16.0, fontStyle: FontStyle.italic)),
InkWell( InkWell(
onTap: () { onTap: () {
Clipboard.setData(ClipboardData(text: pidText(widget.id))); Clipboard.setData(ClipboardData(text: widget.id));
setState(() { setState(() {
idCopy = true; idCopy = true;
}); });
@ -118,7 +116,7 @@ class _UserInfoState extends State<UserInfo> {
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text(pidText(widget.id, widget.pre), child: Text(widget.id,
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle(fontSize: 14, color: idColor))), style: TextStyle(fontSize: 14, color: idColor))),
Padding( Padding(

18
src/account.rs

@ -8,9 +8,8 @@ use tdn::types::{
group::EventId, group::EventId,
primitives::{PeerId, PeerKey, Result}, primitives::{PeerId, PeerKey, Result},
}; };
use tdn_did::{generate_eth_account, generate_peer, Language}; use tdn_did::{generate_eth_account, Language};
use tdn_storage::local::{DStorage, DsValue}; use tdn_storage::local::{DStorage, DsValue};
use web3::signing::Key;
use esse_primitives::{id_from_str, id_to_str}; use esse_primitives::{id_from_str, id_to_str};
@ -133,18 +132,11 @@ impl Account {
avatar: Vec<u8>, avatar: Vec<u8>,
) -> Result<(Account, PeerKey, Address)> { ) -> Result<(Account, PeerKey, Address)> {
let lang = lang_from_i64(rlang); let lang = lang_from_i64(rlang);
let sk = generate_peer(
lang,
mnemonic,
index,
0, // account default multiple address index is 0.
if pass.len() > 0 { Some(pass) } else { None },
)?;
// Default ETH wallet account. // Default ETH wallet account.
let wallet_pass = if pass.len() > 0 { Some(pass) } else { None }; let wallet_pass = if pass.len() > 0 { Some(pass) } else { None };
let wallet_sk = generate_eth_account(lang, mnemonic, index, 0, wallet_pass)?; let wallet_sk = generate_eth_account(lang, mnemonic, index, 0, wallet_pass)?;
let wallet_address = format!("{:?}", (&wallet_sk).address()); let wallet_address = format!("{:?}", (&wallet_sk).peer_id());
let wallet = ChainToken::ETH.update_main(&wallet_address, ""); let wallet = ChainToken::ETH.update_main(&wallet_address, "");
let w = Address::new(ChainToken::ETH, 0, wallet_address, true); let w = Address::new(ChainToken::ETH, 0, wallet_address, true);
@ -156,7 +148,7 @@ impl Account {
salt, salt,
lock, lock,
&ckey, &ckey,
vec![&sk.to_db_bytes(), mnemonic.as_bytes()], vec![&wallet_sk.to_db_bytes(), mnemonic.as_bytes()],
)?; )?;
let mnemonic = ebytes.pop().unwrap_or(vec![]); let mnemonic = ebytes.pop().unwrap_or(vec![]);
let secret = ebytes.pop().unwrap_or(vec![]); let secret = ebytes.pop().unwrap_or(vec![]);
@ -164,7 +156,7 @@ impl Account {
Ok(( Ok((
Account::new( Account::new(
sk.peer_id(), wallet_sk.peer_id(),
index, index,
rlang, rlang,
pass.to_string(), pass.to_string(),
@ -179,7 +171,7 @@ impl Account {
PeerId::default(), PeerId::default(),
[0u8; 32], [0u8; 32],
), ),
sk, wallet_sk,
w, w,
)) ))
} }

2
src/apps/domain/models.rs

@ -53,7 +53,7 @@ impl Provider {
is_proxy: v.pop().unwrap().as_bool(), is_proxy: v.pop().unwrap().as_bool(),
is_default: v.pop().unwrap().as_bool(), is_default: v.pop().unwrap().as_bool(),
is_ok: v.pop().unwrap().as_bool(), is_ok: v.pop().unwrap().as_bool(),
addr: PeerId::from_hex(v.pop().unwrap().as_string()).unwrap_or(Default::default()), addr: PeerId::from_hex(v.pop().unwrap().as_str()).unwrap_or(Default::default()),
name: v.pop().unwrap().as_string(), name: v.pop().unwrap().as_string(),
id: v.pop().unwrap().as_i64(), id: v.pop().unwrap().as_i64(),
} }

2
src/apps/group/models/group.rs

@ -93,7 +93,7 @@ impl GroupChat {
local: v.pop().unwrap().as_bool(), local: v.pop().unwrap().as_bool(),
close: v.pop().unwrap().as_bool(), close: v.pop().unwrap().as_bool(),
name: v.pop().unwrap().as_string(), name: v.pop().unwrap().as_string(),
addr: PeerId::from_hex(v.pop().unwrap().as_string()).unwrap_or(Default::default()), addr: PeerId::from_hex(v.pop().unwrap().as_str()).unwrap_or(Default::default()),
gid: v.pop().unwrap().as_i64() as GroupChatId, gid: v.pop().unwrap().as_i64() as GroupChatId,
height: v.pop().unwrap().as_i64(), height: v.pop().unwrap().as_i64(),
id: v.pop().unwrap().as_i64(), id: v.pop().unwrap().as_i64(),

33
src/apps/wallet/rpc.rs

@ -1,15 +1,14 @@
use std::sync::Arc; use std::sync::Arc;
use tdn::types::{ use tdn::types::{
message::RpcSendMessage, message::RpcSendMessage,
primitives::{HandleResult, Result}, primitives::{HandleResult, PeerKey, PeerSecretKey, Result},
rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam}, rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam},
}; };
use tdn_did::{generate_btc_account, generate_eth_account, secp256k1::SecretKey}; use tdn_did::{generate_btc_account, generate_eth_account};
use tdn_storage::local::DStorage; use tdn_storage::local::DStorage;
use tokio::sync::mpsc::Sender; use tokio::sync::mpsc::Sender;
use web3::{ use web3::{
contract::{tokens::Tokenize, Contract}, contract::{tokens::Tokenize, Contract},
signing::Key,
transports::http::Http, transports::http::Http,
types::{Address as EthAddress, Bytes, CallRequest, TransactionParameters, U256}, types::{Address as EthAddress, Bytes, CallRequest, TransactionParameters, U256},
Web3, Web3,
@ -185,7 +184,7 @@ async fn token_transfer(
to_str: &str, to_str: &str,
amount_str: &str, amount_str: &str,
c_str: &str, c_str: &str,
secret: &SecretKey, key: &PeerKey,
network: &Network, network: &Network,
chain: &ChainToken, chain: &ChainToken,
) -> Result<String> { ) -> Result<String> {
@ -232,7 +231,10 @@ async fn token_transfer(
_ => return Err(anyhow!("not supported")), _ => return Err(anyhow!("not supported")),
}; };
let signed = web3.accounts().sign_transaction(tx, secret).await?; let signed = web3
.accounts()
.sign_transaction(tx, key.sec_key.raw())
.await?;
let result = web3 let result = web3
.eth() .eth()
.send_raw_transaction(signed.raw_transaction) .send_raw_transaction(signed.raw_transaction)
@ -357,8 +359,8 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<Global>) {
let index = Address::next_index(&db, &chain)?; let index = Address::next_index(&db, &chain)?;
let mut address = match chain { let mut address = match chain {
ChainToken::ETH | ChainToken::ERC20 | ChainToken::ERC721 => { ChainToken::ETH | ChainToken::ERC20 | ChainToken::ERC721 => {
let sk = generate_eth_account(lang, &mnemonic, account_index, index, pass)?; let key = generate_eth_account(lang, &mnemonic, account_index, index, pass)?;
let address = format!("{:?}", (&sk).address()); let address = key.peer_id().to_hex();
Address::new(chain, index as i64, address, index == 0) Address::new(chain, index as i64, address, index == 0)
} }
ChainToken::BTC => { ChainToken::BTC => {
@ -393,15 +395,16 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<Global>) {
let secret = params[1].as_str().ok_or(RpcError::ParseError)?; let secret = params[1].as_str().ok_or(RpcError::ParseError)?;
let lock = params[2].as_str().ok_or(RpcError::ParseError)?; let lock = params[2].as_str().ok_or(RpcError::ParseError)?;
let sk: SecretKey = secret.parse().or(Err(RpcError::ParseError))?; let sk: PeerSecretKey = secret.try_into().or(Err(RpcError::ParseError))?;
let addr = format!("{:?}", (&sk).address()); let key = PeerKey::from_sec_key(sk);
let addr = key.peer_id().to_hex();
let pid = state.pid().await; let pid = state.pid().await;
let own_lock = state.own.read().await; let own_lock = state.own.read().await;
let ckey = &own_lock.account(&pid)?.encrypt; let ckey = &own_lock.account(&pid)?.encrypt;
let db_key = own_lock.db_key(&pid)?; let db_key = own_lock.db_key(&pid)?;
let cbytes = encrypt(&state.secret, lock, ckey, sk.as_ref())?; let cbytes = encrypt(&state.secret, lock, ckey, &key.to_db_bytes())?;
drop(own_lock); drop(own_lock);
let db = wallet_db(&state.base, &pid, &db_key)?; let db = wallet_db(&state.base, &pid, &db_key)?;
@ -506,7 +509,7 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<Global>) {
None None
}; };
let sk: SecretKey = if address.is_gen() { let key: PeerKey = if address.is_gen() {
match chain { match chain {
ChainToken::ETH | ChainToken::ERC20 | ChainToken::ERC721 => { ChainToken::ETH | ChainToken::ERC20 | ChainToken::ERC721 => {
generate_eth_account( generate_eth_account(
@ -522,15 +525,15 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<Global>) {
} }
} }
} else { } else {
let sk = SecretKey::from_slice(&pbytes) let key = PeerKey::from_db_bytes(&pbytes)
.or(Err(RpcError::Custom("Secret is invalid!".to_owned())))?; .or(Err(RpcError::Custom("Secret is invalid!".to_owned())))?;
if format!("{:?}", (&sk).address()) != address.address { if key.peer_id().to_hex().to_lowercase() != address.address.to_lowercase() {
return Err(RpcError::Custom("Secret is invalid!".to_owned())); return Err(RpcError::Custom("Secret is invalid!".to_owned()));
} }
sk key
}; };
let hash = token_transfer(&address.address, to, amount, c_str, &sk, &network, &chain) let hash = token_transfer(&address.address, to, amount, c_str, &key, &network, &chain)
.await .await
.map_err(|e| RpcError::Custom(format!("{:?}", e)))?; .map_err(|e| RpcError::Custom(format!("{:?}", e)))?;

2
types/cloud/Cargo.toml

@ -11,4 +11,4 @@ license = "MIT/Apache-2.0"
[dependencies] [dependencies]
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn_types = { version = "0.8", default-features = false } tdn_types = { version = "0.10", default-features = false }

4
types/dao/Cargo.toml

@ -12,5 +12,5 @@ license = "MIT/Apache-2.0"
[dependencies] [dependencies]
esse_primitives = { version = "0.1", path = "../primitives" } esse_primitives = { version = "0.1", path = "../primitives" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn_types = { version = "0.8", default-features = false } tdn_types = { version = "0.10", default-features = false }
tdn_did = { version = "0.8", default-features = false } tdn_did = { version = "0.10", default-features = false }

4
types/data/Cargo.toml

@ -14,5 +14,5 @@ default = ["tdn"]
tdn = ["tdn_did", "tdn_types"] tdn = ["tdn_did", "tdn_types"]
[dependencies] [dependencies]
tdn_did = { version = "0.8", default-features = false, optional = true } tdn_did = { version = "0.10", default-features = false, optional = true }
tdn_types = { version = "0.8", default-features = false, optional = true } tdn_types = { version = "0.10", default-features = false, optional = true }

2
types/domain/Cargo.toml

@ -11,4 +11,4 @@ license = "MIT/Apache-2.0"
[dependencies] [dependencies]
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn_types = { version = "0.8", default-features = false } tdn_types = { version = "0.10", default-features = false }

2
types/group/Cargo.toml

@ -12,4 +12,4 @@ license = "MIT/Apache-2.0"
[dependencies] [dependencies]
esse_primitives = { version = "0.1", path = "../primitives" } esse_primitives = { version = "0.1", path = "../primitives" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn_types = { version = "0.8", default-features = false } tdn_types = { version = "0.10", default-features = false }

2
types/primitives/Cargo.toml

@ -11,4 +11,4 @@ license = "MIT/Apache-2.0"
[dependencies] [dependencies]
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tdn_types = { version = "0.8", default-features = false } tdn_types = { version = "0.10", default-features = false }

17
types/primitives/src/lib.rs

@ -1,8 +1,5 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tdn_types::{ use tdn_types::{group::GroupId, primitives::PeerId};
group::GroupId,
primitives::{new_io_error, PeerId, PEER_ID_LENGTH},
};
/// ESSE chat service default TDN GROUP ID. /// ESSE chat service default TDN GROUP ID.
pub const ESSE_ID: GroupId = 0; pub const ESSE_ID: GroupId = 0;
@ -70,18 +67,14 @@ impl MessageType {
} }
} }
#[inline]
pub fn id_to_str(peer: &PeerId) -> String { pub fn id_to_str(peer: &PeerId) -> String {
bs32::encode(&peer.0) peer.to_hex()
} }
#[inline]
pub fn id_from_str(s: &str) -> std::io::Result<PeerId> { pub fn id_from_str(s: &str) -> std::io::Result<PeerId> {
let data = bs32::decode(s).ok_or(new_io_error("id from string is failure."))?; PeerId::from_hex(s)
if data.len() != PEER_ID_LENGTH {
return Err(new_io_error("id from string is failure."));
}
let mut bytes = [0u8; PEER_ID_LENGTH];
bytes.copy_from_slice(&data);
Ok(PeerId(bytes))
} }
pub mod bs32 { pub mod bs32 {

Loading…
Cancel
Save