Mnemon.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Module\App;
  3. use App\Module\Ulogic\Enum\WALLET_ADDRESS_TYPE;
  4. use App\Module\Ulogic\Model\WalletAddress;
  5. use App\Module\Ulogic\Services\UserRelationService;
  6. use App\Module\User\Model\User;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. use UCore\Exception\ValidateException;
  10. /**
  11. * 助记词
  12. */
  13. class Mnemon
  14. {
  15. const KEY = 'INIT_WORD_';
  16. const TTL = 86400;
  17. /**
  18. * @param int $wordCount
  19. * @return object|\FurqanSiddiqui\BIP39\Mnemonic
  20. * @throws \FurqanSiddiqui\BIP39\Exception\Bip39EntropyException
  21. * @throws \FurqanSiddiqui\BIP39\Exception\Bip39MnemonicException
  22. * @throws \Random\RandomException
  23. * 生成助记词
  24. */
  25. public static function generate(int $userId): object
  26. {
  27. // 生成助记词
  28. $mnemonic = \FurqanSiddiqui\BIP39\BIP39::fromRandom(
  29. \FurqanSiddiqui\BIP39\Language\English::getInstance(),
  30. wordCount: 12
  31. );
  32. // 存入缓存
  33. $key = self::KEY . $userId;
  34. Cache::set($key, $mnemonic->entropy, self::TTL);
  35. return $mnemonic;
  36. }
  37. /**
  38. * @param $word
  39. * @param $userId
  40. * @param bool $isRegister
  41. * @return \FurqanSiddiqui\BIP39\Mnemonic|string
  42. * @throws \FurqanSiddiqui\BIP39\Exception\Bip39MnemonicException
  43. * 验证助记词
  44. */
  45. public static function wordsToMnemonic($word = '', $userId = 0, $isRegister = true)
  46. {
  47. $word = explode(',', $word);
  48. $mnemonic = \FurqanSiddiqui\BIP39\BIP39::fromWords(
  49. $word,
  50. \FurqanSiddiqui\BIP39\Language\English::getInstance()
  51. );
  52. $userWordEntropy = $mnemonic->entropy;
  53. if ($isRegister) {
  54. $redisKey = self::KEY . $userId;
  55. if (!Cache::has($redisKey)) {
  56. throw new ValidateException(null,'助记词失效');
  57. }
  58. $cacheWordEntropy = Cache::get(self::KEY . $userId);
  59. }else{
  60. $cacheWordEntropy = User::getUserInfoByCondition('user_id',$userId)->password;
  61. }
  62. if ($userWordEntropy !== $cacheWordEntropy) {
  63. throw new ValidateException(null,'助记词验证失败');
  64. }
  65. // 不需要注册,返回true
  66. if (!$isRegister) {
  67. return true;
  68. }
  69. // 事务
  70. DB::beginTransaction();
  71. try {
  72. // 生成uraus地址
  73. $addStr = WalletAddress::createAddress();
  74. $walletAddress = '0xuraus' . $addStr;
  75. WalletAddress::createRow($userId, $walletAddress);
  76. // 写入user表数据
  77. User::updateByUserId($userId, 'password', $cacheWordEntropy);
  78. // 绑定用户关系
  79. UserRelationService::createRelation($userId);
  80. Db::commit();
  81. return true;
  82. } catch (\Exception $e) {
  83. DB::rollBack();
  84. return false;
  85. }
  86. }
  87. }