@onekeyfe/react-native-lite-card 6.7.0-23 → 6.7.0-24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,7 @@ import com.facebook.react.module.annotations.ReactModule
16
16
  import com.onekeyfe.reactnativelitecard.nfc.NFCExceptions
17
17
  import com.onekeyfe.reactnativelitecard.nfc.NfcUtils
18
18
  import com.onekeyfe.reactnativelitecard.onekeyLite.OneKeyLiteCard
19
+ import com.onekeyfe.reactnativelitecard.onekeyLite.PendingTag
19
20
  import com.onekeyfe.reactnativelitecard.onekeyLite.entitys.CardState
20
21
  import com.onekeyfe.reactnativelitecard.utils.NfcPermissionUtils
21
22
  import com.onekeyfe.reactnativelitecard.utils.Utils
@@ -66,12 +67,11 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
66
67
  }
67
68
  }
68
69
 
69
- private val mNFCConnectedChannel = Channel<IsoDep?>(1)
70
+ private val mNFCConnectedChannel = Channel<PendingTag?>(1)
70
71
  private var lastIsoDep: IsoDep? = null
71
72
  private val diagnosticSequence = AtomicInteger(0)
72
73
  private val mNFCState = AtomicInteger(NFCState.Dead)
73
74
  private val mShowDialogNumber = AtomicInteger(0)
74
- private var mCurrentCardState: CardState? = null
75
75
 
