1
1
'use strict' ;
2
2
3
3
const Service = require ( 'egg' ) . Service ;
4
-
4
+ const secp256k1 = require ( 'secp256k1/elliptic' ) ;
5
+ const createKeccakHash = require ( 'keccak' ) ;
6
+ const crypto = require ( 'crypto' ) ;
5
7
class UserService extends Service {
6
8
7
9
async create ( user ) {
@@ -18,10 +20,8 @@ class UserService extends Service {
18
20
}
19
21
20
22
const exist_user = await ctx . model . User . find ( { where : { mobile } } ) ;
21
- console . log ( exist_user ) ;
22
23
if ( exist_user ) return exist_user ;
23
24
24
-
25
25
return ctx . model . User . create ( { mobile } ) ;
26
26
}
27
27
@@ -90,6 +90,43 @@ class UserService extends Service {
90
90
return this . getByAddress ( address ) ;
91
91
}
92
92
93
+ // 创建钱包
94
+ async createWallet ( user_id ) {
95
+ const ctx = this . ctx ;
96
+
97
+ const user = await ctx . model . User . find ( { where : { id : user_id } } ) ;
98
+ if ( ! user ) {
99
+ ctx . throw ( 400 , `用户(id: ${ user_id } )不存在` , { code : 'USER_NOT_FOUND' , errors : { user_id } } ) ;
100
+ }
101
+ if ( user . address ) {
102
+ ctx . throw ( 400 , `用户(id: ${ user_id } )已有钱包,无法创建新的` , { code : 'USER_ALREADY_HAS_WALLET' , errors : { user_id, address : user . address } } ) ;
103
+ }
104
+
105
+ let private_key = crypto . randomBytes ( 32 ) ;
106
+ const publicKey = secp256k1 . publicKeyCreate ( private_key , false ) . slice ( 1 ) ;
107
+ let address = createKeccakHash ( 'keccak256' ) . update ( publicKey ) . digest ( )
108
+ . slice ( - 20 ) ;
109
+ private_key = private_key . toString ( 'hex' ) . toLowerCase ( ) ;
110
+ address = '0x' + address . toString ( 'hex' ) . toLowerCase ( ) ;
111
+
112
+ await ctx . model . User . update ( {
113
+ address,
114
+ private_key
115
+ } , {
116
+ where : {
117
+ id : user_id ,
118
+ address : null , // 如果同一个用户高并发打过来,可能会被更新多次, 所以不要用user.updates({address,private_key})
119
+ private_key : null ,
120
+ } ,
121
+ returning : true ,
122
+ } ) ;
123
+
124
+ return {
125
+ address,
126
+ private_key
127
+ } ;
128
+ }
129
+
93
130
}
94
131
95
132
module . exports = UserService ;
0 commit comments