76
76
  private val mActivityEventListener = object : BaseActivityEventListener() {
77
77
  override fun onNewIntent(intent: Intent) {
@@ -97,15 +97,14 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
97
97
  }
98
98
 
99
99
  OneKeyLog.info("LiteCard", "stage=tag_received wallTimeMs=${System.currentTimeMillis()}")
100
+ val pendingTag = PendingTag(isoDep)
101
+ if (mNFCConnectedChannel.trySend(pendingTag).isFailure) return
100
102
  launch(Dispatchers.IO) {
101
- mNFCConnectedChannel.trySend(isoDep)
102
103
  try {
103
104
  // 处理主动触发 NFC
104
105
  delay(100)
105
- if (!mNFCConnectedChannel.isEmpty) {
106
- OneKeyLog.error("LiteCard","There is no way to use NFC")
107
- // mNFCConnectedChannel.receive()
108
- val startRequest = OneKeyLiteCard.initRequest(isoDep)
106
+ val startRequest = OneKeyLiteCard.tryDiscover(pendingTag)
107
+ if (startRequest != null && !pendingTag.isClaimed()) {
109
108
  val dataMap = Arguments.createMap().apply {
110
109
  putInt("code", -1)
111
110
  putString("type", "OneKey_Lite")
@@ -117,6 +116,7 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
117
116
  }
118
117
  } catch (e: Exception) {
119
118
  OneKeyLog.error("LiteCard", "stage=connection_failure type=${if (e is NFCExceptions) "nfc" else "other"}")
119
+ if (pendingTag.isClaimed()) return@launch
120
120
  // 未知设备或连接失败
121
121
  val dataMap = Arguments.createMap().apply {
122
122
  putInt("code", -1)
@@ -137,7 +137,6 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
137
137
  private fun releaseDevice() {
138
138
  if (mShowDialogNumber.get() <= 0) return
139
139
 
140
- mCurrentCardState = null
141
140
  val decrementAndGet = mShowDialogNumber.decrementAndGet()
142
141
 
143
142
  // 关闭连接结束 ui
@@ -174,11 +173,8 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
174
173
  var receiveIsoDep: IsoDep? = null
175
174
 
176
175
  if (tryReceiveResult.isSuccess) {
177
- receiveIsoDep = tryReceiveResult.getOrNull()
176
+ receiveIsoDep = tryReceiveResult.getOrNull()?.claim()
178
177
  OneKeyLog.info("LiteCard", "acquireID=$acquireID stage=acquire_source source=channel connected=${receiveIsoDep.isSafeConnected()}")
179
- if (!receiveIsoDep.isSafeConnected()) {
180
- receiveIsoDep = null
181
- }
182
178
  }
183
179
 
184
180
  if (receiveIsoDep == null && lastIsoDep.isSafeConnected()) {
@@ -187,33 +183,18 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
187
183
  }
188
184
  if (receiveIsoDep == null) {
189
185
  OneKeyLog.info("LiteCard", "acquireID=$acquireID stage=acquire_source source=wait")
190
- receiveIsoDep = mNFCConnectedChannel.receive()
186
+ receiveIsoDep = mNFCConnectedChannel.receive()?.claim()
191
187
  }
192
188
 
193
189
  OneKeyLog.info("LiteCard", "acquireID=$acquireID stage=acquire_result available=${receiveIsoDep != null} connected=${receiveIsoDep.isSafeConnected()}")
194
190
  lastIsoDep = receiveIsoDep
195
- if (receiveIsoDep == null) {
196
- // 取消连接
197
- releaseDevice()
198
- } else {
199
- val initChannelRequest = OneKeyLiteCard.initRequest(receiveIsoDep)
200
-
201
- mCurrentCardState = initChannelRequest
202
- OneKeyLog.info("LiteCard", "acquireID=$acquireID stage=card_state isNewCard=${initChannelRequest.isNewCard} hasBackup=${initChannelRequest.hasBackup}")
203
-
204
- // 展示连接结束 ui
205
- emitOnNFCUIEvent(Arguments.createMap().also {
206
- it.putInt("code", 2)
207
- it.putString("message", "connected")
208
- }.copy())
209
- }
210
191
  return receiveIsoDep
211
192
  }
212
193
 
213
194
  private suspend fun <T> handleOperation(
214
195
  callback: Callback?,
215
196
  operation: String,
216
- execute: (isoDep: IsoDep) -> T
197
+ execute: (session: OneKeyLiteCard.CardSession) -> T
217
198
  ) {
218
199
  val operationID = diagnosticSequence.incrementAndGet()
219
200
  val started = SystemClock.elapsedRealtime()
@@ -223,15 +204,25 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
223
204
  return
224
205
  }
225
206
  NfcPermissionUtils.checkPermission(topActivity) {
207
+ var cardState: CardState? = null
226
208
  try {
227
209
  OneKeyLog.debug("LiteCard","NFC permission check success")
228
210
  val isoDep = acquireDevice() ?: return
229
- val executeResult = execute(isoDep)
211
+ val executeResult = OneKeyLiteCard.withCardSession(isoDep) { session ->
212
+ cardState = session.cardState
213
+ OneKeyLog.info("LiteCard", "operation=$operation operationID=$operationID stage=card_state isNewCard=${session.cardState.isNewCard} hasBackup=${session.cardState.hasBackup}")
214
+ // This queues a React Native event; completion callbacks stay outside ownership.
215
+ emitOnNFCUIEvent(Arguments.createMap().also {
216
+ it.putInt("code", 2)
217
+ it.putString("message", "connected")
218
+ }.copy())
219
+ execute(session)
220
+ }
230
221
  OneKeyLog.info("LiteCard", "operation=$operation operationID=$operationID stage=callback code=0 elapsedMs=${SystemClock.elapsedRealtime() - started}")
231
- callback?.invoke(null, executeResult, mCurrentCardState.createArguments())
222
+ callback?.invoke(null, executeResult, cardState.createArguments())
232
223
  } catch (e: NFCExceptions) {
233
224
  OneKeyLog.info("LiteCard", "operation=$operation operationID=$operationID stage=callback code=${e.code} elapsedMs=${SystemClock.elapsedRealtime() - started}")
234
- callback?.invoke(e.createArguments(), null, mCurrentCardState.createArguments())
225
+ callback?.invoke(e.createArguments(), null, cardState.createArguments())
235
226
  } finally {
236
227
  releaseDevice()
237
228
  }
@@ -264,9 +255,9 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
264
255
  override fun getLiteInfo(callback: Callback?) {
265
256
  launch {
266
257
  OneKeyLog.debug("LiteCard","getLiteInfo")
267
- handleOperation<Any>(callback, "getLiteInfo") { isoDep ->
258
+ handleOperation<Any>(callback, "getLiteInfo") { session ->
268
259
  OneKeyLog.debug("LiteCard","getLiteInfo Obtain the device")
269
- val cardInfo = OneKeyLiteCard.getCardInfo(isoDep)
260
+ val cardInfo = OneKeyLiteCard.getCardInfo(session)
270
261
  OneKeyLog.debug("LiteCard","getLiteInfo result obtained")
271
262
  cardInfo.createArguments()
272
263
  }
@@ -307,6 +298,7 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
307
298
  mnemonic: String?,
308
299
  pwd: String?,
309
300
  overwrite: Boolean,
301
+ expectedSerial: String?,
310
302
  callback: Callback?
311
303
  ) {
312
304
  if (pwd.isNullOrEmpty() || pwd.length != 6 || !pwd.all { it.isDigit() }) {
@@ -318,15 +310,15 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
318
310
  return
319
311
  }
320
312
  launch {
321
- handleOperation(callback, "setMnemonic") { isoDep ->
313
+ handleOperation(callback, "setMnemonic") { session ->
322
314
  OneKeyLog.debug("LiteCard","setMnemonic Obtain the device")
323
315
  val isSuccess =
324
316
  OneKeyLiteCard.setMnemonic(
325
- mCurrentCardState,
326
- isoDep,
317
+ session,
327
318
  mnemonic,
328
319
  pwd,
329
- overwrite
320
+ overwrite,
321
+ expectedSerial
330
322
  )
331
323
  if (!isSuccess) throw NFCExceptions.ExecFailureException()
332
324
  OneKeyLog.debug("LiteCard","setMnemonic result success")
@@ -345,9 +337,9 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
345
337
  }
346
338
  launch {
347
339
  OneKeyLog.debug("LiteCard","getMnemonicWithPin")
348
- handleOperation(callback, "getMnemonicWithPin") { isoDep ->
340
+ handleOperation(callback, "getMnemonicWithPin") { session ->
349
341
  OneKeyLog.debug("LiteCard","getMnemonicWithPin Obtain the device")
350
- OneKeyLiteCard.getMnemonicWithPin(mCurrentCardState, isoDep, pwd)
342
+ OneKeyLiteCard.getMnemonicWithPin(session, pwd)
351
343
  }
352
344
  }
353
345
  }
@@ -359,9 +351,9 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
359
351
  ) {
360
352
  launch {
361
353
  OneKeyLog.debug("LiteCard","changePin")
362
- handleOperation(callback, "changePin") { isoDep ->
354
+ handleOperation(callback, "changePin") { session ->
363
355
  OneKeyLog.debug("LiteCard","changePin Obtain the device")
364
- OneKeyLiteCard.changPin(mCurrentCardState, isoDep, oldPin, newPin)
356
+ OneKeyLiteCard.changPin(session, oldPin, newPin)
365
357
  }
366
358
  }
367
359
  }
@@ -369,9 +361,9 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
369
361
  override fun reset(callback: Callback?) {
370
362
  launch {
371
363
  OneKeyLog.debug("LiteCard","reset")
372
- handleOperation(callback, "reset") { isoDep ->
364
+ handleOperation(callback, "reset") { session ->
373
365
  OneKeyLog.debug("LiteCard","reset Obtain the device")
374
- val isSuccess = OneKeyLiteCard.reset(isoDep)
366
+ val isSuccess = OneKeyLiteCard.reset(session)
375
367
  if (!isSuccess) throw NFCExceptions.ExecFailureException()
376
368
  OneKeyLog.debug("LiteCard","reset result success")
377
369
  true
@@ -8,6 +8,10 @@ import androidx.lifecycle.Lifecycle
8
8
  import com.google.gson.Gson
9
9
  import kotlinx.coroutines.Dispatchers
10
10
  import kotlinx.coroutines.withContext
11
+ import kotlinx.coroutines.sync.Mutex
12
+ import kotlinx.coroutines.sync.withLock
13
+ import org.haobtc.onekey.card.gpchannel.GPChannelNatives.nativeGPCFinalize
14
+ import java.util.concurrent.atomic.AtomicBoolean
11
15
  import com.onekeyfe.reactnativelitecard.nfc.NFCExceptions
12
16
  import com.onekeyfe.reactnativelitecard.nfc.NfcUtils
13
17
  import com.onekeyfe.reactnativelitecard.onekeyLite.entitys.CardState
@@ -17,14 +21,30 @@ import com.onekeyfe.reactnativelitecard.onekeyLite.nfc.CommandGenerator
17
21
  import com.onekeyfe.reactnativelitecard.utils.LogUtil.printLog
18
22
  import com.onekeyfe.reactnativelitecard.utils.NfcPermissionUtils
19
23
 
24
+ internal class PendingTag(val isoDep: IsoDep) {
25
+ private val claimed = AtomicBoolean(false)
26
+
27
+ fun claim(): IsoDep {
28
+ claimed.set(true)
29
+ return isoDep
30
+ }
31
+
32
+ fun isClaimed(): Boolean = claimed.get()
33
+ }
34
+
20
35
  object OneKeyLiteCard {
21
36
  const val TAG = "OneKeyLiteCard"
22
37
 
23
38
  private val mCommandGenerator by lazy {
24
39
  CommandGenerator()
25
40
  }
26
- @Volatile
27
- private var mCardConnection: Connection? = null
41
+ // GPChannel owns one native context, including across React Native runtimes.
42
+ private val operationMutex = Mutex()
43
+
44
+ internal class CardSession internal constructor(
45
+ internal val connection: Connection,
46
+ val cardState: CardState
47
+ )
28
48
 
29
49
  suspend fun startNfc(activity: FragmentActivity, callback: ((Boolean) -> Unit)? = null) =
30
50
  withContext(Dispatchers.Main) {
@@ -61,55 +81,79 @@ object OneKeyLiteCard {
61
81
  NfcUtils.mNfcAdapter?.disableForegroundDispatch(activity)
62
82
  }
63
83
 
64
- // first init channel ,can filter not match device
65
- @Throws(NFCExceptions::class)
66
- suspend fun initRequest(isoDep: IsoDep?) = withContext(Dispatchers.IO) {
67
- if (isoDep == null) {
68
- throw NFCExceptions.ConnectionFailException()
84
+ internal suspend fun <T> withCardSession(
85
+ isoDep: IsoDep,
86
+ execute: (CardSession) -> T
87
+ ): T = withContext(Dispatchers.IO) {
88
+ operationMutex.withLock {
89
+ withInitializedSession(isoDep, execute)
90
+ }
91
+ }
92
+
93
+ internal suspend fun tryDiscover(tag: PendingTag): CardState? = withContext(Dispatchers.IO) {
94
+ if (tag.isClaimed() || !operationMutex.tryLock()) return@withContext null
95
+ try {
96
+ if (tag.isClaimed()) return@withContext null
97
+ withInitializedSession(tag.isoDep) { it.cardState }.takeUnless { tag.isClaimed() }
98
+ } finally {
99
+ operationMutex.unlock()
100
+ }
101
+ }
102
+
103
+ private fun <T> withInitializedSession(isoDep: IsoDep, execute: (CardSession) -> T): T {
104
+ try {
105
+ val connection = Connection(isoDep, mCommandGenerator)
106
+ return execute(CardSession(connection, connection.getCardInfo()))
107
+ } finally {
108
+ // Construction itself reads the card and may fail after touching GPChannel.
109
+ nativeGPCFinalize()
69
110
  }
70
- mCardConnection = Connection(isoDep, mCommandGenerator)
71
- return@withContext mCardConnection?.getCardInfo()
72
- ?: throw NFCExceptions.InitChannelException()
73
111
  }
74
112
 
75
113
  @Throws(NFCExceptions::class)
76
- private fun setupNewPinRequest(isoDep: IsoDep, pin: String?): Boolean {
114
+ private fun setupNewPinRequest(session: CardSession, pin: String?): Boolean {
77
115
  if (pin.isNullOrEmpty()) {
78
116
  throw NFCExceptions.InputPasswordEmptyException()
79
117
  }
80
- return mCardConnection?.setupNewPin(pin) ?: false
118
+ return session.connection.setupNewPin(pin)
81
119
  }
82
120
 
83
121
  @Throws(NFCExceptions::class)
84
- fun changePinRequest(isoDep: IsoDep, oldPwd: String?, newPwd: String?): Int {
122
+ private fun changePinRequest(session: CardSession, oldPwd: String?, newPwd: String?): Int {
85
123
  if (oldPwd.isNullOrEmpty()) {
86
124
  throw NFCExceptions.InputPasswordEmptyException()
87
125
  }
88
- return mCardConnection?.changePin(oldPwd, newPwd) ?: 0
126
+ return session.connection.changePin(oldPwd, newPwd)
89
127
  }
90
128
 
91
129
  @Throws(NFCExceptions::class)
92
- fun verifyPinBackupRequest(isoDep: IsoDep, verifyPin: String?): Int {
130
+ private fun verifyPinBackupRequest(session: CardSession, verifyPin: String?): Int {
93
131
  if (verifyPin.isNullOrEmpty()) {
94
132
  throw NFCExceptions.InputPasswordEmptyException()
95
133
  }
96
- return mCardConnection?.startVerifyPin(verifyPin) ?: 0
134
+ return session.connection.startVerifyPin(verifyPin)
97
135
  }
98
136
 
99
137
  @Throws(NFCExceptions::class)
100
- fun getCardInfo(isoDep: IsoDep): CardState {
101
- return mCardConnection?.getCardInfo() ?: throw NFCExceptions.ConnectionFailException()
138
+ internal fun getCardInfo(session: CardSession): CardState {
139
+ return session.connection.getCardInfo()
102
140
  }
103
141
 
104
142
  @Throws(NFCExceptions::class)
105
- fun setMnemonic(
106
- cardState: CardState?,
107
- isoDep: IsoDep,
143
+ internal fun setMnemonic(
144
+ session: CardSession,
108
145
  mnemonic: String?,
109
146
  pwd: String?,
110
- overwrite: Boolean = false
147
+ overwrite: Boolean = false,
148
+ expectedSerial: String? = null
111
149
  ): Boolean {
112
- if (cardState == null) throw NFCExceptions.ConnectionFailException()
150
+ val cardState = session.cardState
151
+ val serial = cardState.serialNum
152
+ if (expectedSerial != null && (serial.isEmpty() ||
153
+ serial == NfcConstant.NOT_MATCH_DEVICE || expectedSerial != serial)) {
154
+ OneKeyLog.info("LiteCard", "operation=setMnemonic stage=identity_mismatch")
155
+ throw NFCExceptions.DeviceMismatchException()
156
+ }
113
157
 
114
158
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=card_state isNewCard=${cardState.isNewCard} hasBackup=${cardState.hasBackup} overwrite=$overwrite wallTimeMs=${System.currentTimeMillis()}")
115
159
 
@@ -121,10 +165,10 @@ object OneKeyLiteCard {
121
165
  }
122
166
  }
123
167
 
124
- if (overwrite && mCardConnection?.getCardType() == AppleCardType.V2) {
168
+ if (overwrite && session.connection.getCardType() == AppleCardType.V2) {
125
169
  // Verify the password before clearing the card
126
170
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=overwrite_verify_begin")
127
- val verifyPin = verifyPinBackupRequest(isoDep, pwd)
171
+ val verifyPin = verifyPinBackupRequest(session, pwd)
128
172
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=overwrite_verify_result success=${verifyPin == NfcConstant.VERIFY_SUCCESS}")
129
173
  if (verifyPin != NfcConstant.VERIFY_SUCCESS) {
130
174
  handlerVerifyPinError(cardState, verifyPin)
@@ -137,7 +181,7 @@ object OneKeyLiteCard {
137
181
  if (cardState.isNewCard) {
138
182
  // 如果是新卡设置密码
139
183
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=set_pin_begin")
140
- val setupSuccess = setupNewPinRequest(isoDep, pwd)
184
+ val setupSuccess = setupNewPinRequest(session, pwd)
141
185
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=set_pin_result success=$setupSuccess")
142
186
  if (!setupSuccess) {
143
187
  throw NFCExceptions.InitPasswordException()
@@ -145,7 +189,7 @@ object OneKeyLiteCard {
145
189
  }
146
190
 
147
191
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=verify_pin_begin")
148
- val verifyPin = verifyPinBackupRequest(isoDep, pwd)
192
+ val verifyPin = verifyPinBackupRequest(session, pwd)
149
193
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=verify_pin_result success=${verifyPin == NfcConstant.VERIFY_SUCCESS}")
150
194
  if (verifyPin != NfcConstant.VERIFY_SUCCESS) {
151
195
  if (overwrite) {
@@ -157,25 +201,25 @@ object OneKeyLiteCard {
157
201
 
158
202
  if (mnemonic.isNullOrEmpty()) throw NFCExceptions.ExecFailureException()
159
203
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=backup_begin")
160
- val backupSuccess = mCardConnection?.backupData(mnemonic) == true
204
+ val backupSuccess = session.connection.backupData(mnemonic)
161
205
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=backup_result success=$backupSuccess")
162
206
  return backupSuccess
163
207
  }
164
208
 
165
209
  @Throws(NFCExceptions::class)
166
- fun getMnemonicWithPin(cardState: CardState?, isoDep: IsoDep, pwd: String): String {
167
- if (cardState == null) throw NFCExceptions.ConnectionFailException()
210
+ internal fun getMnemonicWithPin(session: CardSession, pwd: String): String {
211
+ val cardState = session.cardState
168
212
 
169
213
  if (cardState.isNewCard || !cardState.hasBackup) {
170
214
  throw NFCExceptions.NotInitializedException()
171
215
  }
172
216
 
173
- val verifyPin = verifyPinBackupRequest(isoDep, pwd)
217
+ val verifyPin = verifyPinBackupRequest(session, pwd)
174
218
  if (verifyPin != NfcConstant.VERIFY_SUCCESS) {
175
219
  handlerVerifyPinError(cardState, verifyPin)
176
220
  }
177
221
 
178
- val result = mCardConnection?.exportData()
222
+ val result = session.connection.exportData()
179
223
 
180
224
  if (result.isNullOrEmpty()) {
181
225
  throw NFCExceptions.NotInitializedException()
@@ -184,14 +228,14 @@ object OneKeyLiteCard {
184
228
  }
185
229
 
186
230
  @Throws(NFCExceptions::class)
187
- fun changPin(cardState: CardState?, isoDep: IsoDep, oldPwd: String, newPwd: String): Boolean {
188
- if (cardState == null) throw NFCExceptions.ConnectionFailException()
231
+ internal fun changPin(session: CardSession, oldPwd: String, newPwd: String): Boolean {
232
+ val cardState = session.cardState
189
233
 
190
234
  if (cardState.isNewCard || !cardState.hasBackup) {
191
235
  throw NFCExceptions.NotInitializedException()
192
236
  }
193
237
 
194
- val result = changePinRequest(isoDep, oldPwd, newPwd)
238
+ val result = changePinRequest(session, oldPwd, newPwd)
195
239
  handlerVerifyPinError(cardState, result, true)
196
240
 
197
241
  return when (result) {
@@ -209,8 +253,8 @@ object OneKeyLiteCard {
209
253
  }
210
254
  }
211
255
 
212
- fun reset(isoDep: IsoDep): Boolean {
213
- return mCardConnection?.resetCard() == NfcConstant.RESET_PIN_SUCCESS
256
+ internal fun reset(session: CardSession): Boolean {
257
+ return session.connection.resetCard() == NfcConstant.RESET_PIN_SUCCESS
214
258
  }
215
259
 
216
260
  private fun handlerVerifyPinError(
@@ -1,5 +1,8 @@
1
1
  package com.onekeyfe.reactnativelitecard.onekeyLite.nfc
2
2
 
3
+ import com.margelo.nitro.nativelogger.OneKeyLog
4
+ import java.util.concurrent.atomic.AtomicLong
5
+ import org.haobtc.onekey.card.gpchannel.GPChannelNatives.nativeGetErrorCode
3
6
  import com.google.gson.JsonObject
4
7
  import com.google.gson.JsonParser
5
8
  import org.haobtc.onekey.card.gpchannel.GPChannelNatives.nativeGPCParseAPDUResponse
@@ -48,6 +51,7 @@ enum class CommandType(val code: String) {
48
51
 
49
52
  class Command(
50
53
  private val cardType: AppleCardType,
54
+ private val type: CommandType,
51
55
  val area: CommandArea,
52
56
  val command: String,
53
57
  private val ignoreSafeChannel: Boolean,
@@ -56,6 +60,10 @@ class Command(
56
60
  private val hasOpenSafeChannel: Boolean,
57
61
  val data: String,
58
62
  ) {
63
+ companion object {
64
+ private val diagnosticSequence = AtomicLong(0)
65
+ }
66
+
59
67
  private fun beforeConnecting(connection: Connection) {
60
68
  val needOpenSafeChannel = useSafeChannel || (useSafeChannelWhenOpen && hasOpenSafeChannel)
61
69
  val needCloseSafeChannel =
@@ -106,16 +114,25 @@ class Command(
106
114
  }
107
115
 
108
116
  fun send(connection: Connection): SendResponse {
117
+ val commandID = diagnosticSequence.incrementAndGet()
118
+ val secure = useSafeChannel || (useSafeChannelWhenOpen && hasOpenSafeChannel)
119
+ OneKeyLog.info("LiteCard", "commandID=$commandID command=${type.code} stage=before_connect secure=$secure")
109
120
  beforeConnecting(connection)
110
121
  // buildApdu && parseResponse Use in pairs
111
122
  val apdu = buildApdu()
123
+ OneKeyLog.info("LiteCard", "commandID=$commandID command=${type.code} stage=build buildSucceeded=${apdu.isNotEmpty()}")
112
124
  if (apdu.isEmpty()) {
113
125
  return SendResponse("0xFFFF", 0xFF.toByte(), 0xFF.toByte(), parseSuccess = false)
114
126
  }
115
127
  val result = Connection.send(connection.isoDep, apdu)
116
- val resultObject = CardResponse.objectFromData(parseResponse(result.rawResponse))
128
+ val rawResponseBytes = if (result.rawResponse == "0xFFFF") -1 else result.rawResponse.length / 2
129
+ OneKeyLog.info("LiteCard", "commandID=$commandID command=${type.code} stage=transport_result rawResponseBytes=$rawResponseBytes rawSW1=${result.sw1.toInt() and 0xFF} rawSW2=${result.sw2.toInt() and 0xFF}")
130
+ val parsedResponse = parseResponse(result.rawResponse)
131
+ val lastSdkError = if (parsedResponse == null) nativeGetErrorCode() else 0
132
+ val resultObject = CardResponse.objectFromData(parsedResponse)
117
133
  result.result = resultObject?.response ?: ""
118
134
  result.parseSuccess = resultObject != null && resultObject.wRet == 0x9000
135
+ OneKeyLog.info("LiteCard", "commandID=$commandID command=${type.code} stage=parse lastSdkError=$lastSdkError parsePresent=${resultObject != null} parsedSW=${resultObject?.wRet ?: -1} parseSuccess=${result.parseSuccess}")
119
136
  return result
120
137
  }
121
138
  }
@@ -169,6 +186,7 @@ class CommandGenerator {
169
186
 
170
187
  return Command(
171
188
  cardType = cardType,
189
+ type = type,
172
190
  area = area,
173
191
  command = command,
174
192
  ignoreSafeChannel = ignoreSafeChannel,
@@ -66,6 +66,8 @@ class Connection(val isoDep: IsoDep, private val mCommandGenerator: CommandGener
66
66
  private var hasOpenSafeChannel: Boolean = false
67
67
  private var hasSetupPin: Boolean = false
68
68
  private var hasBackup: Boolean = false
69
+ private var pinStatusValid: Boolean = false
70
+ private var backupStatusValid: Boolean = false
69
71
  private var mCommandArea = CommandArea.None
70
72
 
71
73
  init {
@@ -224,8 +226,10 @@ class Connection(val isoDep: IsoDep, private val mCommandGenerator: CommandGener
224
226
  )
225
227
  val res = command.send(this)
226
228
  printLog(TAG, "<--- getBackupStatus end: ${res.getCode()} area:${mCommandArea}")
229
+ backupStatusValid = res.isSuccess() && !res.isEmptyData()
230
+ OneKeyLog.info("LiteCard", "stage=backup_state_read readSucceeded=$backupStatusValid hasBackup=${res.isSuccess() && res.data == "02"}")
227
231
 
228
- if (!res.isSuccess()) {
232
+ if (!backupStatusValid) {
229
233
  return false
230
234
  }
231
235
 
@@ -239,8 +243,10 @@ class Connection(val isoDep: IsoDep, private val mCommandGenerator: CommandGener
239
243
  )
240
244
  val res = command.send(this)
241
245
  printLog(TAG, "<--- getPinStatus end: ${res.getCode()} area:${mCommandArea}")
246
+ pinStatusValid = res.isSuccess() && !res.isEmptyData()
247
+ OneKeyLog.info("LiteCard", "stage=pin_state_read readSucceeded=$pinStatusValid isNewCard=${res.isSuccess() && res.data == "02"}")
242
248
 
243
- if (!res.isSuccess()) {
249
+ if (!pinStatusValid) {
244
250
  return false
245
251
  }
246
252
 
@@ -298,8 +304,10 @@ class Connection(val isoDep: IsoDep, private val mCommandGenerator: CommandGener
298
304
  }
299
305
 
300
306
  loadPinStatus()
307
+ if (!pinStatusValid) throw NFCExceptions.ConnectionFailException()
301
308
  if (mCardType == AppleCardType.V2) {
302
309
  loadBackupStatus()
310
+ if (!backupStatusValid) throw NFCExceptions.ConnectionFailException()
303
311
  } else {
304
312
  hasBackup = hasSetupPin
305
313
  }
@@ -8,6 +8,28 @@
8
8
  #import "OKLiteCommandTool.h"
9
9
  #import "OKNFCBridge.h"
10
10
  #import "OKNFCUtility.h"
11
+ #import "LCLogger.h"
12
+
13
+ static NSString *OKLiteCommandName(OKLiteCommand command) {
14
+ switch (command) {
15
+ case OKLiteCommandSelectSecure: return @"select_secure";
16
+ case OKLiteCommandSelectBackup: return @"select_backup";
17
+ case OKLiteCommandGetCardSN: return @"get_serial";
18
+ case OKLiteCommandGetCardCert: return @"get_certificate";
19
+ case OKLiteCommandGetBackupStatus: return @"get_backup_status";
20
+ case OKLiteCommandGetPINStatus: return @"get_pin_status";
21
+ case OKLiteCommandSetPIN: return @"set_pin";
22
+ case OKLiteCommandChangePIN: return @"change_pin";
23
+ case OKLiteCommandVerifyPIN: return @"verify_pin";
24
+ case OKLiteCommandImportMnemonic: return @"backup_data";
25
+ case OKLiteCommandExportMnemonic: return @"export_data";
26
+ case OKLiteCommandWipeCard: return @"reset_card";
27
+ case OKLiteCommandPinRTL: return @"get_pin_retry_count";
28
+ case OKLiteCommandOpenChannel_1: return @"verify_certificate";
29
+ case OKLiteCommandOpenChannel_2: return @"verify_auth_data";
30
+ }
31
+ return @"unknown";
32
+ }
11
33
 
12
34
  @implementation OKLiteCommandTool
13
35
 
@@ -15,8 +37,15 @@
15
37
  modal:(OKLiteCommandModal *)modal
16
38
  completionHandler:(void(^)(NSData *responseData, uint8_t sw1, uint8_t sw2, NSError * _Nullable error, NSString *parseRespon))completionHandler {
17
39
 
40
+ static NSUInteger nextCommandID = 0;
41
+ NSUInteger commandID;
42
+ @synchronized (OKLiteCommandTool.class) { commandID = ++nextCommandID; }
43
+ NSString *command = OKLiteCommandName(modal.command);
44
+ [LCLogger info:[NSString stringWithFormat:@"commandID=%lu command=%@ stage=send buildSucceeded=%d parseRequested=%d", (unsigned long)commandID, command, apdu != nil, modal.parseResp]];
18
45
  id<NFCISO7816Tag> tag = [self.delegate getNFCsessionTag];
19
46
  [tag sendCommandAPDU:apdu completionHandler:^(NSData *responseData, uint8_t sw1, uint8_t sw2, NSError *error) {
47
+ uint8_t rawSW1 = sw1;
48
+ uint8_t rawSW2 = sw2;
20
49
  NSString *parseRespon = nil;
21
50
  if (modal.parseResp) {
22
51
  parseRespon = [OKNFCBridge parseSafeAPDUResponse:responseData sw1:sw1 sw2:sw2];
@@ -25,6 +54,11 @@
25
54
  }
26
55
  }
27
56
 
57
+ BOOL coreNFCError = [error.domain isEqualToString:NFCErrorDomain];
58
+ [LCLogger info:[NSString stringWithFormat:@"commandID=%lu command=%@ stage=response rawSW1=%u rawSW2=%u effectiveSW1=%u effectiveSW2=%u responseDataBytes=%lu parseRequested=%d parsePresent=%d transportError=%d coreNFCError=%d errorCode=%ld", (unsigned long)commandID, command, rawSW1, rawSW2, sw1, sw2, (unsigned long)responseData.length, modal.parseResp, parseRespon != nil, error != nil, coreNFCError, (long)error.code]];
59
+ if (modal.command == OKLiteCommandGetBackupStatus || modal.command == OKLiteCommandGetPINStatus) {
60
+ [LCLogger info:[NSString stringWithFormat:@"commandID=%lu command=%@ stage=state_read readSucceeded=%d", (unsigned long)commandID, command, error == nil && sw1 == OKNFC_SW1_OK && responseData.length > 0]];
61
+ }
28
62
  [OKNFCUtility logAPDU:modal.desc response:responseData sw1:sw1 sw2:sw2 error:error];
29
63
  if (completionHandler) {
30
64
  completionHandler(responseData,sw1,sw2,error,parseRespon);
@@ -64,6 +64,7 @@
64
64
  JUB_UINT16 wRet = 0;
65
65
  JUB_CHAR_PTR pDecResp = nullptr;
66
66
  rv = JUB_GPC_ParseSafeAPDUResponse(c_data ,&wRet, &pDecResp);
67
+ [LCLogger info:[NSString stringWithFormat:@"stage=parse_safe_response parseReturnCode=%lu parsedSW=%u parsePresent=%d", (unsigned long)rv, wRet, pDecResp != nullptr]];
67
68
  if (JUBR_OK != rv) {
68
69
  return nil;
69
70
  }
@@ -98,6 +98,7 @@
98
98
 
99
99
  - (BOOL)syncLiteInfo {
100
100
 
101
+ self.status = OKNFCLiteStatusError;
101
102
  OKNFCLiteStatus status = OKNFCLiteStatusError;
102
103
  self.pinRTL = 0;
103
104
  NSUInteger PinStatus = OKNFC_PIN_ERROR;
@@ -112,6 +113,11 @@
112
113
  return NO;
113
114
  }
114
115
  PinStatus = [self getPINStatus];
116
+ [LCLogger info:[NSString stringWithFormat:@"stage=pin_state_read readSucceeded=%d", PinStatus != OKNFC_PIN_ERROR]];
117
+ if (PinStatus == OKNFC_PIN_ERROR) {
118
+ self.status = OKNFCLiteStatusError;
119
+ return NO;
120
+ }
115
121
  status = PinStatus == OKNFC_PIN_UNSET ? OKNFCLiteStatusNewCard : OKNFCLiteStatusActivated;
116
122
  self.status = status;
117
123
  self.pinRTL = PinStatus == OKNFC_PIN_UNSET ? 10 : PinStatus;
@@ -489,7 +495,7 @@
489
495
  [self.commandTool sendCommandWithAPDU:[modal buildAPDU]
490
496
  modal:modal
491
497
  completionHandler:^(NSData * _Nonnull responseData, uint8_t sw1, uint8_t sw2, NSError * _Nullable error, NSString * _Nonnull parseRespon) {
492
- if (sw1 != OKNFC_SW1_OK) {
498
+ if (error != nil || sw1 != OKNFC_SW1_OK || responseData.length == 0) {
493
499
  [LCLogger error:@"获取 PIN 状态失败"];
494
500
  dispatch_semaphore_signal(sema);
495
501
  return;
@@ -501,12 +507,13 @@
501
507
  return;
502
508
  } else {
503
509
  OKLiteCommandModal *modal2 = [[OKLiteCommandModal alloc] initWithCommand:OKLiteCommandPinRTL version:self.version];
504
- [self.commandTool sendCommandWithAPDU:[modal2 buildAPDU] modal:modal completionHandler:^(NSData * _Nonnull responseData, uint8_t sw1, uint8_t sw2, NSError * _Nullable error, NSString * _Nonnull parseRespon) {
505
- if (sw1 == OKNFC_SW1_OK) {
506
- unsigned int outVal;
510
+ [self.commandTool sendCommandWithAPDU:[modal2 buildAPDU] modal:modal2 completionHandler:^(NSData * _Nonnull responseData, uint8_t sw1, uint8_t sw2, NSError * _Nullable error, NSString * _Nonnull parseRespon) {
511
+ if (error == nil && sw1 == OKNFC_SW1_OK && responseData.length > 0) {
512
+ unsigned int outVal = 0;
507
513
  NSScanner* scanner = [NSScanner scannerWithString:responseData.toHexString];
508
- [scanner scanHexInt:&outVal];
509
- pinStatus = outVal;
514
+ if ([scanner scanHexInt:&outVal]) {
515
+ pinStatus = outVal;
516
+ }
510
517
  }
511
518
  dispatch_semaphore_signal(sema);
512
519
  }];
@@ -30,7 +30,7 @@
30
30
 
31
31
  - (void)reset:(ResetCallback)callBack;
32
32
 
33
- - (void)setMnemonic:(NSString *)mnemonic withPin:(NSString *)pin overwrite:(BOOL)overwrite complete:(SetMnemonicCallback)complete;
33
+ - (void)setMnemonic:(NSString *)mnemonic withPin:(NSString *)pin overwrite:(BOOL)overwrite expectedSerial:(NSString * _Nullable)expectedSerial complete:(SetMnemonicCallback)complete;
34
34
 
35
35
  - (void)getMnemonicWithPin:(NSString *)pin complete:(GetMnemonicCallback)complete;
36
36
 
@@ -37,6 +37,7 @@
37
37
  @property (nonatomic, copy) NSString *pin;
38
38
  @property (nonatomic, copy) NSString *neoPin;
39
39
  @property (nonatomic, copy) NSString *exportMnemonic;
40
+ @property (nonatomic, copy) NSString *expectedSerial;
40
41
  @property (nonatomic, assign) BOOL certVerified;
41
42
  @property (nonatomic, assign) OKNFCLiteApp selectNFCApp;
42
43
  @property (nonatomic, strong) OKLiteV1 *lite;
@@ -132,6 +133,7 @@
132
133
  } break;
133
134
  case OKNFCLiteSessionTypeSetMnemonic:
134
135
  case OKNFCLiteSessionTypeSetMnemonicForce: {
136
+ self.expectedSerial = nil;
135
137
  SetMnemonicCallback callback = [self takeCompletionForKey:kSetMnemonicBlock];
136
138
  if (callback) {
137
139
  callback(self.lite, asCancel ? OKNFCLiteSetMncStatusCancel : OKNFCLiteSetMncStatusError);
@@ -274,6 +276,7 @@
274
276
  - (void)setMnemonic:(NSString *)mnemonic
275
277
  withPin:(NSString *)pin
276
278
  overwrite:(BOOL)overwrite
279
+ expectedSerial:(NSString * _Nullable)expectedSerial
277
280
  complete:(SetMnemonicCallback)complete {
278
281
 
279
282
  if (pin.length != OKNFC_PIN_LENGTH) {
@@ -282,6 +285,7 @@
282
285
  }
283
286
  self.pin = pin;
284
287
  self.exportMnemonic = mnemonic;
288
+ self.expectedSerial = expectedSerial;
285
289
  if(overwrite) {
286
290
  // 写入强制覆盖
287
291
  self.sessionType = OKNFCLiteSessionTypeSetMnemonicForce;
@@ -296,9 +300,21 @@
296
300
  - (void)_setMnemonic:(BOOL)force {
297
301
  NSString *mnemonic = self.exportMnemonic;
298
302
  NSString *pin = self.pin;
303
+ NSString *expectedSerial = self.expectedSerial;
304
+ self.expectedSerial = nil;
299
305
  // Clear sensitive data from properties immediately
300
306
  self.exportMnemonic = nil;
301
307
  self.pin = nil;
308
+ if (expectedSerial != nil) {
309
+ BOOL infoValid = [self.lite syncLiteInfo];
310
+ if (!infoValid || ![expectedSerial isEqualToString:self.lite.SN]) {
311
+ [self logSessionStage:infoValid ? @"identity_mismatch" : @"identity_read_failed" details:@"operation=setMnemonic"];
312
+ SetMnemonicCallback callback = [self takeCompletionForKey:kSetMnemonicBlock];
313
+ [self endNFCSessionWithError:YES];
314
+ if (callback) callback(self.lite, infoValid ? OKNFCLiteSetMncStatusSNNotMatch : OKNFCLiteSetMncStatusError);
315
+ return;
316
+ }
317
+ }
302
318
  __weak typeof(self) weakSelf = self;
303
319
  [self.lite setMnemonic:mnemonic withPin:pin overwrite:force complete:^(OKLiteV1 *lite, OKNFCLiteSetMncStatus status) {
304
320
  SetMnemonicCallback callback = [weakSelf takeCompletionForKey:kSetMnemonicBlock];
@@ -97,12 +97,12 @@ static RCTResponseSenderBlock OKLiteCallbackOnce(NSString *operation, RCTRespons
97
97
  }
98
98
  }
99
99
 
100
- - (void)setMnemonic:(NSString *)mnemonic pwd:(NSString *)pwd overwrite:(BOOL)overwrite callback:(RCTResponseSenderBlock)callBack
100
+ - (void)setMnemonic:(NSString *)mnemonic pwd:(NSString *)pwd overwrite:(BOOL)overwrite expectedSerial:(NSString * _Nullable)expectedSerial callback:(RCTResponseSenderBlock)callBack
101
101
  {
102
102
  callBack = OKLiteCallbackOnce(@"setMnemonic", callBack);
103
103
  if ([ReactNativeLiteCard checkSDKVaild:callBack]) {
104
104
  __block OKNFCManager *liteManager = [[OKNFCManager alloc] init];
105
- [liteManager setMnemonic:mnemonic withPin:pwd overwrite:overwrite complete:^(OKLiteV1 *lite, OKNFCLiteSetMncStatus status) {
105
+ [liteManager setMnemonic:mnemonic withPin:pwd overwrite:overwrite expectedSerial:expectedSerial complete:^(OKLiteV1 *lite, OKNFCLiteSetMncStatus status) {
106
106
  NSDictionary *cardInfo = [lite cardInfo];
107
107
  switch (status) {
108
108
  case OKNFCLiteSetMncStatusSuccess:
@@ -26,9 +26,9 @@ class OnekeyLite {
26
26
  OKLiteManager.checkNFCPermission(this.convertToPromise(resolve));
27
27
  });
28
28
  }
29
- setMnemonic(mnemonic, pwd, overwrite = false) {
29
+ setMnemonic(mnemonic, pwd, overwrite = false, expectedSerial) {
30
30
  return new Promise(resolve => {
31
- OKLiteManager.setMnemonic(mnemonic, pwd, overwrite, this.convertToPromise(resolve));
31
+ OKLiteManager.setMnemonic(mnemonic, pwd, overwrite, expectedSerial ?? null, this.convertToPromise(resolve));
32
32
  });
33
33
  }
34
34
  getMnemonicWithPin(pwd) {
@@ -45,7 +45,7 @@ type KeyValuePair = {
45
45
  export interface Spec extends TurboModule {
46
46
  getLiteInfo(callback: (error: CallbackError | null, data: CardInfo | null, cardInfo: CardInfo | null) => void): void;
47
47
  checkNFCPermission(callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
48
- setMnemonic(mnemonic: string, pwd: string, overwrite: boolean, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
48
+ setMnemonic(mnemonic: string, pwd: string, overwrite: boolean, expectedSerial: string | null, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
49
49
  getMnemonicWithPin(pwd: string, callback: (error: CallbackError | null, data: string | null, cardInfo: CardInfo | null) => void): void;
50
50
  changePin(oldPin: string, newPin: string, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
51
51
  reset(callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
@@ -9,7 +9,7 @@ declare class OnekeyLite {
9
9
  addAccordListener(): import("react-native").EventSubscription;
10
10
  getLiteInfo(): Promise<PromiseResult<CardInfo>>;
11
11
  checkNFCPermission(): Promise<PromiseResult<boolean>>;
12
- setMnemonic(mnemonic: string, pwd: string, overwrite?: boolean): Promise<PromiseResult<boolean>>;
12
+ setMnemonic(mnemonic: string, pwd: string, overwrite?: boolean, expectedSerial?: string): Promise<PromiseResult<boolean>>;
13
13
  getMnemonicWithPin(pwd: string): Promise<PromiseResult<string>>;
14
14
  changePin(oldPin: string, newPin: string): Promise<PromiseResult<boolean>>;
15
15
  reset(): Promise<PromiseResult<boolean>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-lite-card",
3
- "version": "6.7.0-23",
3
+ "version": "6.7.0-24",
4
4
  "description": "OneKey Lite NFC card operations and connection events for React Native",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -72,6 +72,7 @@ export interface Spec extends TurboModule {
72
72
  mnemonic: string,
73
73
  pwd: string,
74
74
  overwrite: boolean,
75
+ expectedSerial: string | null,
75
76
  callback: (
76
77
  error: CallbackError | null,
77
78
  data: boolean | null,
package/src/index.tsx CHANGED
@@ -39,12 +39,18 @@ class OnekeyLite {
39
39
  });
40
40
  }
41
41
 
42
- setMnemonic(mnemonic: string, pwd: string, overwrite = false) {
42
+ setMnemonic(
43
+ mnemonic: string,
44
+ pwd: string,
45
+ overwrite = false,
46
+ expectedSerial?: string
47
+ ) {
43
48
  return new Promise<PromiseResult<boolean>>((resolve) => {
44
49
  OKLiteManager.setMnemonic(
45
50
  mnemonic,
46
51
  pwd,
47
52
  overwrite,
53
+ expectedSerial ?? null,
48
54
  this.convertToPromise(resolve)
49
55
  );
50
56
  });